diff --git a/handwritten/bigquery-storage/.OwlBot.yaml b/handwritten/bigquery-storage/.OwlBot.yaml index e35546ed08db..7dc2a309c91f 100644 --- a/handwritten/bigquery-storage/.OwlBot.yaml +++ b/handwritten/bigquery-storage/.OwlBot.yaml @@ -1,10 +1,10 @@ -# Copyright 2021 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. # You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# 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, @@ -12,17 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -deep-preserve-regex: - - /owl-bot-staging/v1alpha2 - - /owl-bot-staging/v1beta2 - - -deep-remove-regex: - - /owl-bot-staging - deep-copy-regex: - - source: /google/cloud/bigquery/storage/(v.*)/.*-nodejs - dest: /owl-bot-staging/bigquery-storage/$1 - -begin-after-commit-hash: e0ea8b51f30e2ff6104abd1e4c8d1eb67078c86a + - source: /google/cloud/bigquery/storage/google-cloud-bigquery-storage-nodejs + dest: /owl-bot-staging/google-cloud-bigquery-storage +api-name: storage \ No newline at end of file diff --git a/handwritten/bigquery-storage/.jsdoc.js b/handwritten/bigquery-storage/.jsdoc.js index a278e26223f0..e0a978946159 100644 --- a/handwritten/bigquery-storage/.jsdoc.js +++ b/handwritten/bigquery-storage/.jsdoc.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -40,7 +40,7 @@ module.exports = { includePattern: '\\.js$' }, templates: { - copyright: 'Copyright 2025 Google LLC', + copyright: 'Copyright 2026 Google LLC', includeDate: false, sourceFiles: false, systemName: '@google-cloud/bigquery-storage', diff --git a/handwritten/bigquery-storage/README.md b/handwritten/bigquery-storage/README.md index 5e9efa548ee0..bfe59af0b8fe 100644 --- a/handwritten/bigquery-storage/README.md +++ b/handwritten/bigquery-storage/README.md @@ -1,129 +1,22 @@ [//]: # "This README.md file is auto-generated, all changes to this file will be lost." -[//]: # "To regenerate it, use `python -m synthtool`." +[//]: # "The comments you see below are used to generate those parts of the template in later states." Google Cloud Platform logo -# [Google BigQuery Storage: Node.js Client](https://github.com/googleapis/nodejs-bigquery-storage) +# [BigQuery Storage API: Nodejs Client][homepage] -[![release level](https://img.shields.io/badge/release%20level-stable-brightgreen.svg?style=flat)](https://cloud.google.com/terms/launch-stages) -[![npm version](https://img.shields.io/npm/v/@google-cloud/bigquery-storage.svg)](https://www.npmjs.org/package/@google-cloud/bigquery-storage) - - - - -> Node.js idiomatic client for [BigQuery Storage](https://cloud.google.com/bigquery). - -The BigQuery Storage product is divided into two major APIs: Write and Read API. -BigQuery Storage API does not provide functionality related to managing BigQuery -resources such as datasets, jobs, or tables. - -The BigQuery Storage Write API is a unified data-ingestion API for BigQuery. -It combines streaming ingestion and batch loading into a single high-performance API. -You can use the Storage Write API to stream records into BigQuery in real time or -to batch process an arbitrarily large number of records and commit them in a single -atomic operation. - -Read more in our [introduction guide](https://cloud.google.com/bigquery/docs/write-api). - -Using a system provided default stream, this code sample demonstrates using the -schema of a destination stream/table to construct a writer, and send several -batches of row data to the table. - -```javascript -const {adapt, managedwriter} = require('@google-cloud/bigquery-storage'); -const {WriterClient, JSONWriter} = managedwriter; - -async function appendJSONRowsDefaultStream() { - const projectId = 'my_project'; - const datasetId = 'my_dataset'; - const tableId = 'my_table'; - - const destinationTable = `projects/${projectId}/datasets/${datasetId}/tables/${tableId}`; - const writeClient = new WriterClient({projectId}); - - try { - const writeStream = await writeClient.getWriteStream({ - streamId: `${destinationTable}/streams/_default`, - view: 'FULL' - }); - const protoDescriptor = adapt.convertStorageSchemaToProto2Descriptor( - writeStream.tableSchema, - 'root' - ); - - const connection = await writeClient.createStreamConnection({ - streamId: managedwriter.DefaultStream, - destinationTable, - }); - const streamId = connection.getStreamId(); - - const writer = new JSONWriter({ - streamId, - connection, - protoDescriptor, - }); - - let rows = []; - const pendingWrites = []; - - // Row 1 - let row = { - row_num: 1, - customer_name: 'Octavia', - }; - rows.push(row); - - // Row 2 - row = { - row_num: 2, - customer_name: 'Turing', - }; - rows.push(row); - - // Send batch. - let pw = writer.appendRows(rows); - pendingWrites.push(pw); - - rows = []; - - // Row 3 - row = { - row_num: 3, - customer_name: 'Bell', - }; - rows.push(row); - - // Send batch. - pw = writer.appendRows(rows); - pendingWrites.push(pw); - - const results = await Promise.all( - pendingWrites.map(pw => pw.getResult()) - ); - console.log('Write results:', results); - } catch (err) { - console.log(err); - } finally { - writeClient.close(); - } -} -``` - -The BigQuery Storage Read API provides fast access to BigQuery-managed storage by -using an gRPC based protocol. When you use the Storage Read API, structured data is -sent over the wire in a binary serialization format. This allows for additional -parallelism among multiple consumers for a set of results. +[//]: # "releaseLevel" -Read more how to [use the BigQuery Storage Read API](https://cloud.google.com/bigquery/docs/reference/storage). +[![npm version](https://img.shields.io/npm/v/@google-cloud/bigquery-storage.svg)](https://www.npmjs.org/package/@google-cloud/bigquery-storage) -See sample code on the [Quickstart section](#quickstart). +BigQuery Storage API client for Node.js +[//]: # "partials.introduction" A comprehensive list of changes in each version may be found in -[the CHANGELOG](https://github.com/googleapis/nodejs-bigquery-storage/blob/main/CHANGELOG.md). +[the CHANGELOG][homepage_changelog]. -* [Google BigQuery Storage Node.js Client API Reference][client-docs] -* [Google BigQuery Storage Documentation][product-docs] -* [github.com/googleapis/nodejs-bigquery-storage](https://github.com/googleapis/nodejs-bigquery-storage) +* [BigQuery Storage API Nodejs Client API Reference](https://cloud.google.com/nodejs/docs/reference/storage/latest) +* [BigQuery Storage API Documentation](https://cloud.google.com/bigquery/docs/reference/storage/) Read more about the client libraries for Cloud APIs, including the older Google APIs Client Libraries, in [Client Libraries Explained][explained]. @@ -132,178 +25,35 @@ Google APIs Client Libraries, in [Client Libraries Explained][explained]. **Table of contents:** - * [Quickstart](#quickstart) * [Before you begin](#before-you-begin) * [Installing the client library](#installing-the-client-library) - * [Using the client library](#using-the-client-library) -* [Samples](#samples) + * [Versioning](#versioning) * [Contributing](#contributing) * [License](#license) ## Quickstart - ### Before you begin 1. [Select or create a Cloud Platform project][projects]. 1. [Enable billing for your project][billing]. -1. [Enable the Google BigQuery Storage API][enable_api]. +1. [Enable the BigQuery Storage API API][enable_api]. 1. [Set up authentication][auth] so you can access the API from your local workstation. - ### Installing the client library ```bash npm install @google-cloud/bigquery-storage ``` - -### Using the client library - -```javascript - -// The read stream contains blocks of Avro-encoded bytes. We use the -// 'avsc' library to decode these blocks. Install avsc with the following -// command: npm install avsc -const avro = require('avsc'); - -// See reference documentation at -// https://cloud.google.com/bigquery/docs/reference/storage -const {BigQueryReadClient} = require('@google-cloud/bigquery-storage'); - -const client = new BigQueryReadClient(); - -async function bigqueryStorageQuickstart() { - // Get current project ID. The read session is created in this project. - // This project can be different from that which contains the table. - const myProjectId = await client.getProjectId(); - - // This example reads baby name data from the public datasets. - const projectId = 'bigquery-public-data'; - const datasetId = 'usa_names'; - const tableId = 'usa_1910_current'; - - const tableReference = `projects/${projectId}/datasets/${datasetId}/tables/${tableId}`; - - const parent = `projects/${myProjectId}`; - - /* We limit the output columns to a subset of those allowed in the table, - * and set a simple filter to only report names from the state of - * Washington (WA). - */ - const readOptions = { - selectedFields: ['name', 'number', 'state'], - rowRestriction: 'state = "WA"', - }; - - let tableModifiers = null; - const snapshotSeconds = 0; - - // Set a snapshot time if it's been specified. - if (snapshotSeconds > 0) { - tableModifiers = {snapshotTime: {seconds: snapshotSeconds}}; - } - - // API request. - const request = { - parent, - readSession: { - table: tableReference, - // This API can also deliver data serialized in Apache Arrow format. - // This example leverages Apache Avro. - dataFormat: 'AVRO', - readOptions, - tableModifiers, - }, - }; - - const [session] = await client.createReadSession(request); - - const schema = JSON.parse(session.avroSchema.schema); - - const avroType = avro.Type.forSchema(schema); - - /* The offset requested must be less than the last - * row read from ReadRows. Requesting a larger offset is - * undefined. - */ - let offset = 0; - - const readRowsRequest = { - // Required stream name and optional offset. Offset requested must be less than - // the last row read from readRows(). Requesting a larger offset is undefined. - readStream: session.streams[0].name, - offset, - }; - - const names = new Set(); - const states = []; - - /* We'll use only a single stream for reading data from the table. Because - * of dynamic sharding, this will yield all the rows in the table. However, - * if you wanted to fan out multiple readers you could do so by having a - * reader process each individual stream. - */ - client - .readRows(readRowsRequest) - .on('error', console.error) - .on('data', data => { - offset = data.avroRows.serializedBinaryRows.offset; - - try { - // Decode all rows in buffer - let pos; - do { - const decodedData = avroType.decode( - data.avroRows.serializedBinaryRows, - pos, - ); - - if (decodedData.value) { - names.add(decodedData.value.name); - - if (!states.includes(decodedData.value.state)) { - states.push(decodedData.value.state); - } - } - - pos = decodedData.offset; - } while (pos > 0); - } catch (error) { - console.log(error); - } - }) - .on('end', () => { - console.log(`Got ${names.size} unique names in states: ${states}`); - console.log(`Last offset: ${offset}`); - }); -} - -``` - - +[//]: # "partials.body" ## Samples -Samples are in the [`samples/`](https://github.com/googleapis/nodejs-bigquery-storage/tree/main/samples) directory. Each sample's `README.md` has instructions for running its sample. - -| Sample | Source Code | Try it | -| --------------------------- | --------------------------------- | ------ | -| Append_rows_buffered | [source code](https://github.com/googleapis/nodejs-bigquery-storage/blob/main/samples/append_rows_buffered.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-bigquery-storage&page=editor&open_in_editor=samples/append_rows_buffered.js,samples/README.md) | -| Append_rows_json_writer_committed | [source code](https://github.com/googleapis/nodejs-bigquery-storage/blob/main/samples/append_rows_json_writer_committed.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-bigquery-storage&page=editor&open_in_editor=samples/append_rows_json_writer_committed.js,samples/README.md) | -| Append_rows_json_writer_default | [source code](https://github.com/googleapis/nodejs-bigquery-storage/blob/main/samples/append_rows_json_writer_default.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-bigquery-storage&page=editor&open_in_editor=samples/append_rows_json_writer_default.js,samples/README.md) | -| Append_rows_pending | [source code](https://github.com/googleapis/nodejs-bigquery-storage/blob/main/samples/append_rows_pending.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-bigquery-storage&page=editor&open_in_editor=samples/append_rows_pending.js,samples/README.md) | -| Append_rows_proto2 | [source code](https://github.com/googleapis/nodejs-bigquery-storage/blob/main/samples/append_rows_proto2.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-bigquery-storage&page=editor&open_in_editor=samples/append_rows_proto2.js,samples/README.md) | -| Append_rows_table_to_proto2 | [source code](https://github.com/googleapis/nodejs-bigquery-storage/blob/main/samples/append_rows_table_to_proto2.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-bigquery-storage&page=editor&open_in_editor=samples/append_rows_table_to_proto2.js,samples/README.md) | -| Customer_record_pb | [source code](https://github.com/googleapis/nodejs-bigquery-storage/blob/main/samples/customer_record_pb.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-bigquery-storage&page=editor&open_in_editor=samples/customer_record_pb.js,samples/README.md) | -| BigQuery Storage Quickstart | [source code](https://github.com/googleapis/nodejs-bigquery-storage/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-bigquery-storage&page=editor&open_in_editor=samples/quickstart.js,samples/README.md) | -| Sample_data_pb | [source code](https://github.com/googleapis/nodejs-bigquery-storage/blob/main/samples/sample_data_pb.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-bigquery-storage&page=editor&open_in_editor=samples/sample_data_pb.js,samples/README.md) | +Samples are in the [`samples/`][homepage_samples] directory. Each sample's `README.md` has instructions for running its sample. - - -The [Google BigQuery Storage Node.js Client API Reference][client-docs] documentation -also contains samples. +[//]: # "samples" ## Supported Node.js Versions @@ -330,42 +80,29 @@ for versions compatible with Node.js 8. This library follows [Semantic Versioning](http://semver.org/). - - -This library is considered to be **stable**. The code surface will not change in backwards-incompatible ways -unless absolutely necessary (e.g. because of critical security issues) or with -an extensive deprecation period. Issues and requests against **stable** libraries -are addressed with the highest priority. - - - - - - More Information: [Google Cloud Platform Launch Stages][launch_stages] [launch_stages]: https://cloud.google.com/terms/launch-stages ## Contributing -Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/nodejs-bigquery-storage/blob/main/CONTRIBUTING.md). +Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/google-cloud-node/blob/main/CONTRIBUTING.md). -Please note that this `README.md`, the `samples/README.md`, +Please note that this `README.md` and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`) -are generated from a central template. To edit one of these files, make an edit -to its templates in -[directory](https://github.com/googleapis/synthtool). +are generated from a central template. ## License Apache Version 2.0 -See [LICENSE](https://github.com/googleapis/nodejs-bigquery-storage/blob/main/LICENSE) +See [LICENSE](https://github.com/googleapis/google-cloud-node/blob/main/LICENSE) -[client-docs]: https://cloud.google.com/nodejs/docs/reference/bigquery-storage/latest -[product-docs]: https://cloud.google.com/bigquery/docs/reference/storage [shell_img]: https://gstatic.com/cloudssh/images/open-btn.png [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=bigquerystorage.googleapis.com -[auth]: https://cloud.google.com/docs/authentication/external/set-up-adc-local \ No newline at end of file +[auth]: https://cloud.google.com/docs/authentication/external/set-up-adc-local +[homepage_samples]: https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-bigquery-storage/samples +[homepage_changelog]: https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-bigquery-storage/CHANGELOG.md +[homepage]: https://github.com/googleapis/google-cloud-node/blob/main/packages/google-cloud-bigquery-storage diff --git a/handwritten/bigquery-storage/protos/google/cloud/bigquery/storage/v1beta2/arrow.proto b/handwritten/bigquery-storage/protos/google/cloud/bigquery/storage/v1beta2/arrow.proto new file mode 100644 index 000000000000..7d17d559e244 --- /dev/null +++ b/handwritten/bigquery-storage/protos/google/cloud/bigquery/storage/v1beta2/arrow.proto @@ -0,0 +1,57 @@ +// 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.cloud.bigquery.storage.v1beta2; + +option go_package = "cloud.google.com/go/bigquery/storage/apiv1beta2/storagepb;storagepb"; +option java_multiple_files = true; +option java_outer_classname = "ArrowProto"; +option java_package = "com.google.cloud.bigquery.storage.v1beta2"; + +// Arrow schema as specified in +// https://arrow.apache.org/docs/python/api/datatypes.html +// and serialized to bytes using IPC: +// https://arrow.apache.org/docs/format/Columnar.html#serialization-and-interprocess-communication-ipc +// +// See code samples on how this message can be deserialized. +message ArrowSchema { + // IPC serialized Arrow schema. + bytes serialized_schema = 1; +} + +// Arrow RecordBatch. +message ArrowRecordBatch { + // IPC-serialized Arrow RecordBatch. + bytes serialized_record_batch = 1; +} + +// Contains options specific to Arrow Serialization. +message ArrowSerializationOptions { + // The IPC format to use when serializing Arrow streams. + enum Format { + // If unspecied the IPC format as of 0.15 release will be used. + FORMAT_UNSPECIFIED = 0; + + // Use the legacy IPC message format as of Apache Arrow Release 0.14. + ARROW_0_14 = 1; + + // Use the message format as of Apache Arrow Release 0.15. + ARROW_0_15 = 2; + } + + // The Arrow IPC format to use. + Format format = 1; +} diff --git a/handwritten/bigquery-storage/protos/google/cloud/bigquery/storage/v1beta2/avro.proto b/handwritten/bigquery-storage/protos/google/cloud/bigquery/storage/v1beta2/avro.proto new file mode 100644 index 000000000000..bd48a5cd0d80 --- /dev/null +++ b/handwritten/bigquery-storage/protos/google/cloud/bigquery/storage/v1beta2/avro.proto @@ -0,0 +1,35 @@ +// 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.cloud.bigquery.storage.v1beta2; + +option go_package = "cloud.google.com/go/bigquery/storage/apiv1beta2/storagepb;storagepb"; +option java_multiple_files = true; +option java_outer_classname = "AvroProto"; +option java_package = "com.google.cloud.bigquery.storage.v1beta2"; + +// Avro schema. +message AvroSchema { + // Json serialized schema, as described at + // https://avro.apache.org/docs/1.8.1/spec.html. + string schema = 1; +} + +// Avro rows. +message AvroRows { + // Binary serialized rows in a block. + bytes serialized_binary_rows = 1; +} diff --git a/handwritten/bigquery-storage/protos/google/cloud/bigquery/storage/v1beta2/protobuf.proto b/handwritten/bigquery-storage/protos/google/cloud/bigquery/storage/v1beta2/protobuf.proto new file mode 100644 index 000000000000..cdc77e7e6618 --- /dev/null +++ b/handwritten/bigquery-storage/protos/google/cloud/bigquery/storage/v1beta2/protobuf.proto @@ -0,0 +1,40 @@ +// 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.cloud.bigquery.storage.v1beta2; + +import "google/protobuf/descriptor.proto"; + +option go_package = "cloud.google.com/go/bigquery/storage/apiv1beta2/storagepb;storagepb"; +option java_multiple_files = true; +option java_outer_classname = "ProtoBufProto"; +option java_package = "com.google.cloud.bigquery.storage.v1beta2"; + +// ProtoSchema describes the schema of the serialized protocol buffer data rows. +message ProtoSchema { + // Descriptor for input message. The descriptor has to be self contained, + // including all the nested types, excepted for proto buffer well known types + // (https://developers.google.com/protocol-buffers/docs/reference/google.protobuf). + google.protobuf.DescriptorProto proto_descriptor = 1; +} + +message ProtoRows { + // A sequence of rows serialized as a Protocol Buffer. + // + // See https://developers.google.com/protocol-buffers/docs/overview for more + // information on deserializing this field. + repeated bytes serialized_rows = 1; +} diff --git a/handwritten/bigquery-storage/protos/google/cloud/bigquery/storage/v1beta2/storage.proto b/handwritten/bigquery-storage/protos/google/cloud/bigquery/storage/v1beta2/storage.proto new file mode 100644 index 000000000000..35fb37a8202c --- /dev/null +++ b/handwritten/bigquery-storage/protos/google/cloud/bigquery/storage/v1beta2/storage.proto @@ -0,0 +1,577 @@ +// 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.cloud.bigquery.storage.v1beta2; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/cloud/bigquery/storage/v1beta2/arrow.proto"; +import "google/cloud/bigquery/storage/v1beta2/avro.proto"; +import "google/cloud/bigquery/storage/v1beta2/protobuf.proto"; +import "google/cloud/bigquery/storage/v1beta2/stream.proto"; +import "google/cloud/bigquery/storage/v1beta2/table.proto"; +import "google/protobuf/timestamp.proto"; +import "google/protobuf/wrappers.proto"; +import "google/rpc/status.proto"; + +option go_package = "cloud.google.com/go/bigquery/storage/apiv1beta2/storagepb;storagepb"; +option java_multiple_files = true; +option java_outer_classname = "StorageProto"; +option java_package = "com.google.cloud.bigquery.storage.v1beta2"; + +// BigQuery Read API. +// +// The Read API can be used to read data from BigQuery. +// +// New code should use the v1 Read API going forward, if they don't use Write +// API at the same time. +service BigQueryRead { + option (google.api.default_host) = "bigquerystorage.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/bigquery," + "https://www.googleapis.com/auth/cloud-platform"; + + // Creates a new read session. A read session divides the contents of a + // BigQuery table into one or more streams, which can then be used to read + // data from the table. The read session also specifies properties of the + // data to be read, such as a list of columns or a push-down filter describing + // the rows to be returned. + // + // A particular row can be read by at most one stream. When the caller has + // reached the end of each stream in the session, then all the data in the + // table has been read. + // + // Data is assigned to each stream such that roughly the same number of + // rows can be read from each stream. Because the server-side unit for + // assigning data is collections of rows, the API does not guarantee that + // each stream will return the same number or rows. Additionally, the + // limits are enforced based on the number of pre-filtered rows, so some + // filters can lead to lopsided assignments. + // + // Read sessions automatically expire 6 hours after they are created and do + // not require manual clean-up by the caller. + rpc CreateReadSession(CreateReadSessionRequest) returns (ReadSession) { + option (google.api.http) = { + post: "/v1beta2/{read_session.table=projects/*/datasets/*/tables/*}" + body: "*" + }; + option (google.api.method_signature) = + "parent,read_session,max_stream_count"; + } + + // Reads rows from the stream in the format prescribed by the ReadSession. + // Each response contains one or more table rows, up to a maximum of 100 MiB + // per response; read requests which attempt to read individual rows larger + // than 100 MiB will fail. + // + // Each request also returns a set of stream statistics reflecting the current + // state of the stream. + rpc ReadRows(ReadRowsRequest) returns (stream ReadRowsResponse) { + option (google.api.http) = { + get: "/v1beta2/{read_stream=projects/*/locations/*/sessions/*/streams/*}" + }; + option (google.api.method_signature) = "read_stream,offset"; + } + + // Splits a given `ReadStream` into two `ReadStream` objects. These + // `ReadStream` objects are referred to as the primary and the residual + // streams of the split. The original `ReadStream` can still be read from in + // the same manner as before. Both of the returned `ReadStream` objects can + // also be read from, and the rows returned by both child streams will be + // the same as the rows read from the original stream. + // + // Moreover, the two child streams will be allocated back-to-back in the + // original `ReadStream`. Concretely, it is guaranteed that for streams + // original, primary, and residual, that original[0-j] = primary[0-j] and + // original[j-n] = residual[0-m] once the streams have been read to + // completion. + rpc SplitReadStream(SplitReadStreamRequest) + returns (SplitReadStreamResponse) { + option (google.api.http) = { + get: "/v1beta2/{name=projects/*/locations/*/sessions/*/streams/*}" + }; + } +} + +// BigQuery Write API. +// +// The Write API can be used to write data to BigQuery. +// +// +// The [google.cloud.bigquery.storage.v1 +// API](/bigquery/docs/reference/storage/rpc/google.cloud.bigquery.storage.v1) +// should be used instead of the v1beta2 API for BigQueryWrite operations. +service BigQueryWrite { + option deprecated = true; + option (google.api.default_host) = "bigquerystorage.googleapis.com"; + option (google.api.oauth_scopes) = + "https://www.googleapis.com/auth/bigquery," + "https://www.googleapis.com/auth/bigquery.insertdata," + "https://www.googleapis.com/auth/cloud-platform"; + + // Creates a write stream to the given table. + // Additionally, every table has a special COMMITTED stream named '_default' + // to which data can be written. This stream doesn't need to be created using + // CreateWriteStream. It is a stream that can be used simultaneously by any + // number of clients. Data written to this stream is considered committed as + // soon as an acknowledgement is received. + rpc CreateWriteStream(CreateWriteStreamRequest) returns (WriteStream) { + option deprecated = true; + option (google.api.http) = { + post: "/v1beta2/{parent=projects/*/datasets/*/tables/*}" + body: "write_stream" + }; + option (google.api.method_signature) = "parent,write_stream"; + } + + // Appends data to the given stream. + // + // If `offset` is specified, the `offset` is checked against the end of + // stream. The server returns `OUT_OF_RANGE` in `AppendRowsResponse` if an + // attempt is made to append to an offset beyond the current end of the stream + // or `ALREADY_EXISTS` if user provids an `offset` that has already been + // written to. User can retry with adjusted offset within the same RPC + // stream. If `offset` is not specified, append happens at the end of the + // stream. + // + // The response contains the offset at which the append happened. Responses + // are received in the same order in which requests are sent. There will be + // one response for each successful request. If the `offset` is not set in + // response, it means append didn't happen due to some errors. If one request + // fails, all the subsequent requests will also fail until a success request + // is made again. + // + // If the stream is of `PENDING` type, data will only be available for read + // operations after the stream is committed. + rpc AppendRows(stream AppendRowsRequest) returns (stream AppendRowsResponse) { + option deprecated = true; + option (google.api.http) = { + post: "/v1beta2/{write_stream=projects/*/datasets/*/tables/*/streams/*}" + body: "*" + }; + option (google.api.method_signature) = "write_stream"; + } + + // Gets a write stream. + rpc GetWriteStream(GetWriteStreamRequest) returns (WriteStream) { + option deprecated = true; + option (google.api.http) = { + post: "/v1beta2/{name=projects/*/datasets/*/tables/*/streams/*}" + body: "*" + }; + option (google.api.method_signature) = "name"; + } + + // Finalize a write stream so that no new data can be appended to the + // stream. Finalize is not supported on the '_default' stream. + rpc FinalizeWriteStream(FinalizeWriteStreamRequest) + returns (FinalizeWriteStreamResponse) { + option deprecated = true; + option (google.api.http) = { + post: "/v1beta2/{name=projects/*/datasets/*/tables/*/streams/*}" + body: "*" + }; + option (google.api.method_signature) = "name"; + } + + // Atomically commits a group of `PENDING` streams that belong to the same + // `parent` table. + // Streams must be finalized before commit and cannot be committed multiple + // times. Once a stream is committed, data in the stream becomes available + // for read operations. + rpc BatchCommitWriteStreams(BatchCommitWriteStreamsRequest) + returns (BatchCommitWriteStreamsResponse) { + option deprecated = true; + option (google.api.http) = { + get: "/v1beta2/{parent=projects/*/datasets/*/tables/*}" + }; + option (google.api.method_signature) = "parent"; + } + + // Flushes rows to a BUFFERED stream. + // If users are appending rows to BUFFERED stream, flush operation is + // required in order for the rows to become available for reading. A + // Flush operation flushes up to any previously flushed offset in a BUFFERED + // stream, to the offset specified in the request. + // Flush is not supported on the _default stream, since it is not BUFFERED. + rpc FlushRows(FlushRowsRequest) returns (FlushRowsResponse) { + option deprecated = true; + option (google.api.http) = { + post: "/v1beta2/{write_stream=projects/*/datasets/*/tables/*/streams/*}" + body: "*" + }; + option (google.api.method_signature) = "write_stream"; + } +} + +// Request message for `CreateReadSession`. +message CreateReadSessionRequest { + // Required. The request project that owns the session, in the form of + // `projects/{project_id}`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "cloudresourcemanager.googleapis.com/Project" + } + ]; + + // Required. Session to be created. + ReadSession read_session = 2 [(google.api.field_behavior) = REQUIRED]; + + // Max initial number of streams. If unset or zero, the server will + // provide a value of streams so as to produce reasonable throughput. Must be + // non-negative. The number of streams may be lower than the requested number, + // depending on the amount parallelism that is reasonable for the table. Error + // will be returned if the max count is greater than the current system + // max limit of 1,000. + // + // Streams must be read starting from offset 0. + int32 max_stream_count = 3; +} + +// Request message for `ReadRows`. +message ReadRowsRequest { + // Required. Stream to read rows from. + string read_stream = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "bigquerystorage.googleapis.com/ReadStream" + } + ]; + + // The offset requested must be less than the last row read from Read. + // Requesting a larger offset is undefined. If not specified, start reading + // from offset zero. + int64 offset = 2; +} + +// Information on if the current connection is being throttled. +message ThrottleState { + // How much this connection is being throttled. Zero means no throttling, + // 100 means fully throttled. + int32 throttle_percent = 1; +} + +// Estimated stream statistics for a given Stream. +message StreamStats { + message Progress { + // The fraction of rows assigned to the stream that have been processed by + // the server so far, not including the rows in the current response + // message. + // + // This value, along with `at_response_end`, can be used to interpolate + // the progress made as the rows in the message are being processed using + // the following formula: `at_response_start + (at_response_end - + // at_response_start) * rows_processed_from_response / rows_in_response`. + // + // Note that if a filter is provided, the `at_response_end` value of the + // previous response may not necessarily be equal to the + // `at_response_start` value of the current response. + double at_response_start = 1; + + // Similar to `at_response_start`, except that this value includes the + // rows in the current response. + double at_response_end = 2; + } + + // Represents the progress of the current stream. + Progress progress = 2; +} + +// Response from calling `ReadRows` may include row data, progress and +// throttling information. +message ReadRowsResponse { + // Row data is returned in format specified during session creation. + oneof rows { + // Serialized row data in AVRO format. + AvroRows avro_rows = 3; + + // Serialized row data in Arrow RecordBatch format. + ArrowRecordBatch arrow_record_batch = 4; + } + + // Number of serialized rows in the rows block. + int64 row_count = 6; + + // Statistics for the stream. + StreamStats stats = 2; + + // Throttling state. If unset, the latest response still describes + // the current throttling status. + ThrottleState throttle_state = 5; + + // The schema for the read. If read_options.selected_fields is set, the + // schema may be different from the table schema as it will only contain + // the selected fields. This schema is equivalent to the one returned by + // CreateSession. This field is only populated in the first ReadRowsResponse + // RPC. + oneof schema { + // Output only. Avro schema. + AvroSchema avro_schema = 7 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Arrow schema. + ArrowSchema arrow_schema = 8 [(google.api.field_behavior) = OUTPUT_ONLY]; + } +} + +// Request message for `SplitReadStream`. +message SplitReadStreamRequest { + // Required. Name of the stream to split. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "bigquerystorage.googleapis.com/ReadStream" + } + ]; + + // A value in the range (0.0, 1.0) that specifies the fractional point at + // which the original stream should be split. The actual split point is + // evaluated on pre-filtered rows, so if a filter is provided, then there is + // no guarantee that the division of the rows between the new child streams + // will be proportional to this fractional value. Additionally, because the + // server-side unit for assigning data is collections of rows, this fraction + // will always map to a data storage boundary on the server side. + double fraction = 2; +} + +message SplitReadStreamResponse { + // Primary stream, which contains the beginning portion of + // |original_stream|. An empty value indicates that the original stream can no + // longer be split. + ReadStream primary_stream = 1; + + // Remainder stream, which contains the tail of |original_stream|. An empty + // value indicates that the original stream can no longer be split. + ReadStream remainder_stream = 2; +} + +// Request message for `CreateWriteStream`. +message CreateWriteStreamRequest { + // Required. Reference to the table to which the stream belongs, in the format + // of `projects/{project}/datasets/{dataset}/tables/{table}`. + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { type: "bigquery.googleapis.com/Table" } + ]; + + // Required. Stream to be created. + WriteStream write_stream = 2 [(google.api.field_behavior) = REQUIRED]; +} + +// Request message for `AppendRows`. +message AppendRowsRequest { + // Proto schema and data. + message ProtoData { + // Proto schema used to serialize the data. + ProtoSchema writer_schema = 1; + + // Serialized row data in protobuf message format. + ProtoRows rows = 2; + } + + // Required. The stream that is the target of the append operation. This value + // must be specified for the initial request. If subsequent requests specify + // the stream name, it must equal to the value provided in the first request. + // To write to the _default stream, populate this field with a string in the + // format `projects/{project}/datasets/{dataset}/tables/{table}/_default`. + string write_stream = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "bigquerystorage.googleapis.com/WriteStream" + } + ]; + + // If present, the write is only performed if the next append offset is same + // as the provided value. If not present, the write is performed at the + // current end of stream. Specifying a value for this field is not allowed + // when calling AppendRows for the '_default' stream. + google.protobuf.Int64Value offset = 2; + + // Input rows. The `writer_schema` field must be specified at the initial + // request and currently, it will be ignored if specified in following + // requests. Following requests must have data in the same format as the + // initial request. + oneof rows { + // Rows in proto format. + ProtoData proto_rows = 4; + } + + // Id set by client to annotate its identity. Only initial request setting is + // respected. + string trace_id = 6; +} + +// Response message for `AppendRows`. +message AppendRowsResponse { + // AppendResult is returned for successful append requests. + message AppendResult { + // The row offset at which the last append occurred. The offset will not be + // set if appending using default streams. + google.protobuf.Int64Value offset = 1; + } + + oneof response { + // Result if the append is successful. + AppendResult append_result = 1; + + // Error returned when problems were encountered. If present, + // it indicates rows were not accepted into the system. + // Users can retry or continue with other append requests within the + // same connection. + // + // Additional information about error signalling: + // + // ALREADY_EXISTS: Happens when an append specified an offset, and the + // backend already has received data at this offset. Typically encountered + // in retry scenarios, and can be ignored. + // + // OUT_OF_RANGE: Returned when the specified offset in the stream is beyond + // the current end of the stream. + // + // INVALID_ARGUMENT: Indicates a malformed request or data. + // + // ABORTED: Request processing is aborted because of prior failures. The + // request can be retried if previous failure is addressed. + // + // INTERNAL: Indicates server side error(s) that can be retried. + google.rpc.Status error = 2; + } + + // If backend detects a schema update, pass it to user so that user can + // use it to input new type of message. It will be empty when no schema + // updates have occurred. + TableSchema updated_schema = 3; +} + +// Request message for `GetWriteStreamRequest`. +message GetWriteStreamRequest { + // Required. Name of the stream to get, in the form of + // `projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}`. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "bigquerystorage.googleapis.com/WriteStream" + } + ]; +} + +// Request message for `BatchCommitWriteStreams`. +message BatchCommitWriteStreamsRequest { + // Required. Parent table that all the streams should belong to, in the form + // of `projects/{project}/datasets/{dataset}/tables/{table}`. + string parent = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The group of streams that will be committed atomically. + repeated string write_streams = 2 [(google.api.field_behavior) = REQUIRED]; +} + +// Response message for `BatchCommitWriteStreams`. +message BatchCommitWriteStreamsResponse { + // The time at which streams were committed in microseconds granularity. + // This field will only exist when there are no stream errors. + // **Note** if this field is not set, it means the commit was not successful. + google.protobuf.Timestamp commit_time = 1; + + // Stream level error if commit failed. Only streams with error will be in + // the list. + // If empty, there is no error and all streams are committed successfully. + // If non empty, certain streams have errors and ZERO stream is committed due + // to atomicity guarantee. + repeated StorageError stream_errors = 2; +} + +// Request message for invoking `FinalizeWriteStream`. +message FinalizeWriteStreamRequest { + // Required. Name of the stream to finalize, in the form of + // `projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}`. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "bigquerystorage.googleapis.com/WriteStream" + } + ]; +} + +// Response message for `FinalizeWriteStream`. +message FinalizeWriteStreamResponse { + // Number of rows in the finalized stream. + int64 row_count = 1; +} + +// Request message for `FlushRows`. +message FlushRowsRequest { + // Required. The stream that is the target of the flush operation. + string write_stream = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "bigquerystorage.googleapis.com/WriteStream" + } + ]; + + // Ending offset of the flush operation. Rows before this offset(including + // this offset) will be flushed. + google.protobuf.Int64Value offset = 2; +} + +// Respond message for `FlushRows`. +message FlushRowsResponse { + // The rows before this offset (including this offset) are flushed. + int64 offset = 1; +} + +// Structured custom BigQuery Storage error message. The error can be attached +// as error details in the returned rpc Status. In particular, the use of error +// codes allows more structured error handling, and reduces the need to evaluate +// unstructured error text strings. +message StorageError { + // Error code for `StorageError`. + enum StorageErrorCode { + // Default error. + STORAGE_ERROR_CODE_UNSPECIFIED = 0; + + // Table is not found in the system. + TABLE_NOT_FOUND = 1; + + // Stream is already committed. + STREAM_ALREADY_COMMITTED = 2; + + // Stream is not found. + STREAM_NOT_FOUND = 3; + + // Invalid Stream type. + // For example, you try to commit a stream that is not pending. + INVALID_STREAM_TYPE = 4; + + // Invalid Stream state. + // For example, you try to commit a stream that is not finalized or is + // garbaged. + INVALID_STREAM_STATE = 5; + + // Stream is finalized. + STREAM_FINALIZED = 6; + } + + // BigQuery Storage specific error code. + StorageErrorCode code = 1; + + // Name of the failed entity. + string entity = 2; + + // Message that describes the error. + string error_message = 3; +} diff --git a/handwritten/bigquery-storage/protos/google/cloud/bigquery/storage/v1beta2/stream.proto b/handwritten/bigquery-storage/protos/google/cloud/bigquery/storage/v1beta2/stream.proto new file mode 100644 index 000000000000..c2d6d7b6a93a --- /dev/null +++ b/handwritten/bigquery-storage/protos/google/cloud/bigquery/storage/v1beta2/stream.proto @@ -0,0 +1,191 @@ +// 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.cloud.bigquery.storage.v1beta2; + +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/cloud/bigquery/storage/v1beta2/arrow.proto"; +import "google/cloud/bigquery/storage/v1beta2/avro.proto"; +import "google/cloud/bigquery/storage/v1beta2/table.proto"; +import "google/protobuf/timestamp.proto"; + +option go_package = "cloud.google.com/go/bigquery/storage/apiv1beta2/storagepb;storagepb"; +option java_multiple_files = true; +option java_outer_classname = "StreamProto"; +option java_package = "com.google.cloud.bigquery.storage.v1beta2"; +option (google.api.resource_definition) = { + type: "bigquery.googleapis.com/Table" + pattern: "projects/{project}/datasets/{dataset}/tables/{table}" +}; + +// Data format for input or output data. +enum DataFormat { + DATA_FORMAT_UNSPECIFIED = 0; + + // Avro is a standard open source row based file format. + // See https://avro.apache.org/ for more details. + AVRO = 1; + + // Arrow is a standard open source column-based message format. + // See https://arrow.apache.org/ for more details. + ARROW = 2; +} + +// Information about the ReadSession. +message ReadSession { + option (google.api.resource) = { + type: "bigquerystorage.googleapis.com/ReadSession" + pattern: "projects/{project}/locations/{location}/sessions/{session}" + }; + + // Additional attributes when reading a table. + message TableModifiers { + // The snapshot time of the table. If not set, interpreted as now. + google.protobuf.Timestamp snapshot_time = 1; + } + + // Options dictating how we read a table. + message TableReadOptions { + // Names of the fields in the table that should be read. If empty, all + // fields will be read. If the specified field is a nested field, all + // the sub-fields in the field will be selected. The output field order is + // unrelated to the order of fields in selected_fields. + repeated string selected_fields = 1; + + // SQL text filtering statement, similar to a WHERE clause in a query. + // Aggregates are not supported. + // + // Examples: "int_field > 5" + // "date_field = CAST('2014-9-27' as DATE)" + // "nullable_field is not NULL" + // "st_equals(geo_field, st_geofromtext("POINT(2, 2)"))" + // "numeric_field BETWEEN 1.0 AND 5.0" + // + // Restricted to a maximum length for 1 MB. + string row_restriction = 2; + + // Optional. Options specific to the Apache Arrow output format. + ArrowSerializationOptions arrow_serialization_options = 3 [(google.api.field_behavior) = OPTIONAL]; + } + + // Output only. Unique identifier for the session, in the form + // `projects/{project_id}/locations/{location}/sessions/{session_id}`. + string name = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Time at which the session becomes invalid. After this time, subsequent + // requests to read this Session will return errors. The expire_time is + // automatically assigned and currently cannot be specified or updated. + google.protobuf.Timestamp expire_time = 2 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Immutable. Data format of the output data. + DataFormat data_format = 3 [(google.api.field_behavior) = IMMUTABLE]; + + // The schema for the read. If read_options.selected_fields is set, the + // schema may be different from the table schema as it will only contain + // the selected fields. + oneof schema { + // Output only. Avro schema. + AvroSchema avro_schema = 4 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Arrow schema. + ArrowSchema arrow_schema = 5 [(google.api.field_behavior) = OUTPUT_ONLY]; + } + + // Immutable. Table that this ReadSession is reading from, in the form + // `projects/{project_id}/datasets/{dataset_id}/tables/{table_id} + string table = 6 [ + (google.api.field_behavior) = IMMUTABLE, + (google.api.resource_reference) = { + type: "bigquery.googleapis.com/Table" + } + ]; + + // Optional. Any modifiers which are applied when reading from the specified table. + TableModifiers table_modifiers = 7 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Read options for this session (e.g. column selection, filters). + TableReadOptions read_options = 8 [(google.api.field_behavior) = OPTIONAL]; + + // Output only. A list of streams created with the session. + // + // At least one stream is created with the session. In the future, larger + // request_stream_count values *may* result in this list being unpopulated, + // in that case, the user will need to use a List method to get the streams + // instead, which is not yet available. + repeated ReadStream streams = 10 [(google.api.field_behavior) = OUTPUT_ONLY]; +} + +// Information about a single stream that gets data out of the storage system. +// Most of the information about `ReadStream` instances is aggregated, making +// `ReadStream` lightweight. +message ReadStream { + option (google.api.resource) = { + type: "bigquerystorage.googleapis.com/ReadStream" + pattern: "projects/{project}/locations/{location}/sessions/{session}/streams/{stream}" + }; + + // Output only. Name of the stream, in the form + // `projects/{project_id}/locations/{location}/sessions/{session_id}/streams/{stream_id}`. + string name = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; +} + +// Information about a single stream that gets data inside the storage system. +message WriteStream { + option (google.api.resource) = { + type: "bigquerystorage.googleapis.com/WriteStream" + pattern: "projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}" + }; + + // Type enum of the stream. + enum Type { + // Unknown type. + TYPE_UNSPECIFIED = 0; + + // Data will commit automatically and appear as soon as the write is + // acknowledged. + COMMITTED = 1; + + // Data is invisible until the stream is committed. + PENDING = 2; + + // Data is only visible up to the offset to which it was flushed. + BUFFERED = 3; + } + + // Output only. Name of the stream, in the form + // `projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}`. + string name = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Immutable. Type of the stream. + Type type = 2 [(google.api.field_behavior) = IMMUTABLE]; + + // Output only. Create time of the stream. For the _default stream, this is the + // creation_time of the table. + google.protobuf.Timestamp create_time = 3 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Commit time of the stream. + // If a stream is of `COMMITTED` type, then it will have a commit_time same as + // `create_time`. If the stream is of `PENDING` type, commit_time being empty + // means it is not committed. + google.protobuf.Timestamp commit_time = 4 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The schema of the destination table. It is only returned in + // `CreateWriteStream` response. Caller should generate data that's + // compatible with this schema to send in initial `AppendRowsRequest`. + // The table schema could go out of date during the life time of the stream. + TableSchema table_schema = 5 [(google.api.field_behavior) = OUTPUT_ONLY]; +} diff --git a/handwritten/bigquery-storage/protos/google/cloud/bigquery/storage/v1beta2/table.proto b/handwritten/bigquery-storage/protos/google/cloud/bigquery/storage/v1beta2/table.proto new file mode 100644 index 000000000000..3dd27cf0f344 --- /dev/null +++ b/handwritten/bigquery-storage/protos/google/cloud/bigquery/storage/v1beta2/table.proto @@ -0,0 +1,111 @@ +// 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.cloud.bigquery.storage.v1beta2; + +import "google/api/field_behavior.proto"; + +option go_package = "cloud.google.com/go/bigquery/storage/apiv1beta2/storagepb;storagepb"; +option java_multiple_files = true; +option java_outer_classname = "TableProto"; +option java_package = "com.google.cloud.bigquery.storage.v1beta2"; + +// Schema of a table +message TableSchema { + // Describes the fields in a table. + repeated TableFieldSchema fields = 1; +} + +// A field in TableSchema +message TableFieldSchema { + enum Type { + // Illegal value + TYPE_UNSPECIFIED = 0; + + // 64K, UTF8 + STRING = 1; + + // 64-bit signed + INT64 = 2; + + // 64-bit IEEE floating point + DOUBLE = 3; + + // Aggregate type + STRUCT = 4; + + // 64K, Binary + BYTES = 5; + + // 2-valued + BOOL = 6; + + // 64-bit signed usec since UTC epoch + TIMESTAMP = 7; + + // Civil date - Year, Month, Day + DATE = 8; + + // Civil time - Hour, Minute, Second, Microseconds + TIME = 9; + + // Combination of civil date and civil time + DATETIME = 10; + + // Geography object + GEOGRAPHY = 11; + + // Numeric value + NUMERIC = 12; + + // BigNumeric value + BIGNUMERIC = 13; + + // Interval + INTERVAL = 14; + + // JSON, String + JSON = 15; + } + + enum Mode { + // Illegal value + MODE_UNSPECIFIED = 0; + + NULLABLE = 1; + + REQUIRED = 2; + + REPEATED = 3; + } + + // Required. The field name. The name must contain only letters (a-z, A-Z), + // numbers (0-9), or underscores (_), and must start with a letter or + // underscore. The maximum length is 128 characters. + string name = 1 [(google.api.field_behavior) = REQUIRED]; + + // Required. The field data type. + Type type = 2 [(google.api.field_behavior) = REQUIRED]; + + // Optional. The field mode. The default value is NULLABLE. + Mode mode = 3 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Describes the nested schema fields if the type property is set to STRUCT. + repeated TableFieldSchema fields = 4 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. The field description. The maximum length is 1,024 characters. + string description = 6 [(google.api.field_behavior) = OPTIONAL]; +} diff --git a/handwritten/bigquery-storage/protos/protos.d.ts b/handwritten/bigquery-storage/protos/protos.d.ts index b56668241417..78d959e8a7b5 100644 --- a/handwritten/bigquery-storage/protos/protos.d.ts +++ b/handwritten/bigquery-storage/protos/protos.d.ts @@ -11499,6 +11499,3994 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } } + + /** Namespace v1beta2. */ + namespace v1beta2 { + + /** Properties of an ArrowSchema. */ + interface IArrowSchema { + + /** ArrowSchema serializedSchema */ + serializedSchema?: (Uint8Array|Buffer|string|null); + } + + /** Represents an ArrowSchema. */ + class ArrowSchema implements IArrowSchema { + + /** + * Constructs a new ArrowSchema. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IArrowSchema); + + /** ArrowSchema serializedSchema. */ + public serializedSchema: (Uint8Array|Buffer|string); + + /** + * Creates a new ArrowSchema instance using the specified properties. + * @param [properties] Properties to set + * @returns ArrowSchema instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IArrowSchema): google.cloud.bigquery.storage.v1beta2.ArrowSchema; + + /** + * Encodes the specified ArrowSchema message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ArrowSchema.verify|verify} messages. + * @param message ArrowSchema message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IArrowSchema, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ArrowSchema message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ArrowSchema.verify|verify} messages. + * @param message ArrowSchema message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IArrowSchema, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ArrowSchema message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ArrowSchema + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.ArrowSchema; + + /** + * Decodes an ArrowSchema message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ArrowSchema + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.ArrowSchema; + + /** + * Verifies an ArrowSchema message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ArrowSchema message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ArrowSchema + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.ArrowSchema; + + /** + * Creates a plain object from an ArrowSchema message. Also converts values to other types if specified. + * @param message ArrowSchema + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.ArrowSchema, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ArrowSchema to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ArrowSchema + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ArrowRecordBatch. */ + interface IArrowRecordBatch { + + /** ArrowRecordBatch serializedRecordBatch */ + serializedRecordBatch?: (Uint8Array|Buffer|string|null); + } + + /** Represents an ArrowRecordBatch. */ + class ArrowRecordBatch implements IArrowRecordBatch { + + /** + * Constructs a new ArrowRecordBatch. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IArrowRecordBatch); + + /** ArrowRecordBatch serializedRecordBatch. */ + public serializedRecordBatch: (Uint8Array|Buffer|string); + + /** + * Creates a new ArrowRecordBatch instance using the specified properties. + * @param [properties] Properties to set + * @returns ArrowRecordBatch instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IArrowRecordBatch): google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch; + + /** + * Encodes the specified ArrowRecordBatch message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch.verify|verify} messages. + * @param message ArrowRecordBatch message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IArrowRecordBatch, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ArrowRecordBatch message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch.verify|verify} messages. + * @param message ArrowRecordBatch message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IArrowRecordBatch, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ArrowRecordBatch message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ArrowRecordBatch + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch; + + /** + * Decodes an ArrowRecordBatch message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ArrowRecordBatch + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch; + + /** + * Verifies an ArrowRecordBatch message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ArrowRecordBatch message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ArrowRecordBatch + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch; + + /** + * Creates a plain object from an ArrowRecordBatch message. Also converts values to other types if specified. + * @param message ArrowRecordBatch + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ArrowRecordBatch to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ArrowRecordBatch + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ArrowSerializationOptions. */ + interface IArrowSerializationOptions { + + /** ArrowSerializationOptions format */ + format?: (google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions.Format|keyof typeof google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions.Format|null); + } + + /** Represents an ArrowSerializationOptions. */ + class ArrowSerializationOptions implements IArrowSerializationOptions { + + /** + * Constructs a new ArrowSerializationOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IArrowSerializationOptions); + + /** ArrowSerializationOptions format. */ + public format: (google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions.Format|keyof typeof google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions.Format); + + /** + * Creates a new ArrowSerializationOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns ArrowSerializationOptions instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IArrowSerializationOptions): google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions; + + /** + * Encodes the specified ArrowSerializationOptions message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions.verify|verify} messages. + * @param message ArrowSerializationOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IArrowSerializationOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ArrowSerializationOptions message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions.verify|verify} messages. + * @param message ArrowSerializationOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IArrowSerializationOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ArrowSerializationOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ArrowSerializationOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions; + + /** + * Decodes an ArrowSerializationOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ArrowSerializationOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions; + + /** + * Verifies an ArrowSerializationOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an ArrowSerializationOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ArrowSerializationOptions + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions; + + /** + * Creates a plain object from an ArrowSerializationOptions message. Also converts values to other types if specified. + * @param message ArrowSerializationOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ArrowSerializationOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ArrowSerializationOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ArrowSerializationOptions { + + /** Format enum. */ + enum Format { + FORMAT_UNSPECIFIED = 0, + ARROW_0_14 = 1, + ARROW_0_15 = 2 + } + } + + /** Properties of an AvroSchema. */ + interface IAvroSchema { + + /** AvroSchema schema */ + schema?: (string|null); + } + + /** Represents an AvroSchema. */ + class AvroSchema implements IAvroSchema { + + /** + * Constructs a new AvroSchema. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IAvroSchema); + + /** AvroSchema schema. */ + public schema: string; + + /** + * Creates a new AvroSchema instance using the specified properties. + * @param [properties] Properties to set + * @returns AvroSchema instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IAvroSchema): google.cloud.bigquery.storage.v1beta2.AvroSchema; + + /** + * Encodes the specified AvroSchema message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AvroSchema.verify|verify} messages. + * @param message AvroSchema message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IAvroSchema, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified AvroSchema message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AvroSchema.verify|verify} messages. + * @param message AvroSchema message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IAvroSchema, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an AvroSchema message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns AvroSchema + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.AvroSchema; + + /** + * Decodes an AvroSchema message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns AvroSchema + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.AvroSchema; + + /** + * Verifies an AvroSchema message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an AvroSchema message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AvroSchema + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.AvroSchema; + + /** + * Creates a plain object from an AvroSchema message. Also converts values to other types if specified. + * @param message AvroSchema + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.AvroSchema, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AvroSchema to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for AvroSchema + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an AvroRows. */ + interface IAvroRows { + + /** AvroRows serializedBinaryRows */ + serializedBinaryRows?: (Uint8Array|Buffer|string|null); + } + + /** Represents an AvroRows. */ + class AvroRows implements IAvroRows { + + /** + * Constructs a new AvroRows. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IAvroRows); + + /** AvroRows serializedBinaryRows. */ + public serializedBinaryRows: (Uint8Array|Buffer|string); + + /** + * Creates a new AvroRows instance using the specified properties. + * @param [properties] Properties to set + * @returns AvroRows instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IAvroRows): google.cloud.bigquery.storage.v1beta2.AvroRows; + + /** + * Encodes the specified AvroRows message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AvroRows.verify|verify} messages. + * @param message AvroRows message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IAvroRows, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified AvroRows message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AvroRows.verify|verify} messages. + * @param message AvroRows message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IAvroRows, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an AvroRows message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns AvroRows + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.AvroRows; + + /** + * Decodes an AvroRows message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns AvroRows + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.AvroRows; + + /** + * Verifies an AvroRows message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an AvroRows message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AvroRows + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.AvroRows; + + /** + * Creates a plain object from an AvroRows message. Also converts values to other types if specified. + * @param message AvroRows + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.AvroRows, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AvroRows to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for AvroRows + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ProtoSchema. */ + interface IProtoSchema { + + /** ProtoSchema protoDescriptor */ + protoDescriptor?: (google.protobuf.IDescriptorProto|null); + } + + /** Represents a ProtoSchema. */ + class ProtoSchema implements IProtoSchema { + + /** + * Constructs a new ProtoSchema. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IProtoSchema); + + /** ProtoSchema protoDescriptor. */ + public protoDescriptor?: (google.protobuf.IDescriptorProto|null); + + /** + * Creates a new ProtoSchema instance using the specified properties. + * @param [properties] Properties to set + * @returns ProtoSchema instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IProtoSchema): google.cloud.bigquery.storage.v1beta2.ProtoSchema; + + /** + * Encodes the specified ProtoSchema message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ProtoSchema.verify|verify} messages. + * @param message ProtoSchema message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IProtoSchema, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ProtoSchema message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ProtoSchema.verify|verify} messages. + * @param message ProtoSchema message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IProtoSchema, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ProtoSchema message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ProtoSchema + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.ProtoSchema; + + /** + * Decodes a ProtoSchema message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ProtoSchema + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.ProtoSchema; + + /** + * Verifies a ProtoSchema message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ProtoSchema message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ProtoSchema + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.ProtoSchema; + + /** + * Creates a plain object from a ProtoSchema message. Also converts values to other types if specified. + * @param message ProtoSchema + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.ProtoSchema, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ProtoSchema to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ProtoSchema + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ProtoRows. */ + interface IProtoRows { + + /** ProtoRows serializedRows */ + serializedRows?: (Uint8Array[]|null); + } + + /** Represents a ProtoRows. */ + class ProtoRows implements IProtoRows { + + /** + * Constructs a new ProtoRows. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IProtoRows); + + /** ProtoRows serializedRows. */ + public serializedRows: Uint8Array[]; + + /** + * Creates a new ProtoRows instance using the specified properties. + * @param [properties] Properties to set + * @returns ProtoRows instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IProtoRows): google.cloud.bigquery.storage.v1beta2.ProtoRows; + + /** + * Encodes the specified ProtoRows message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ProtoRows.verify|verify} messages. + * @param message ProtoRows message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IProtoRows, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ProtoRows message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ProtoRows.verify|verify} messages. + * @param message ProtoRows message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IProtoRows, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ProtoRows message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ProtoRows + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.ProtoRows; + + /** + * Decodes a ProtoRows message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ProtoRows + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.ProtoRows; + + /** + * Verifies a ProtoRows message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ProtoRows message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ProtoRows + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.ProtoRows; + + /** + * Creates a plain object from a ProtoRows message. Also converts values to other types if specified. + * @param message ProtoRows + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.ProtoRows, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ProtoRows to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ProtoRows + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Represents a BigQueryRead */ + class BigQueryRead extends $protobuf.rpc.Service { + + /** + * Constructs a new BigQueryRead 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); + + /** + * Creates new BigQueryRead service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): BigQueryRead; + + /** + * Calls CreateReadSession. + * @param request CreateReadSessionRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ReadSession + */ + public createReadSession(request: google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest, callback: google.cloud.bigquery.storage.v1beta2.BigQueryRead.CreateReadSessionCallback): void; + + /** + * Calls CreateReadSession. + * @param request CreateReadSessionRequest message or plain object + * @returns Promise + */ + public createReadSession(request: google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest): Promise; + + /** + * Calls ReadRows. + * @param request ReadRowsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ReadRowsResponse + */ + public readRows(request: google.cloud.bigquery.storage.v1beta2.IReadRowsRequest, callback: google.cloud.bigquery.storage.v1beta2.BigQueryRead.ReadRowsCallback): void; + + /** + * Calls ReadRows. + * @param request ReadRowsRequest message or plain object + * @returns Promise + */ + public readRows(request: google.cloud.bigquery.storage.v1beta2.IReadRowsRequest): Promise; + + /** + * Calls SplitReadStream. + * @param request SplitReadStreamRequest message or plain object + * @param callback Node-style callback called with the error, if any, and SplitReadStreamResponse + */ + public splitReadStream(request: google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest, callback: google.cloud.bigquery.storage.v1beta2.BigQueryRead.SplitReadStreamCallback): void; + + /** + * Calls SplitReadStream. + * @param request SplitReadStreamRequest message or plain object + * @returns Promise + */ + public splitReadStream(request: google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest): Promise; + } + + namespace BigQueryRead { + + /** + * Callback as used by {@link google.cloud.bigquery.storage.v1beta2.BigQueryRead|createReadSession}. + * @param error Error, if any + * @param [response] ReadSession + */ + type CreateReadSessionCallback = (error: (Error|null), response?: google.cloud.bigquery.storage.v1beta2.ReadSession) => void; + + /** + * Callback as used by {@link google.cloud.bigquery.storage.v1beta2.BigQueryRead|readRows}. + * @param error Error, if any + * @param [response] ReadRowsResponse + */ + type ReadRowsCallback = (error: (Error|null), response?: google.cloud.bigquery.storage.v1beta2.ReadRowsResponse) => void; + + /** + * Callback as used by {@link google.cloud.bigquery.storage.v1beta2.BigQueryRead|splitReadStream}. + * @param error Error, if any + * @param [response] SplitReadStreamResponse + */ + type SplitReadStreamCallback = (error: (Error|null), response?: google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse) => void; + } + + /** Represents a BigQueryWrite */ + class BigQueryWrite extends $protobuf.rpc.Service { + + /** + * Constructs a new BigQueryWrite 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); + + /** + * Creates new BigQueryWrite service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): BigQueryWrite; + + /** + * Calls CreateWriteStream. + * @param request CreateWriteStreamRequest message or plain object + * @param callback Node-style callback called with the error, if any, and WriteStream + */ + public createWriteStream(request: google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest, callback: google.cloud.bigquery.storage.v1beta2.BigQueryWrite.CreateWriteStreamCallback): void; + + /** + * Calls CreateWriteStream. + * @param request CreateWriteStreamRequest message or plain object + * @returns Promise + */ + public createWriteStream(request: google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest): Promise; + + /** + * Calls AppendRows. + * @param request AppendRowsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and AppendRowsResponse + */ + public appendRows(request: google.cloud.bigquery.storage.v1beta2.IAppendRowsRequest, callback: google.cloud.bigquery.storage.v1beta2.BigQueryWrite.AppendRowsCallback): void; + + /** + * Calls AppendRows. + * @param request AppendRowsRequest message or plain object + * @returns Promise + */ + public appendRows(request: google.cloud.bigquery.storage.v1beta2.IAppendRowsRequest): Promise; + + /** + * Calls GetWriteStream. + * @param request GetWriteStreamRequest message or plain object + * @param callback Node-style callback called with the error, if any, and WriteStream + */ + public getWriteStream(request: google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest, callback: google.cloud.bigquery.storage.v1beta2.BigQueryWrite.GetWriteStreamCallback): void; + + /** + * Calls GetWriteStream. + * @param request GetWriteStreamRequest message or plain object + * @returns Promise + */ + public getWriteStream(request: google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest): Promise; + + /** + * Calls FinalizeWriteStream. + * @param request FinalizeWriteStreamRequest message or plain object + * @param callback Node-style callback called with the error, if any, and FinalizeWriteStreamResponse + */ + public finalizeWriteStream(request: google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest, callback: google.cloud.bigquery.storage.v1beta2.BigQueryWrite.FinalizeWriteStreamCallback): void; + + /** + * Calls FinalizeWriteStream. + * @param request FinalizeWriteStreamRequest message or plain object + * @returns Promise + */ + public finalizeWriteStream(request: google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest): Promise; + + /** + * Calls BatchCommitWriteStreams. + * @param request BatchCommitWriteStreamsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BatchCommitWriteStreamsResponse + */ + public batchCommitWriteStreams(request: google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest, callback: google.cloud.bigquery.storage.v1beta2.BigQueryWrite.BatchCommitWriteStreamsCallback): void; + + /** + * Calls BatchCommitWriteStreams. + * @param request BatchCommitWriteStreamsRequest message or plain object + * @returns Promise + */ + public batchCommitWriteStreams(request: google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest): Promise; + + /** + * Calls FlushRows. + * @param request FlushRowsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and FlushRowsResponse + */ + public flushRows(request: google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest, callback: google.cloud.bigquery.storage.v1beta2.BigQueryWrite.FlushRowsCallback): void; + + /** + * Calls FlushRows. + * @param request FlushRowsRequest message or plain object + * @returns Promise + */ + public flushRows(request: google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest): Promise; + } + + namespace BigQueryWrite { + + /** + * Callback as used by {@link google.cloud.bigquery.storage.v1beta2.BigQueryWrite|createWriteStream}. + * @param error Error, if any + * @param [response] WriteStream + */ + type CreateWriteStreamCallback = (error: (Error|null), response?: google.cloud.bigquery.storage.v1beta2.WriteStream) => void; + + /** + * Callback as used by {@link google.cloud.bigquery.storage.v1beta2.BigQueryWrite|appendRows}. + * @param error Error, if any + * @param [response] AppendRowsResponse + */ + type AppendRowsCallback = (error: (Error|null), response?: google.cloud.bigquery.storage.v1beta2.AppendRowsResponse) => void; + + /** + * Callback as used by {@link google.cloud.bigquery.storage.v1beta2.BigQueryWrite|getWriteStream}. + * @param error Error, if any + * @param [response] WriteStream + */ + type GetWriteStreamCallback = (error: (Error|null), response?: google.cloud.bigquery.storage.v1beta2.WriteStream) => void; + + /** + * Callback as used by {@link google.cloud.bigquery.storage.v1beta2.BigQueryWrite|finalizeWriteStream}. + * @param error Error, if any + * @param [response] FinalizeWriteStreamResponse + */ + type FinalizeWriteStreamCallback = (error: (Error|null), response?: google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse) => void; + + /** + * Callback as used by {@link google.cloud.bigquery.storage.v1beta2.BigQueryWrite|batchCommitWriteStreams}. + * @param error Error, if any + * @param [response] BatchCommitWriteStreamsResponse + */ + type BatchCommitWriteStreamsCallback = (error: (Error|null), response?: google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse) => void; + + /** + * Callback as used by {@link google.cloud.bigquery.storage.v1beta2.BigQueryWrite|flushRows}. + * @param error Error, if any + * @param [response] FlushRowsResponse + */ + type FlushRowsCallback = (error: (Error|null), response?: google.cloud.bigquery.storage.v1beta2.FlushRowsResponse) => void; + } + + /** Properties of a CreateReadSessionRequest. */ + interface ICreateReadSessionRequest { + + /** CreateReadSessionRequest parent */ + parent?: (string|null); + + /** CreateReadSessionRequest readSession */ + readSession?: (google.cloud.bigquery.storage.v1beta2.IReadSession|null); + + /** CreateReadSessionRequest maxStreamCount */ + maxStreamCount?: (number|null); + } + + /** Represents a CreateReadSessionRequest. */ + class CreateReadSessionRequest implements ICreateReadSessionRequest { + + /** + * Constructs a new CreateReadSessionRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest); + + /** CreateReadSessionRequest parent. */ + public parent: string; + + /** CreateReadSessionRequest readSession. */ + public readSession?: (google.cloud.bigquery.storage.v1beta2.IReadSession|null); + + /** CreateReadSessionRequest maxStreamCount. */ + public maxStreamCount: number; + + /** + * Creates a new CreateReadSessionRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns CreateReadSessionRequest instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest): google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest; + + /** + * Encodes the specified CreateReadSessionRequest message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest.verify|verify} messages. + * @param message CreateReadSessionRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CreateReadSessionRequest message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest.verify|verify} messages. + * @param message CreateReadSessionRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CreateReadSessionRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CreateReadSessionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest; + + /** + * Decodes a CreateReadSessionRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CreateReadSessionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest; + + /** + * Verifies a CreateReadSessionRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CreateReadSessionRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateReadSessionRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest; + + /** + * Creates a plain object from a CreateReadSessionRequest message. Also converts values to other types if specified. + * @param message CreateReadSessionRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateReadSessionRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateReadSessionRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReadRowsRequest. */ + interface IReadRowsRequest { + + /** ReadRowsRequest readStream */ + readStream?: (string|null); + + /** ReadRowsRequest offset */ + offset?: (number|Long|string|null); + } + + /** Represents a ReadRowsRequest. */ + class ReadRowsRequest implements IReadRowsRequest { + + /** + * Constructs a new ReadRowsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IReadRowsRequest); + + /** ReadRowsRequest readStream. */ + public readStream: string; + + /** ReadRowsRequest offset. */ + public offset: (number|Long|string); + + /** + * Creates a new ReadRowsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns ReadRowsRequest instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IReadRowsRequest): google.cloud.bigquery.storage.v1beta2.ReadRowsRequest; + + /** + * Encodes the specified ReadRowsRequest message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadRowsRequest.verify|verify} messages. + * @param message ReadRowsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IReadRowsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReadRowsRequest message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadRowsRequest.verify|verify} messages. + * @param message ReadRowsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IReadRowsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReadRowsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReadRowsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.ReadRowsRequest; + + /** + * Decodes a ReadRowsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReadRowsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.ReadRowsRequest; + + /** + * Verifies a ReadRowsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReadRowsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadRowsRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.ReadRowsRequest; + + /** + * Creates a plain object from a ReadRowsRequest message. Also converts values to other types if specified. + * @param message ReadRowsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.ReadRowsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReadRowsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadRowsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ThrottleState. */ + interface IThrottleState { + + /** ThrottleState throttlePercent */ + throttlePercent?: (number|null); + } + + /** Represents a ThrottleState. */ + class ThrottleState implements IThrottleState { + + /** + * Constructs a new ThrottleState. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IThrottleState); + + /** ThrottleState throttlePercent. */ + public throttlePercent: number; + + /** + * Creates a new ThrottleState instance using the specified properties. + * @param [properties] Properties to set + * @returns ThrottleState instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IThrottleState): google.cloud.bigquery.storage.v1beta2.ThrottleState; + + /** + * Encodes the specified ThrottleState message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ThrottleState.verify|verify} messages. + * @param message ThrottleState message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IThrottleState, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ThrottleState message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ThrottleState.verify|verify} messages. + * @param message ThrottleState message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IThrottleState, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ThrottleState message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ThrottleState + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.ThrottleState; + + /** + * Decodes a ThrottleState message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ThrottleState + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.ThrottleState; + + /** + * Verifies a ThrottleState message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ThrottleState message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ThrottleState + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.ThrottleState; + + /** + * Creates a plain object from a ThrottleState message. Also converts values to other types if specified. + * @param message ThrottleState + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.ThrottleState, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ThrottleState to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ThrottleState + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StreamStats. */ + interface IStreamStats { + + /** StreamStats progress */ + progress?: (google.cloud.bigquery.storage.v1beta2.StreamStats.IProgress|null); + } + + /** Represents a StreamStats. */ + class StreamStats implements IStreamStats { + + /** + * Constructs a new StreamStats. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IStreamStats); + + /** StreamStats progress. */ + public progress?: (google.cloud.bigquery.storage.v1beta2.StreamStats.IProgress|null); + + /** + * Creates a new StreamStats instance using the specified properties. + * @param [properties] Properties to set + * @returns StreamStats instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IStreamStats): google.cloud.bigquery.storage.v1beta2.StreamStats; + + /** + * Encodes the specified StreamStats message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.StreamStats.verify|verify} messages. + * @param message StreamStats message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IStreamStats, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified StreamStats message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.StreamStats.verify|verify} messages. + * @param message StreamStats message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IStreamStats, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a StreamStats message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns StreamStats + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.StreamStats; + + /** + * Decodes a StreamStats message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns StreamStats + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.StreamStats; + + /** + * Verifies a StreamStats message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a StreamStats message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StreamStats + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.StreamStats; + + /** + * Creates a plain object from a StreamStats message. Also converts values to other types if specified. + * @param message StreamStats + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.StreamStats, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StreamStats to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StreamStats + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace StreamStats { + + /** Properties of a Progress. */ + interface IProgress { + + /** Progress atResponseStart */ + atResponseStart?: (number|null); + + /** Progress atResponseEnd */ + atResponseEnd?: (number|null); + } + + /** Represents a Progress. */ + class Progress implements IProgress { + + /** + * Constructs a new Progress. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.StreamStats.IProgress); + + /** Progress atResponseStart. */ + public atResponseStart: number; + + /** Progress atResponseEnd. */ + public atResponseEnd: number; + + /** + * Creates a new Progress instance using the specified properties. + * @param [properties] Properties to set + * @returns Progress instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.StreamStats.IProgress): google.cloud.bigquery.storage.v1beta2.StreamStats.Progress; + + /** + * Encodes the specified Progress message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.StreamStats.Progress.verify|verify} messages. + * @param message Progress message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.StreamStats.IProgress, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified Progress message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.StreamStats.Progress.verify|verify} messages. + * @param message Progress message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.StreamStats.IProgress, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a Progress message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns Progress + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.StreamStats.Progress; + + /** + * Decodes a Progress message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns Progress + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.StreamStats.Progress; + + /** + * Verifies a Progress message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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.cloud.bigquery.storage.v1beta2.StreamStats.Progress; + + /** + * 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.cloud.bigquery.storage.v1beta2.StreamStats.Progress, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * 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 a ReadRowsResponse. */ + interface IReadRowsResponse { + + /** ReadRowsResponse avroRows */ + avroRows?: (google.cloud.bigquery.storage.v1beta2.IAvroRows|null); + + /** ReadRowsResponse arrowRecordBatch */ + arrowRecordBatch?: (google.cloud.bigquery.storage.v1beta2.IArrowRecordBatch|null); + + /** ReadRowsResponse rowCount */ + rowCount?: (number|Long|string|null); + + /** ReadRowsResponse stats */ + stats?: (google.cloud.bigquery.storage.v1beta2.IStreamStats|null); + + /** ReadRowsResponse throttleState */ + throttleState?: (google.cloud.bigquery.storage.v1beta2.IThrottleState|null); + + /** ReadRowsResponse avroSchema */ + avroSchema?: (google.cloud.bigquery.storage.v1beta2.IAvroSchema|null); + + /** ReadRowsResponse arrowSchema */ + arrowSchema?: (google.cloud.bigquery.storage.v1beta2.IArrowSchema|null); + } + + /** Represents a ReadRowsResponse. */ + class ReadRowsResponse implements IReadRowsResponse { + + /** + * Constructs a new ReadRowsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IReadRowsResponse); + + /** ReadRowsResponse avroRows. */ + public avroRows?: (google.cloud.bigquery.storage.v1beta2.IAvroRows|null); + + /** ReadRowsResponse arrowRecordBatch. */ + public arrowRecordBatch?: (google.cloud.bigquery.storage.v1beta2.IArrowRecordBatch|null); + + /** ReadRowsResponse rowCount. */ + public rowCount: (number|Long|string); + + /** ReadRowsResponse stats. */ + public stats?: (google.cloud.bigquery.storage.v1beta2.IStreamStats|null); + + /** ReadRowsResponse throttleState. */ + public throttleState?: (google.cloud.bigquery.storage.v1beta2.IThrottleState|null); + + /** ReadRowsResponse avroSchema. */ + public avroSchema?: (google.cloud.bigquery.storage.v1beta2.IAvroSchema|null); + + /** ReadRowsResponse arrowSchema. */ + public arrowSchema?: (google.cloud.bigquery.storage.v1beta2.IArrowSchema|null); + + /** ReadRowsResponse rows. */ + public rows?: ("avroRows"|"arrowRecordBatch"); + + /** ReadRowsResponse schema. */ + public schema?: ("avroSchema"|"arrowSchema"); + + /** + * Creates a new ReadRowsResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns ReadRowsResponse instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IReadRowsResponse): google.cloud.bigquery.storage.v1beta2.ReadRowsResponse; + + /** + * Encodes the specified ReadRowsResponse message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadRowsResponse.verify|verify} messages. + * @param message ReadRowsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IReadRowsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReadRowsResponse message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadRowsResponse.verify|verify} messages. + * @param message ReadRowsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IReadRowsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReadRowsResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReadRowsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.ReadRowsResponse; + + /** + * Decodes a ReadRowsResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReadRowsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.ReadRowsResponse; + + /** + * Verifies a ReadRowsResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReadRowsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadRowsResponse + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.ReadRowsResponse; + + /** + * Creates a plain object from a ReadRowsResponse message. Also converts values to other types if specified. + * @param message ReadRowsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.ReadRowsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReadRowsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadRowsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a SplitReadStreamRequest. */ + interface ISplitReadStreamRequest { + + /** SplitReadStreamRequest name */ + name?: (string|null); + + /** SplitReadStreamRequest fraction */ + fraction?: (number|null); + } + + /** Represents a SplitReadStreamRequest. */ + class SplitReadStreamRequest implements ISplitReadStreamRequest { + + /** + * Constructs a new SplitReadStreamRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest); + + /** SplitReadStreamRequest name. */ + public name: string; + + /** SplitReadStreamRequest fraction. */ + public fraction: number; + + /** + * Creates a new SplitReadStreamRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns SplitReadStreamRequest instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest): google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest; + + /** + * Encodes the specified SplitReadStreamRequest message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest.verify|verify} messages. + * @param message SplitReadStreamRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SplitReadStreamRequest message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest.verify|verify} messages. + * @param message SplitReadStreamRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SplitReadStreamRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SplitReadStreamRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest; + + /** + * Decodes a SplitReadStreamRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SplitReadStreamRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest; + + /** + * Verifies a SplitReadStreamRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SplitReadStreamRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SplitReadStreamRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest; + + /** + * Creates a plain object from a SplitReadStreamRequest message. Also converts values to other types if specified. + * @param message SplitReadStreamRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SplitReadStreamRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SplitReadStreamRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a SplitReadStreamResponse. */ + interface ISplitReadStreamResponse { + + /** SplitReadStreamResponse primaryStream */ + primaryStream?: (google.cloud.bigquery.storage.v1beta2.IReadStream|null); + + /** SplitReadStreamResponse remainderStream */ + remainderStream?: (google.cloud.bigquery.storage.v1beta2.IReadStream|null); + } + + /** Represents a SplitReadStreamResponse. */ + class SplitReadStreamResponse implements ISplitReadStreamResponse { + + /** + * Constructs a new SplitReadStreamResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.ISplitReadStreamResponse); + + /** SplitReadStreamResponse primaryStream. */ + public primaryStream?: (google.cloud.bigquery.storage.v1beta2.IReadStream|null); + + /** SplitReadStreamResponse remainderStream. */ + public remainderStream?: (google.cloud.bigquery.storage.v1beta2.IReadStream|null); + + /** + * Creates a new SplitReadStreamResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns SplitReadStreamResponse instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.ISplitReadStreamResponse): google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse; + + /** + * Encodes the specified SplitReadStreamResponse message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse.verify|verify} messages. + * @param message SplitReadStreamResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.ISplitReadStreamResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SplitReadStreamResponse message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse.verify|verify} messages. + * @param message SplitReadStreamResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.ISplitReadStreamResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SplitReadStreamResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SplitReadStreamResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse; + + /** + * Decodes a SplitReadStreamResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SplitReadStreamResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse; + + /** + * Verifies a SplitReadStreamResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a SplitReadStreamResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SplitReadStreamResponse + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse; + + /** + * Creates a plain object from a SplitReadStreamResponse message. Also converts values to other types if specified. + * @param message SplitReadStreamResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SplitReadStreamResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SplitReadStreamResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateWriteStreamRequest. */ + interface ICreateWriteStreamRequest { + + /** CreateWriteStreamRequest parent */ + parent?: (string|null); + + /** CreateWriteStreamRequest writeStream */ + writeStream?: (google.cloud.bigquery.storage.v1beta2.IWriteStream|null); + } + + /** Represents a CreateWriteStreamRequest. */ + class CreateWriteStreamRequest implements ICreateWriteStreamRequest { + + /** + * Constructs a new CreateWriteStreamRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest); + + /** CreateWriteStreamRequest parent. */ + public parent: string; + + /** CreateWriteStreamRequest writeStream. */ + public writeStream?: (google.cloud.bigquery.storage.v1beta2.IWriteStream|null); + + /** + * Creates a new CreateWriteStreamRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns CreateWriteStreamRequest instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest): google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest; + + /** + * Encodes the specified CreateWriteStreamRequest message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest.verify|verify} messages. + * @param message CreateWriteStreamRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified CreateWriteStreamRequest message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest.verify|verify} messages. + * @param message CreateWriteStreamRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a CreateWriteStreamRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns CreateWriteStreamRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest; + + /** + * Decodes a CreateWriteStreamRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns CreateWriteStreamRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest; + + /** + * Verifies a CreateWriteStreamRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a CreateWriteStreamRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateWriteStreamRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest; + + /** + * Creates a plain object from a CreateWriteStreamRequest message. Also converts values to other types if specified. + * @param message CreateWriteStreamRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateWriteStreamRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateWriteStreamRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an AppendRowsRequest. */ + interface IAppendRowsRequest { + + /** AppendRowsRequest writeStream */ + writeStream?: (string|null); + + /** AppendRowsRequest offset */ + offset?: (google.protobuf.IInt64Value|null); + + /** AppendRowsRequest protoRows */ + protoRows?: (google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.IProtoData|null); + + /** AppendRowsRequest traceId */ + traceId?: (string|null); + } + + /** Represents an AppendRowsRequest. */ + class AppendRowsRequest implements IAppendRowsRequest { + + /** + * Constructs a new AppendRowsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IAppendRowsRequest); + + /** AppendRowsRequest writeStream. */ + public writeStream: string; + + /** AppendRowsRequest offset. */ + public offset?: (google.protobuf.IInt64Value|null); + + /** AppendRowsRequest protoRows. */ + public protoRows?: (google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.IProtoData|null); + + /** AppendRowsRequest traceId. */ + public traceId: string; + + /** AppendRowsRequest rows. */ + public rows?: "protoRows"; + + /** + * Creates a new AppendRowsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns AppendRowsRequest instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IAppendRowsRequest): google.cloud.bigquery.storage.v1beta2.AppendRowsRequest; + + /** + * Encodes the specified AppendRowsRequest message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.verify|verify} messages. + * @param message AppendRowsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IAppendRowsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified AppendRowsRequest message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.verify|verify} messages. + * @param message AppendRowsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IAppendRowsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an AppendRowsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns AppendRowsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.AppendRowsRequest; + + /** + * Decodes an AppendRowsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns AppendRowsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.AppendRowsRequest; + + /** + * Verifies an AppendRowsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an AppendRowsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AppendRowsRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.AppendRowsRequest; + + /** + * Creates a plain object from an AppendRowsRequest message. Also converts values to other types if specified. + * @param message AppendRowsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.AppendRowsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AppendRowsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for AppendRowsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace AppendRowsRequest { + + /** Properties of a ProtoData. */ + interface IProtoData { + + /** ProtoData writerSchema */ + writerSchema?: (google.cloud.bigquery.storage.v1beta2.IProtoSchema|null); + + /** ProtoData rows */ + rows?: (google.cloud.bigquery.storage.v1beta2.IProtoRows|null); + } + + /** Represents a ProtoData. */ + class ProtoData implements IProtoData { + + /** + * Constructs a new ProtoData. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.IProtoData); + + /** ProtoData writerSchema. */ + public writerSchema?: (google.cloud.bigquery.storage.v1beta2.IProtoSchema|null); + + /** ProtoData rows. */ + public rows?: (google.cloud.bigquery.storage.v1beta2.IProtoRows|null); + + /** + * Creates a new ProtoData instance using the specified properties. + * @param [properties] Properties to set + * @returns ProtoData instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.IProtoData): google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData; + + /** + * Encodes the specified ProtoData message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData.verify|verify} messages. + * @param message ProtoData message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.IProtoData, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ProtoData message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData.verify|verify} messages. + * @param message ProtoData message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.IProtoData, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ProtoData message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ProtoData + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData; + + /** + * Decodes a ProtoData message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ProtoData + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData; + + /** + * Verifies a ProtoData message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ProtoData message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ProtoData + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData; + + /** + * Creates a plain object from a ProtoData message. Also converts values to other types if specified. + * @param message ProtoData + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ProtoData to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ProtoData + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an AppendRowsResponse. */ + interface IAppendRowsResponse { + + /** AppendRowsResponse appendResult */ + appendResult?: (google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.IAppendResult|null); + + /** AppendRowsResponse error */ + error?: (google.rpc.IStatus|null); + + /** AppendRowsResponse updatedSchema */ + updatedSchema?: (google.cloud.bigquery.storage.v1beta2.ITableSchema|null); + } + + /** Represents an AppendRowsResponse. */ + class AppendRowsResponse implements IAppendRowsResponse { + + /** + * Constructs a new AppendRowsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IAppendRowsResponse); + + /** AppendRowsResponse appendResult. */ + public appendResult?: (google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.IAppendResult|null); + + /** AppendRowsResponse error. */ + public error?: (google.rpc.IStatus|null); + + /** AppendRowsResponse updatedSchema. */ + public updatedSchema?: (google.cloud.bigquery.storage.v1beta2.ITableSchema|null); + + /** AppendRowsResponse response. */ + public response?: ("appendResult"|"error"); + + /** + * Creates a new AppendRowsResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns AppendRowsResponse instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IAppendRowsResponse): google.cloud.bigquery.storage.v1beta2.AppendRowsResponse; + + /** + * Encodes the specified AppendRowsResponse message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.verify|verify} messages. + * @param message AppendRowsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IAppendRowsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified AppendRowsResponse message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.verify|verify} messages. + * @param message AppendRowsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IAppendRowsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an AppendRowsResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns AppendRowsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.AppendRowsResponse; + + /** + * Decodes an AppendRowsResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns AppendRowsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.AppendRowsResponse; + + /** + * Verifies an AppendRowsResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an AppendRowsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AppendRowsResponse + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.AppendRowsResponse; + + /** + * Creates a plain object from an AppendRowsResponse message. Also converts values to other types if specified. + * @param message AppendRowsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.AppendRowsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AppendRowsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for AppendRowsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace AppendRowsResponse { + + /** Properties of an AppendResult. */ + interface IAppendResult { + + /** AppendResult offset */ + offset?: (google.protobuf.IInt64Value|null); + } + + /** Represents an AppendResult. */ + class AppendResult implements IAppendResult { + + /** + * Constructs a new AppendResult. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.IAppendResult); + + /** AppendResult offset. */ + public offset?: (google.protobuf.IInt64Value|null); + + /** + * Creates a new AppendResult instance using the specified properties. + * @param [properties] Properties to set + * @returns AppendResult instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.IAppendResult): google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult; + + /** + * Encodes the specified AppendResult message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult.verify|verify} messages. + * @param message AppendResult message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.IAppendResult, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified AppendResult message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult.verify|verify} messages. + * @param message AppendResult message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.IAppendResult, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an AppendResult message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns AppendResult + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult; + + /** + * Decodes an AppendResult message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns AppendResult + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult; + + /** + * Verifies an AppendResult message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates an AppendResult message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AppendResult + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult; + + /** + * Creates a plain object from an AppendResult message. Also converts values to other types if specified. + * @param message AppendResult + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this AppendResult to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for AppendResult + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a GetWriteStreamRequest. */ + interface IGetWriteStreamRequest { + + /** GetWriteStreamRequest name */ + name?: (string|null); + } + + /** Represents a GetWriteStreamRequest. */ + class GetWriteStreamRequest implements IGetWriteStreamRequest { + + /** + * Constructs a new GetWriteStreamRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest); + + /** GetWriteStreamRequest name. */ + public name: string; + + /** + * Creates a new GetWriteStreamRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns GetWriteStreamRequest instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest): google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest; + + /** + * Encodes the specified GetWriteStreamRequest message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest.verify|verify} messages. + * @param message GetWriteStreamRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified GetWriteStreamRequest message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest.verify|verify} messages. + * @param message GetWriteStreamRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a GetWriteStreamRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns GetWriteStreamRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest; + + /** + * Decodes a GetWriteStreamRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns GetWriteStreamRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest; + + /** + * Verifies a GetWriteStreamRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a GetWriteStreamRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetWriteStreamRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest; + + /** + * Creates a plain object from a GetWriteStreamRequest message. Also converts values to other types if specified. + * @param message GetWriteStreamRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetWriteStreamRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetWriteStreamRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchCommitWriteStreamsRequest. */ + interface IBatchCommitWriteStreamsRequest { + + /** BatchCommitWriteStreamsRequest parent */ + parent?: (string|null); + + /** BatchCommitWriteStreamsRequest writeStreams */ + writeStreams?: (string[]|null); + } + + /** Represents a BatchCommitWriteStreamsRequest. */ + class BatchCommitWriteStreamsRequest implements IBatchCommitWriteStreamsRequest { + + /** + * Constructs a new BatchCommitWriteStreamsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest); + + /** BatchCommitWriteStreamsRequest parent. */ + public parent: string; + + /** BatchCommitWriteStreamsRequest writeStreams. */ + public writeStreams: string[]; + + /** + * Creates a new BatchCommitWriteStreamsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns BatchCommitWriteStreamsRequest instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest): google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest; + + /** + * Encodes the specified BatchCommitWriteStreamsRequest message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest.verify|verify} messages. + * @param message BatchCommitWriteStreamsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified BatchCommitWriteStreamsRequest message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest.verify|verify} messages. + * @param message BatchCommitWriteStreamsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a BatchCommitWriteStreamsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns BatchCommitWriteStreamsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest; + + /** + * Decodes a BatchCommitWriteStreamsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns BatchCommitWriteStreamsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest; + + /** + * Verifies a BatchCommitWriteStreamsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a BatchCommitWriteStreamsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchCommitWriteStreamsRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest; + + /** + * Creates a plain object from a BatchCommitWriteStreamsRequest message. Also converts values to other types if specified. + * @param message BatchCommitWriteStreamsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchCommitWriteStreamsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchCommitWriteStreamsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchCommitWriteStreamsResponse. */ + interface IBatchCommitWriteStreamsResponse { + + /** BatchCommitWriteStreamsResponse commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + + /** BatchCommitWriteStreamsResponse streamErrors */ + streamErrors?: (google.cloud.bigquery.storage.v1beta2.IStorageError[]|null); + } + + /** Represents a BatchCommitWriteStreamsResponse. */ + class BatchCommitWriteStreamsResponse implements IBatchCommitWriteStreamsResponse { + + /** + * Constructs a new BatchCommitWriteStreamsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsResponse); + + /** BatchCommitWriteStreamsResponse commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); + + /** BatchCommitWriteStreamsResponse streamErrors. */ + public streamErrors: google.cloud.bigquery.storage.v1beta2.IStorageError[]; + + /** + * Creates a new BatchCommitWriteStreamsResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns BatchCommitWriteStreamsResponse instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsResponse): google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse; + + /** + * Encodes the specified BatchCommitWriteStreamsResponse message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse.verify|verify} messages. + * @param message BatchCommitWriteStreamsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified BatchCommitWriteStreamsResponse message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse.verify|verify} messages. + * @param message BatchCommitWriteStreamsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a BatchCommitWriteStreamsResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns BatchCommitWriteStreamsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse; + + /** + * Decodes a BatchCommitWriteStreamsResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns BatchCommitWriteStreamsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse; + + /** + * Verifies a BatchCommitWriteStreamsResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a BatchCommitWriteStreamsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchCommitWriteStreamsResponse + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse; + + /** + * Creates a plain object from a BatchCommitWriteStreamsResponse message. Also converts values to other types if specified. + * @param message BatchCommitWriteStreamsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchCommitWriteStreamsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchCommitWriteStreamsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FinalizeWriteStreamRequest. */ + interface IFinalizeWriteStreamRequest { + + /** FinalizeWriteStreamRequest name */ + name?: (string|null); + } + + /** Represents a FinalizeWriteStreamRequest. */ + class FinalizeWriteStreamRequest implements IFinalizeWriteStreamRequest { + + /** + * Constructs a new FinalizeWriteStreamRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest); + + /** FinalizeWriteStreamRequest name. */ + public name: string; + + /** + * Creates a new FinalizeWriteStreamRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns FinalizeWriteStreamRequest instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest): google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest; + + /** + * Encodes the specified FinalizeWriteStreamRequest message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest.verify|verify} messages. + * @param message FinalizeWriteStreamRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FinalizeWriteStreamRequest message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest.verify|verify} messages. + * @param message FinalizeWriteStreamRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FinalizeWriteStreamRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FinalizeWriteStreamRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest; + + /** + * Decodes a FinalizeWriteStreamRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FinalizeWriteStreamRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest; + + /** + * Verifies a FinalizeWriteStreamRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FinalizeWriteStreamRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FinalizeWriteStreamRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest; + + /** + * Creates a plain object from a FinalizeWriteStreamRequest message. Also converts values to other types if specified. + * @param message FinalizeWriteStreamRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FinalizeWriteStreamRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FinalizeWriteStreamRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FinalizeWriteStreamResponse. */ + interface IFinalizeWriteStreamResponse { + + /** FinalizeWriteStreamResponse rowCount */ + rowCount?: (number|Long|string|null); + } + + /** Represents a FinalizeWriteStreamResponse. */ + class FinalizeWriteStreamResponse implements IFinalizeWriteStreamResponse { + + /** + * Constructs a new FinalizeWriteStreamResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamResponse); + + /** FinalizeWriteStreamResponse rowCount. */ + public rowCount: (number|Long|string); + + /** + * Creates a new FinalizeWriteStreamResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns FinalizeWriteStreamResponse instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamResponse): google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse; + + /** + * Encodes the specified FinalizeWriteStreamResponse message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse.verify|verify} messages. + * @param message FinalizeWriteStreamResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FinalizeWriteStreamResponse message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse.verify|verify} messages. + * @param message FinalizeWriteStreamResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FinalizeWriteStreamResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FinalizeWriteStreamResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse; + + /** + * Decodes a FinalizeWriteStreamResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FinalizeWriteStreamResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse; + + /** + * Verifies a FinalizeWriteStreamResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FinalizeWriteStreamResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FinalizeWriteStreamResponse + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse; + + /** + * Creates a plain object from a FinalizeWriteStreamResponse message. Also converts values to other types if specified. + * @param message FinalizeWriteStreamResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FinalizeWriteStreamResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FinalizeWriteStreamResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FlushRowsRequest. */ + interface IFlushRowsRequest { + + /** FlushRowsRequest writeStream */ + writeStream?: (string|null); + + /** FlushRowsRequest offset */ + offset?: (google.protobuf.IInt64Value|null); + } + + /** Represents a FlushRowsRequest. */ + class FlushRowsRequest implements IFlushRowsRequest { + + /** + * Constructs a new FlushRowsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest); + + /** FlushRowsRequest writeStream. */ + public writeStream: string; + + /** FlushRowsRequest offset. */ + public offset?: (google.protobuf.IInt64Value|null); + + /** + * Creates a new FlushRowsRequest instance using the specified properties. + * @param [properties] Properties to set + * @returns FlushRowsRequest instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest): google.cloud.bigquery.storage.v1beta2.FlushRowsRequest; + + /** + * Encodes the specified FlushRowsRequest message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.FlushRowsRequest.verify|verify} messages. + * @param message FlushRowsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FlushRowsRequest message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.FlushRowsRequest.verify|verify} messages. + * @param message FlushRowsRequest message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FlushRowsRequest message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FlushRowsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.FlushRowsRequest; + + /** + * Decodes a FlushRowsRequest message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FlushRowsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.FlushRowsRequest; + + /** + * Verifies a FlushRowsRequest message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FlushRowsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FlushRowsRequest + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.FlushRowsRequest; + + /** + * Creates a plain object from a FlushRowsRequest message. Also converts values to other types if specified. + * @param message FlushRowsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.FlushRowsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FlushRowsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FlushRowsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FlushRowsResponse. */ + interface IFlushRowsResponse { + + /** FlushRowsResponse offset */ + offset?: (number|Long|string|null); + } + + /** Represents a FlushRowsResponse. */ + class FlushRowsResponse implements IFlushRowsResponse { + + /** + * Constructs a new FlushRowsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IFlushRowsResponse); + + /** FlushRowsResponse offset. */ + public offset: (number|Long|string); + + /** + * Creates a new FlushRowsResponse instance using the specified properties. + * @param [properties] Properties to set + * @returns FlushRowsResponse instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IFlushRowsResponse): google.cloud.bigquery.storage.v1beta2.FlushRowsResponse; + + /** + * Encodes the specified FlushRowsResponse message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.FlushRowsResponse.verify|verify} messages. + * @param message FlushRowsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IFlushRowsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FlushRowsResponse message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.FlushRowsResponse.verify|verify} messages. + * @param message FlushRowsResponse message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IFlushRowsResponse, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FlushRowsResponse message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FlushRowsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.FlushRowsResponse; + + /** + * Decodes a FlushRowsResponse message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FlushRowsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.FlushRowsResponse; + + /** + * Verifies a FlushRowsResponse message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a FlushRowsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FlushRowsResponse + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.FlushRowsResponse; + + /** + * Creates a plain object from a FlushRowsResponse message. Also converts values to other types if specified. + * @param message FlushRowsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.FlushRowsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FlushRowsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FlushRowsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a StorageError. */ + interface IStorageError { + + /** StorageError code */ + code?: (google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode|keyof typeof google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode|null); + + /** StorageError entity */ + entity?: (string|null); + + /** StorageError errorMessage */ + errorMessage?: (string|null); + } + + /** Represents a StorageError. */ + class StorageError implements IStorageError { + + /** + * Constructs a new StorageError. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IStorageError); + + /** StorageError code. */ + public code: (google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode|keyof typeof google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode); + + /** StorageError entity. */ + public entity: string; + + /** StorageError errorMessage. */ + public errorMessage: string; + + /** + * Creates a new StorageError instance using the specified properties. + * @param [properties] Properties to set + * @returns StorageError instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IStorageError): google.cloud.bigquery.storage.v1beta2.StorageError; + + /** + * Encodes the specified StorageError message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.StorageError.verify|verify} messages. + * @param message StorageError message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IStorageError, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified StorageError message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.StorageError.verify|verify} messages. + * @param message StorageError message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IStorageError, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a StorageError message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns StorageError + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.StorageError; + + /** + * Decodes a StorageError message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns StorageError + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.StorageError; + + /** + * Verifies a StorageError message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a StorageError message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StorageError + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.StorageError; + + /** + * Creates a plain object from a StorageError message. Also converts values to other types if specified. + * @param message StorageError + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.StorageError, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StorageError to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StorageError + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace StorageError { + + /** StorageErrorCode enum. */ + enum StorageErrorCode { + STORAGE_ERROR_CODE_UNSPECIFIED = 0, + TABLE_NOT_FOUND = 1, + STREAM_ALREADY_COMMITTED = 2, + STREAM_NOT_FOUND = 3, + INVALID_STREAM_TYPE = 4, + INVALID_STREAM_STATE = 5, + STREAM_FINALIZED = 6 + } + } + + /** DataFormat enum. */ + enum DataFormat { + DATA_FORMAT_UNSPECIFIED = 0, + AVRO = 1, + ARROW = 2 + } + + /** Properties of a ReadSession. */ + interface IReadSession { + + /** ReadSession name */ + name?: (string|null); + + /** ReadSession expireTime */ + expireTime?: (google.protobuf.ITimestamp|null); + + /** ReadSession dataFormat */ + dataFormat?: (google.cloud.bigquery.storage.v1beta2.DataFormat|keyof typeof google.cloud.bigquery.storage.v1beta2.DataFormat|null); + + /** ReadSession avroSchema */ + avroSchema?: (google.cloud.bigquery.storage.v1beta2.IAvroSchema|null); + + /** ReadSession arrowSchema */ + arrowSchema?: (google.cloud.bigquery.storage.v1beta2.IArrowSchema|null); + + /** ReadSession table */ + table?: (string|null); + + /** ReadSession tableModifiers */ + tableModifiers?: (google.cloud.bigquery.storage.v1beta2.ReadSession.ITableModifiers|null); + + /** ReadSession readOptions */ + readOptions?: (google.cloud.bigquery.storage.v1beta2.ReadSession.ITableReadOptions|null); + + /** ReadSession streams */ + streams?: (google.cloud.bigquery.storage.v1beta2.IReadStream[]|null); + } + + /** Represents a ReadSession. */ + class ReadSession implements IReadSession { + + /** + * Constructs a new ReadSession. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IReadSession); + + /** ReadSession name. */ + public name: string; + + /** ReadSession expireTime. */ + public expireTime?: (google.protobuf.ITimestamp|null); + + /** ReadSession dataFormat. */ + public dataFormat: (google.cloud.bigquery.storage.v1beta2.DataFormat|keyof typeof google.cloud.bigquery.storage.v1beta2.DataFormat); + + /** ReadSession avroSchema. */ + public avroSchema?: (google.cloud.bigquery.storage.v1beta2.IAvroSchema|null); + + /** ReadSession arrowSchema. */ + public arrowSchema?: (google.cloud.bigquery.storage.v1beta2.IArrowSchema|null); + + /** ReadSession table. */ + public table: string; + + /** ReadSession tableModifiers. */ + public tableModifiers?: (google.cloud.bigquery.storage.v1beta2.ReadSession.ITableModifiers|null); + + /** ReadSession readOptions. */ + public readOptions?: (google.cloud.bigquery.storage.v1beta2.ReadSession.ITableReadOptions|null); + + /** ReadSession streams. */ + public streams: google.cloud.bigquery.storage.v1beta2.IReadStream[]; + + /** ReadSession schema. */ + public schema?: ("avroSchema"|"arrowSchema"); + + /** + * Creates a new ReadSession instance using the specified properties. + * @param [properties] Properties to set + * @returns ReadSession instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IReadSession): google.cloud.bigquery.storage.v1beta2.ReadSession; + + /** + * Encodes the specified ReadSession message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadSession.verify|verify} messages. + * @param message ReadSession message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IReadSession, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReadSession message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadSession.verify|verify} messages. + * @param message ReadSession message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IReadSession, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReadSession message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReadSession + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.ReadSession; + + /** + * Decodes a ReadSession message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReadSession + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.ReadSession; + + /** + * Verifies a ReadSession message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReadSession message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadSession + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.ReadSession; + + /** + * Creates a plain object from a ReadSession message. Also converts values to other types if specified. + * @param message ReadSession + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.ReadSession, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReadSession to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadSession + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ReadSession { + + /** Properties of a TableModifiers. */ + interface ITableModifiers { + + /** TableModifiers snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a TableModifiers. */ + class TableModifiers implements ITableModifiers { + + /** + * Constructs a new TableModifiers. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.ReadSession.ITableModifiers); + + /** TableModifiers snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a new TableModifiers instance using the specified properties. + * @param [properties] Properties to set + * @returns TableModifiers instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.ReadSession.ITableModifiers): google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers; + + /** + * Encodes the specified TableModifiers message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers.verify|verify} messages. + * @param message TableModifiers message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.ReadSession.ITableModifiers, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified TableModifiers message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers.verify|verify} messages. + * @param message TableModifiers message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.ReadSession.ITableModifiers, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a TableModifiers message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns TableModifiers + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers; + + /** + * Decodes a TableModifiers message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns TableModifiers + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers; + + /** + * Verifies a TableModifiers message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a TableModifiers message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TableModifiers + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers; + + /** + * Creates a plain object from a TableModifiers message. Also converts values to other types if specified. + * @param message TableModifiers + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TableModifiers to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TableModifiers + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a TableReadOptions. */ + interface ITableReadOptions { + + /** TableReadOptions selectedFields */ + selectedFields?: (string[]|null); + + /** TableReadOptions rowRestriction */ + rowRestriction?: (string|null); + + /** TableReadOptions arrowSerializationOptions */ + arrowSerializationOptions?: (google.cloud.bigquery.storage.v1beta2.IArrowSerializationOptions|null); + } + + /** Represents a TableReadOptions. */ + class TableReadOptions implements ITableReadOptions { + + /** + * Constructs a new TableReadOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.ReadSession.ITableReadOptions); + + /** TableReadOptions selectedFields. */ + public selectedFields: string[]; + + /** TableReadOptions rowRestriction. */ + public rowRestriction: string; + + /** TableReadOptions arrowSerializationOptions. */ + public arrowSerializationOptions?: (google.cloud.bigquery.storage.v1beta2.IArrowSerializationOptions|null); + + /** + * Creates a new TableReadOptions instance using the specified properties. + * @param [properties] Properties to set + * @returns TableReadOptions instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.ReadSession.ITableReadOptions): google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions; + + /** + * Encodes the specified TableReadOptions message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions.verify|verify} messages. + * @param message TableReadOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.ReadSession.ITableReadOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified TableReadOptions message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions.verify|verify} messages. + * @param message TableReadOptions message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.ReadSession.ITableReadOptions, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a TableReadOptions message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns TableReadOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions; + + /** + * Decodes a TableReadOptions message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns TableReadOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions; + + /** + * Verifies a TableReadOptions message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a TableReadOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TableReadOptions + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions; + + /** + * Creates a plain object from a TableReadOptions message. Also converts values to other types if specified. + * @param message TableReadOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TableReadOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TableReadOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a ReadStream. */ + interface IReadStream { + + /** ReadStream name */ + name?: (string|null); + } + + /** Represents a ReadStream. */ + class ReadStream implements IReadStream { + + /** + * Constructs a new ReadStream. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IReadStream); + + /** ReadStream name. */ + public name: string; + + /** + * Creates a new ReadStream instance using the specified properties. + * @param [properties] Properties to set + * @returns ReadStream instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IReadStream): google.cloud.bigquery.storage.v1beta2.ReadStream; + + /** + * Encodes the specified ReadStream message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadStream.verify|verify} messages. + * @param message ReadStream message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IReadStream, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ReadStream message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadStream.verify|verify} messages. + * @param message ReadStream message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IReadStream, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a ReadStream message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ReadStream + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.ReadStream; + + /** + * Decodes a ReadStream message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ReadStream + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.ReadStream; + + /** + * Verifies a ReadStream message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a ReadStream message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadStream + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.ReadStream; + + /** + * Creates a plain object from a ReadStream message. Also converts values to other types if specified. + * @param message ReadStream + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.ReadStream, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReadStream to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadStream + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WriteStream. */ + interface IWriteStream { + + /** WriteStream name */ + name?: (string|null); + + /** WriteStream type */ + type?: (google.cloud.bigquery.storage.v1beta2.WriteStream.Type|keyof typeof google.cloud.bigquery.storage.v1beta2.WriteStream.Type|null); + + /** WriteStream createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** WriteStream commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + + /** WriteStream tableSchema */ + tableSchema?: (google.cloud.bigquery.storage.v1beta2.ITableSchema|null); + } + + /** Represents a WriteStream. */ + class WriteStream implements IWriteStream { + + /** + * Constructs a new WriteStream. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.IWriteStream); + + /** WriteStream name. */ + public name: string; + + /** WriteStream type. */ + public type: (google.cloud.bigquery.storage.v1beta2.WriteStream.Type|keyof typeof google.cloud.bigquery.storage.v1beta2.WriteStream.Type); + + /** WriteStream createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** WriteStream commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); + + /** WriteStream tableSchema. */ + public tableSchema?: (google.cloud.bigquery.storage.v1beta2.ITableSchema|null); + + /** + * Creates a new WriteStream instance using the specified properties. + * @param [properties] Properties to set + * @returns WriteStream instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.IWriteStream): google.cloud.bigquery.storage.v1beta2.WriteStream; + + /** + * Encodes the specified WriteStream message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.WriteStream.verify|verify} messages. + * @param message WriteStream message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.IWriteStream, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified WriteStream message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.WriteStream.verify|verify} messages. + * @param message WriteStream message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.IWriteStream, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a WriteStream message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns WriteStream + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.WriteStream; + + /** + * Decodes a WriteStream message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns WriteStream + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.WriteStream; + + /** + * Verifies a WriteStream message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a WriteStream message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteStream + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.WriteStream; + + /** + * Creates a plain object from a WriteStream message. Also converts values to other types if specified. + * @param message WriteStream + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.WriteStream, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteStream to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteStream + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace WriteStream { + + /** Type enum. */ + enum Type { + TYPE_UNSPECIFIED = 0, + COMMITTED = 1, + PENDING = 2, + BUFFERED = 3 + } + } + + /** Properties of a TableSchema. */ + interface ITableSchema { + + /** TableSchema fields */ + fields?: (google.cloud.bigquery.storage.v1beta2.ITableFieldSchema[]|null); + } + + /** Represents a TableSchema. */ + class TableSchema implements ITableSchema { + + /** + * Constructs a new TableSchema. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.ITableSchema); + + /** TableSchema fields. */ + public fields: google.cloud.bigquery.storage.v1beta2.ITableFieldSchema[]; + + /** + * Creates a new TableSchema instance using the specified properties. + * @param [properties] Properties to set + * @returns TableSchema instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.ITableSchema): google.cloud.bigquery.storage.v1beta2.TableSchema; + + /** + * Encodes the specified TableSchema message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.TableSchema.verify|verify} messages. + * @param message TableSchema message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.ITableSchema, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified TableSchema message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.TableSchema.verify|verify} messages. + * @param message TableSchema message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.ITableSchema, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a TableSchema message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns TableSchema + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.TableSchema; + + /** + * Decodes a TableSchema message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns TableSchema + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.TableSchema; + + /** + * Verifies a TableSchema message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a TableSchema message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TableSchema + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.TableSchema; + + /** + * Creates a plain object from a TableSchema message. Also converts values to other types if specified. + * @param message TableSchema + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.TableSchema, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TableSchema to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TableSchema + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a TableFieldSchema. */ + interface ITableFieldSchema { + + /** TableFieldSchema name */ + name?: (string|null); + + /** TableFieldSchema type */ + type?: (google.cloud.bigquery.storage.v1beta2.TableFieldSchema.Type|keyof typeof google.cloud.bigquery.storage.v1beta2.TableFieldSchema.Type|null); + + /** TableFieldSchema mode */ + mode?: (google.cloud.bigquery.storage.v1beta2.TableFieldSchema.Mode|keyof typeof google.cloud.bigquery.storage.v1beta2.TableFieldSchema.Mode|null); + + /** TableFieldSchema fields */ + fields?: (google.cloud.bigquery.storage.v1beta2.ITableFieldSchema[]|null); + + /** TableFieldSchema description */ + description?: (string|null); + } + + /** Represents a TableFieldSchema. */ + class TableFieldSchema implements ITableFieldSchema { + + /** + * Constructs a new TableFieldSchema. + * @param [properties] Properties to set + */ + constructor(properties?: google.cloud.bigquery.storage.v1beta2.ITableFieldSchema); + + /** TableFieldSchema name. */ + public name: string; + + /** TableFieldSchema type. */ + public type: (google.cloud.bigquery.storage.v1beta2.TableFieldSchema.Type|keyof typeof google.cloud.bigquery.storage.v1beta2.TableFieldSchema.Type); + + /** TableFieldSchema mode. */ + public mode: (google.cloud.bigquery.storage.v1beta2.TableFieldSchema.Mode|keyof typeof google.cloud.bigquery.storage.v1beta2.TableFieldSchema.Mode); + + /** TableFieldSchema fields. */ + public fields: google.cloud.bigquery.storage.v1beta2.ITableFieldSchema[]; + + /** TableFieldSchema description. */ + public description: string; + + /** + * Creates a new TableFieldSchema instance using the specified properties. + * @param [properties] Properties to set + * @returns TableFieldSchema instance + */ + public static create(properties?: google.cloud.bigquery.storage.v1beta2.ITableFieldSchema): google.cloud.bigquery.storage.v1beta2.TableFieldSchema; + + /** + * Encodes the specified TableFieldSchema message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.TableFieldSchema.verify|verify} messages. + * @param message TableFieldSchema message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.cloud.bigquery.storage.v1beta2.ITableFieldSchema, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified TableFieldSchema message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.TableFieldSchema.verify|verify} messages. + * @param message TableFieldSchema message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.cloud.bigquery.storage.v1beta2.ITableFieldSchema, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a TableFieldSchema message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns TableFieldSchema + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.cloud.bigquery.storage.v1beta2.TableFieldSchema; + + /** + * Decodes a TableFieldSchema message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns TableFieldSchema + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.cloud.bigquery.storage.v1beta2.TableFieldSchema; + + /** + * Verifies a TableFieldSchema message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a TableFieldSchema message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TableFieldSchema + */ + public static fromObject(object: { [k: string]: any }): google.cloud.bigquery.storage.v1beta2.TableFieldSchema; + + /** + * Creates a plain object from a TableFieldSchema message. Also converts values to other types if specified. + * @param message TableFieldSchema + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.cloud.bigquery.storage.v1beta2.TableFieldSchema, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TableFieldSchema to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TableFieldSchema + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TableFieldSchema { + + /** Type enum. */ + enum Type { + TYPE_UNSPECIFIED = 0, + STRING = 1, + INT64 = 2, + DOUBLE = 3, + STRUCT = 4, + BYTES = 5, + BOOL = 6, + TIMESTAMP = 7, + DATE = 8, + TIME = 9, + DATETIME = 10, + GEOGRAPHY = 11, + NUMERIC = 12, + BIGNUMERIC = 13, + INTERVAL = 14, + JSON = 15 + } + + /** Mode enum. */ + enum Mode { + MODE_UNSPECIFIED = 0, + NULLABLE = 1, + REQUIRED = 2, + REPEATED = 3 + } + } + } } } } diff --git a/handwritten/bigquery-storage/protos/protos.js b/handwritten/bigquery-storage/protos/protos.js index ff0c3f1b261e..4e93d6735ead 100644 --- a/handwritten/bigquery-storage/protos/protos.js +++ b/handwritten/bigquery-storage/protos/protos.js @@ -29359,6 +29359,9841 @@ return v1beta1; })(); + storage.v1beta2 = (function() { + + /** + * Namespace v1beta2. + * @memberof google.cloud.bigquery.storage + * @namespace + */ + var v1beta2 = {}; + + v1beta2.ArrowSchema = (function() { + + /** + * Properties of an ArrowSchema. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IArrowSchema + * @property {Uint8Array|null} [serializedSchema] ArrowSchema serializedSchema + */ + + /** + * Constructs a new ArrowSchema. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents an ArrowSchema. + * @implements IArrowSchema + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IArrowSchema=} [properties] Properties to set + */ + function ArrowSchema(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * ArrowSchema serializedSchema. + * @member {Uint8Array} serializedSchema + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowSchema + * @instance + */ + ArrowSchema.prototype.serializedSchema = $util.newBuffer([]); + + /** + * Creates a new ArrowSchema instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowSchema + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IArrowSchema=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.ArrowSchema} ArrowSchema instance + */ + ArrowSchema.create = function create(properties) { + return new ArrowSchema(properties); + }; + + /** + * Encodes the specified ArrowSchema message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ArrowSchema.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowSchema + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IArrowSchema} message ArrowSchema message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ArrowSchema.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.serializedSchema != null && Object.hasOwnProperty.call(message, "serializedSchema")) + writer.uint32(/* id 1, wireType 2 =*/10).bytes(message.serializedSchema); + return writer; + }; + + /** + * Encodes the specified ArrowSchema message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ArrowSchema.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowSchema + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IArrowSchema} message ArrowSchema message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ArrowSchema.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ArrowSchema message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowSchema + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.ArrowSchema} ArrowSchema + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ArrowSchema.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.ArrowSchema(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.serializedSchema = reader.bytes(); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes an ArrowSchema message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowSchema + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.ArrowSchema} ArrowSchema + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ArrowSchema.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ArrowSchema message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowSchema + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ArrowSchema.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.serializedSchema != null && message.hasOwnProperty("serializedSchema")) + if (!(message.serializedSchema && typeof message.serializedSchema.length === "number" || $util.isString(message.serializedSchema))) + return "serializedSchema: buffer expected"; + return null; + }; + + /** + * Creates an ArrowSchema message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowSchema + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.ArrowSchema} ArrowSchema + */ + ArrowSchema.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.ArrowSchema) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.ArrowSchema(); + if (object.serializedSchema != null) + if (typeof object.serializedSchema === "string") + $util.base64.decode(object.serializedSchema, message.serializedSchema = $util.newBuffer($util.base64.length(object.serializedSchema)), 0); + else if (object.serializedSchema.length >= 0) + message.serializedSchema = object.serializedSchema; + return message; + }; + + /** + * Creates a plain object from an ArrowSchema message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowSchema + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ArrowSchema} message ArrowSchema + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ArrowSchema.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + if (options.bytes === String) + object.serializedSchema = ""; + else { + object.serializedSchema = []; + if (options.bytes !== Array) + object.serializedSchema = $util.newBuffer(object.serializedSchema); + } + if (message.serializedSchema != null && message.hasOwnProperty("serializedSchema")) + object.serializedSchema = options.bytes === String ? $util.base64.encode(message.serializedSchema, 0, message.serializedSchema.length) : options.bytes === Array ? Array.prototype.slice.call(message.serializedSchema) : message.serializedSchema; + return object; + }; + + /** + * Converts this ArrowSchema to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowSchema + * @instance + * @returns {Object.} JSON object + */ + ArrowSchema.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ArrowSchema + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowSchema + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ArrowSchema.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.ArrowSchema"; + }; + + return ArrowSchema; + })(); + + v1beta2.ArrowRecordBatch = (function() { + + /** + * Properties of an ArrowRecordBatch. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IArrowRecordBatch + * @property {Uint8Array|null} [serializedRecordBatch] ArrowRecordBatch serializedRecordBatch + */ + + /** + * Constructs a new ArrowRecordBatch. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents an ArrowRecordBatch. + * @implements IArrowRecordBatch + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IArrowRecordBatch=} [properties] Properties to set + */ + function ArrowRecordBatch(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * ArrowRecordBatch serializedRecordBatch. + * @member {Uint8Array} serializedRecordBatch + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch + * @instance + */ + ArrowRecordBatch.prototype.serializedRecordBatch = $util.newBuffer([]); + + /** + * Creates a new ArrowRecordBatch instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IArrowRecordBatch=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch} ArrowRecordBatch instance + */ + ArrowRecordBatch.create = function create(properties) { + return new ArrowRecordBatch(properties); + }; + + /** + * Encodes the specified ArrowRecordBatch message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IArrowRecordBatch} message ArrowRecordBatch message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ArrowRecordBatch.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.serializedRecordBatch != null && Object.hasOwnProperty.call(message, "serializedRecordBatch")) + writer.uint32(/* id 1, wireType 2 =*/10).bytes(message.serializedRecordBatch); + return writer; + }; + + /** + * Encodes the specified ArrowRecordBatch message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IArrowRecordBatch} message ArrowRecordBatch message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ArrowRecordBatch.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ArrowRecordBatch message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch} ArrowRecordBatch + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ArrowRecordBatch.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.serializedRecordBatch = reader.bytes(); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes an ArrowRecordBatch message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch} ArrowRecordBatch + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ArrowRecordBatch.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ArrowRecordBatch message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ArrowRecordBatch.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.serializedRecordBatch != null && message.hasOwnProperty("serializedRecordBatch")) + if (!(message.serializedRecordBatch && typeof message.serializedRecordBatch.length === "number" || $util.isString(message.serializedRecordBatch))) + return "serializedRecordBatch: buffer expected"; + return null; + }; + + /** + * Creates an ArrowRecordBatch message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch} ArrowRecordBatch + */ + ArrowRecordBatch.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch(); + if (object.serializedRecordBatch != null) + if (typeof object.serializedRecordBatch === "string") + $util.base64.decode(object.serializedRecordBatch, message.serializedRecordBatch = $util.newBuffer($util.base64.length(object.serializedRecordBatch)), 0); + else if (object.serializedRecordBatch.length >= 0) + message.serializedRecordBatch = object.serializedRecordBatch; + return message; + }; + + /** + * Creates a plain object from an ArrowRecordBatch message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch} message ArrowRecordBatch + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ArrowRecordBatch.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + if (options.bytes === String) + object.serializedRecordBatch = ""; + else { + object.serializedRecordBatch = []; + if (options.bytes !== Array) + object.serializedRecordBatch = $util.newBuffer(object.serializedRecordBatch); + } + if (message.serializedRecordBatch != null && message.hasOwnProperty("serializedRecordBatch")) + object.serializedRecordBatch = options.bytes === String ? $util.base64.encode(message.serializedRecordBatch, 0, message.serializedRecordBatch.length) : options.bytes === Array ? Array.prototype.slice.call(message.serializedRecordBatch) : message.serializedRecordBatch; + return object; + }; + + /** + * Converts this ArrowRecordBatch to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch + * @instance + * @returns {Object.} JSON object + */ + ArrowRecordBatch.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ArrowRecordBatch + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ArrowRecordBatch.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch"; + }; + + return ArrowRecordBatch; + })(); + + v1beta2.ArrowSerializationOptions = (function() { + + /** + * Properties of an ArrowSerializationOptions. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IArrowSerializationOptions + * @property {google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions.Format|null} [format] ArrowSerializationOptions format + */ + + /** + * Constructs a new ArrowSerializationOptions. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents an ArrowSerializationOptions. + * @implements IArrowSerializationOptions + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IArrowSerializationOptions=} [properties] Properties to set + */ + function ArrowSerializationOptions(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * ArrowSerializationOptions format. + * @member {google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions.Format} format + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions + * @instance + */ + ArrowSerializationOptions.prototype.format = 0; + + /** + * Creates a new ArrowSerializationOptions instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IArrowSerializationOptions=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions} ArrowSerializationOptions instance + */ + ArrowSerializationOptions.create = function create(properties) { + return new ArrowSerializationOptions(properties); + }; + + /** + * Encodes the specified ArrowSerializationOptions message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IArrowSerializationOptions} message ArrowSerializationOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ArrowSerializationOptions.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.format != null && Object.hasOwnProperty.call(message, "format")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.format); + return writer; + }; + + /** + * Encodes the specified ArrowSerializationOptions message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IArrowSerializationOptions} message ArrowSerializationOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ArrowSerializationOptions.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ArrowSerializationOptions message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions} ArrowSerializationOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ArrowSerializationOptions.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.format = reader.int32(); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes an ArrowSerializationOptions message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions} ArrowSerializationOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ArrowSerializationOptions.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ArrowSerializationOptions message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ArrowSerializationOptions.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.format != null && message.hasOwnProperty("format")) + switch (message.format) { + default: + return "format: enum value expected"; + case 0: + case 1: + case 2: + break; + } + return null; + }; + + /** + * Creates an ArrowSerializationOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions} ArrowSerializationOptions + */ + ArrowSerializationOptions.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions(); + switch (object.format) { + default: + if (typeof object.format === "number") { + message.format = object.format; + break; + } + break; + case "FORMAT_UNSPECIFIED": + case 0: + message.format = 0; + break; + case "ARROW_0_14": + case 1: + message.format = 1; + break; + case "ARROW_0_15": + case 2: + message.format = 2; + break; + } + return message; + }; + + /** + * Creates a plain object from an ArrowSerializationOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions} message ArrowSerializationOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ArrowSerializationOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.format = options.enums === String ? "FORMAT_UNSPECIFIED" : 0; + if (message.format != null && message.hasOwnProperty("format")) + object.format = options.enums === String ? $root.google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions.Format[message.format] === undefined ? message.format : $root.google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions.Format[message.format] : message.format; + return object; + }; + + /** + * Converts this ArrowSerializationOptions to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions + * @instance + * @returns {Object.} JSON object + */ + ArrowSerializationOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ArrowSerializationOptions + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ArrowSerializationOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions"; + }; + + /** + * Format enum. + * @name google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions.Format + * @enum {number} + * @property {number} FORMAT_UNSPECIFIED=0 FORMAT_UNSPECIFIED value + * @property {number} ARROW_0_14=1 ARROW_0_14 value + * @property {number} ARROW_0_15=2 ARROW_0_15 value + */ + ArrowSerializationOptions.Format = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "FORMAT_UNSPECIFIED"] = 0; + values[valuesById[1] = "ARROW_0_14"] = 1; + values[valuesById[2] = "ARROW_0_15"] = 2; + return values; + })(); + + return ArrowSerializationOptions; + })(); + + v1beta2.AvroSchema = (function() { + + /** + * Properties of an AvroSchema. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IAvroSchema + * @property {string|null} [schema] AvroSchema schema + */ + + /** + * Constructs a new AvroSchema. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents an AvroSchema. + * @implements IAvroSchema + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IAvroSchema=} [properties] Properties to set + */ + function AvroSchema(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * AvroSchema schema. + * @member {string} schema + * @memberof google.cloud.bigquery.storage.v1beta2.AvroSchema + * @instance + */ + AvroSchema.prototype.schema = ""; + + /** + * Creates a new AvroSchema instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.AvroSchema + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IAvroSchema=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.AvroSchema} AvroSchema instance + */ + AvroSchema.create = function create(properties) { + return new AvroSchema(properties); + }; + + /** + * Encodes the specified AvroSchema message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AvroSchema.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.AvroSchema + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IAvroSchema} message AvroSchema message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AvroSchema.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.schema != null && Object.hasOwnProperty.call(message, "schema")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.schema); + return writer; + }; + + /** + * Encodes the specified AvroSchema message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AvroSchema.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.AvroSchema + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IAvroSchema} message AvroSchema message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AvroSchema.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an AvroSchema message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.AvroSchema + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.AvroSchema} AvroSchema + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AvroSchema.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.AvroSchema(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.schema = reader.string(); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes an AvroSchema message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.AvroSchema + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.AvroSchema} AvroSchema + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AvroSchema.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an AvroSchema message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.AvroSchema + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + AvroSchema.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.schema != null && message.hasOwnProperty("schema")) + if (!$util.isString(message.schema)) + return "schema: string expected"; + return null; + }; + + /** + * Creates an AvroSchema message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.AvroSchema + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.AvroSchema} AvroSchema + */ + AvroSchema.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.AvroSchema) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.AvroSchema(); + if (object.schema != null) + message.schema = String(object.schema); + return message; + }; + + /** + * Creates a plain object from an AvroSchema message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.AvroSchema + * @static + * @param {google.cloud.bigquery.storage.v1beta2.AvroSchema} message AvroSchema + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + AvroSchema.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.schema = ""; + if (message.schema != null && message.hasOwnProperty("schema")) + object.schema = message.schema; + return object; + }; + + /** + * Converts this AvroSchema to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.AvroSchema + * @instance + * @returns {Object.} JSON object + */ + AvroSchema.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for AvroSchema + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.AvroSchema + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + AvroSchema.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.AvroSchema"; + }; + + return AvroSchema; + })(); + + v1beta2.AvroRows = (function() { + + /** + * Properties of an AvroRows. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IAvroRows + * @property {Uint8Array|null} [serializedBinaryRows] AvroRows serializedBinaryRows + */ + + /** + * Constructs a new AvroRows. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents an AvroRows. + * @implements IAvroRows + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IAvroRows=} [properties] Properties to set + */ + function AvroRows(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * AvroRows serializedBinaryRows. + * @member {Uint8Array} serializedBinaryRows + * @memberof google.cloud.bigquery.storage.v1beta2.AvroRows + * @instance + */ + AvroRows.prototype.serializedBinaryRows = $util.newBuffer([]); + + /** + * Creates a new AvroRows instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.AvroRows + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IAvroRows=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.AvroRows} AvroRows instance + */ + AvroRows.create = function create(properties) { + return new AvroRows(properties); + }; + + /** + * Encodes the specified AvroRows message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AvroRows.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.AvroRows + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IAvroRows} message AvroRows message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AvroRows.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.serializedBinaryRows != null && Object.hasOwnProperty.call(message, "serializedBinaryRows")) + writer.uint32(/* id 1, wireType 2 =*/10).bytes(message.serializedBinaryRows); + return writer; + }; + + /** + * Encodes the specified AvroRows message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AvroRows.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.AvroRows + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IAvroRows} message AvroRows message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AvroRows.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an AvroRows message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.AvroRows + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.AvroRows} AvroRows + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AvroRows.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.AvroRows(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.serializedBinaryRows = reader.bytes(); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes an AvroRows message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.AvroRows + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.AvroRows} AvroRows + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AvroRows.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an AvroRows message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.AvroRows + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + AvroRows.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.serializedBinaryRows != null && message.hasOwnProperty("serializedBinaryRows")) + if (!(message.serializedBinaryRows && typeof message.serializedBinaryRows.length === "number" || $util.isString(message.serializedBinaryRows))) + return "serializedBinaryRows: buffer expected"; + return null; + }; + + /** + * Creates an AvroRows message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.AvroRows + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.AvroRows} AvroRows + */ + AvroRows.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.AvroRows) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.AvroRows(); + if (object.serializedBinaryRows != null) + if (typeof object.serializedBinaryRows === "string") + $util.base64.decode(object.serializedBinaryRows, message.serializedBinaryRows = $util.newBuffer($util.base64.length(object.serializedBinaryRows)), 0); + else if (object.serializedBinaryRows.length >= 0) + message.serializedBinaryRows = object.serializedBinaryRows; + return message; + }; + + /** + * Creates a plain object from an AvroRows message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.AvroRows + * @static + * @param {google.cloud.bigquery.storage.v1beta2.AvroRows} message AvroRows + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + AvroRows.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + if (options.bytes === String) + object.serializedBinaryRows = ""; + else { + object.serializedBinaryRows = []; + if (options.bytes !== Array) + object.serializedBinaryRows = $util.newBuffer(object.serializedBinaryRows); + } + if (message.serializedBinaryRows != null && message.hasOwnProperty("serializedBinaryRows")) + object.serializedBinaryRows = options.bytes === String ? $util.base64.encode(message.serializedBinaryRows, 0, message.serializedBinaryRows.length) : options.bytes === Array ? Array.prototype.slice.call(message.serializedBinaryRows) : message.serializedBinaryRows; + return object; + }; + + /** + * Converts this AvroRows to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.AvroRows + * @instance + * @returns {Object.} JSON object + */ + AvroRows.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for AvroRows + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.AvroRows + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + AvroRows.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.AvroRows"; + }; + + return AvroRows; + })(); + + v1beta2.ProtoSchema = (function() { + + /** + * Properties of a ProtoSchema. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IProtoSchema + * @property {google.protobuf.IDescriptorProto|null} [protoDescriptor] ProtoSchema protoDescriptor + */ + + /** + * Constructs a new ProtoSchema. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a ProtoSchema. + * @implements IProtoSchema + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IProtoSchema=} [properties] Properties to set + */ + function ProtoSchema(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * ProtoSchema protoDescriptor. + * @member {google.protobuf.IDescriptorProto|null|undefined} protoDescriptor + * @memberof google.cloud.bigquery.storage.v1beta2.ProtoSchema + * @instance + */ + ProtoSchema.prototype.protoDescriptor = null; + + /** + * Creates a new ProtoSchema instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.ProtoSchema + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IProtoSchema=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.ProtoSchema} ProtoSchema instance + */ + ProtoSchema.create = function create(properties) { + return new ProtoSchema(properties); + }; + + /** + * Encodes the specified ProtoSchema message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ProtoSchema.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.ProtoSchema + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IProtoSchema} message ProtoSchema message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ProtoSchema.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.protoDescriptor != null && Object.hasOwnProperty.call(message, "protoDescriptor")) + $root.google.protobuf.DescriptorProto.encode(message.protoDescriptor, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ProtoSchema message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ProtoSchema.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ProtoSchema + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IProtoSchema} message ProtoSchema message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ProtoSchema.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ProtoSchema message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.ProtoSchema + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.ProtoSchema} ProtoSchema + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ProtoSchema.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.ProtoSchema(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.protoDescriptor = $root.google.protobuf.DescriptorProto.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a ProtoSchema message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ProtoSchema + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.ProtoSchema} ProtoSchema + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ProtoSchema.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ProtoSchema message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.ProtoSchema + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ProtoSchema.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.protoDescriptor != null && message.hasOwnProperty("protoDescriptor")) { + var error = $root.google.protobuf.DescriptorProto.verify(message.protoDescriptor, long + 1); + if (error) + return "protoDescriptor." + error; + } + return null; + }; + + /** + * Creates a ProtoSchema message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.ProtoSchema + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.ProtoSchema} ProtoSchema + */ + ProtoSchema.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.ProtoSchema) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.ProtoSchema(); + if (object.protoDescriptor != null) { + if (typeof object.protoDescriptor !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.ProtoSchema.protoDescriptor: object expected"); + message.protoDescriptor = $root.google.protobuf.DescriptorProto.fromObject(object.protoDescriptor, long + 1); + } + return message; + }; + + /** + * Creates a plain object from a ProtoSchema message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.ProtoSchema + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ProtoSchema} message ProtoSchema + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ProtoSchema.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.protoDescriptor = null; + if (message.protoDescriptor != null && message.hasOwnProperty("protoDescriptor")) + object.protoDescriptor = $root.google.protobuf.DescriptorProto.toObject(message.protoDescriptor, options); + return object; + }; + + /** + * Converts this ProtoSchema to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.ProtoSchema + * @instance + * @returns {Object.} JSON object + */ + ProtoSchema.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ProtoSchema + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.ProtoSchema + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ProtoSchema.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.ProtoSchema"; + }; + + return ProtoSchema; + })(); + + v1beta2.ProtoRows = (function() { + + /** + * Properties of a ProtoRows. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IProtoRows + * @property {Array.|null} [serializedRows] ProtoRows serializedRows + */ + + /** + * Constructs a new ProtoRows. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a ProtoRows. + * @implements IProtoRows + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IProtoRows=} [properties] Properties to set + */ + function ProtoRows(properties) { + this.serializedRows = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * ProtoRows serializedRows. + * @member {Array.} serializedRows + * @memberof google.cloud.bigquery.storage.v1beta2.ProtoRows + * @instance + */ + ProtoRows.prototype.serializedRows = $util.emptyArray; + + /** + * Creates a new ProtoRows instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.ProtoRows + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IProtoRows=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.ProtoRows} ProtoRows instance + */ + ProtoRows.create = function create(properties) { + return new ProtoRows(properties); + }; + + /** + * Encodes the specified ProtoRows message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ProtoRows.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.ProtoRows + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IProtoRows} message ProtoRows message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ProtoRows.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.serializedRows != null && message.serializedRows.length) + for (var i = 0; i < message.serializedRows.length; ++i) + writer.uint32(/* id 1, wireType 2 =*/10).bytes(message.serializedRows[i]); + return writer; + }; + + /** + * Encodes the specified ProtoRows message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ProtoRows.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ProtoRows + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IProtoRows} message ProtoRows message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ProtoRows.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ProtoRows message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.ProtoRows + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.ProtoRows} ProtoRows + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ProtoRows.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.ProtoRows(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.serializedRows && message.serializedRows.length)) + message.serializedRows = []; + message.serializedRows.push(reader.bytes()); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a ProtoRows message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ProtoRows + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.ProtoRows} ProtoRows + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ProtoRows.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ProtoRows message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.ProtoRows + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ProtoRows.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.serializedRows != null && message.hasOwnProperty("serializedRows")) { + if (!Array.isArray(message.serializedRows)) + return "serializedRows: array expected"; + for (var i = 0; i < message.serializedRows.length; ++i) + if (!(message.serializedRows[i] && typeof message.serializedRows[i].length === "number" || $util.isString(message.serializedRows[i]))) + return "serializedRows: buffer[] expected"; + } + return null; + }; + + /** + * Creates a ProtoRows message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.ProtoRows + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.ProtoRows} ProtoRows + */ + ProtoRows.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.ProtoRows) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.ProtoRows(); + if (object.serializedRows) { + if (!Array.isArray(object.serializedRows)) + throw TypeError(".google.cloud.bigquery.storage.v1beta2.ProtoRows.serializedRows: array expected"); + message.serializedRows = []; + for (var i = 0; i < object.serializedRows.length; ++i) + if (typeof object.serializedRows[i] === "string") + $util.base64.decode(object.serializedRows[i], message.serializedRows[i] = $util.newBuffer($util.base64.length(object.serializedRows[i])), 0); + else if (object.serializedRows[i].length >= 0) + message.serializedRows[i] = object.serializedRows[i]; + } + return message; + }; + + /** + * Creates a plain object from a ProtoRows message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.ProtoRows + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ProtoRows} message ProtoRows + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ProtoRows.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.serializedRows = []; + if (message.serializedRows && message.serializedRows.length) { + object.serializedRows = []; + for (var j = 0; j < message.serializedRows.length; ++j) + object.serializedRows[j] = options.bytes === String ? $util.base64.encode(message.serializedRows[j], 0, message.serializedRows[j].length) : options.bytes === Array ? Array.prototype.slice.call(message.serializedRows[j]) : message.serializedRows[j]; + } + return object; + }; + + /** + * Converts this ProtoRows to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.ProtoRows + * @instance + * @returns {Object.} JSON object + */ + ProtoRows.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ProtoRows + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.ProtoRows + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ProtoRows.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.ProtoRows"; + }; + + return ProtoRows; + })(); + + v1beta2.BigQueryRead = (function() { + + /** + * Constructs a new BigQueryRead service. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a BigQueryRead + * @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 BigQueryRead(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + + (BigQueryRead.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = BigQueryRead; + + /** + * Creates new BigQueryRead service using the specified rpc implementation. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryRead + * @static + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {BigQueryRead} RPC service. Useful where requests and/or responses are streamed. + */ + BigQueryRead.create = function create(rpcImpl, requestDelimited, responseDelimited) { + return new this(rpcImpl, requestDelimited, responseDelimited); + }; + + /** + * Callback as used by {@link google.cloud.bigquery.storage.v1beta2.BigQueryRead|createReadSession}. + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryRead + * @typedef CreateReadSessionCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.bigquery.storage.v1beta2.ReadSession} [response] ReadSession + */ + + /** + * Calls CreateReadSession. + * @function createReadSession + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryRead + * @instance + * @param {google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest} request CreateReadSessionRequest message or plain object + * @param {google.cloud.bigquery.storage.v1beta2.BigQueryRead.CreateReadSessionCallback} callback Node-style callback called with the error, if any, and ReadSession + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(BigQueryRead.prototype.createReadSession = function createReadSession(request, callback) { + return this.rpcCall(createReadSession, $root.google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest, $root.google.cloud.bigquery.storage.v1beta2.ReadSession, request, callback); + }, "name", { value: "CreateReadSession" }); + + /** + * Calls CreateReadSession. + * @function createReadSession + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryRead + * @instance + * @param {google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest} request CreateReadSessionRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.bigquery.storage.v1beta2.BigQueryRead|readRows}. + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryRead + * @typedef ReadRowsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.bigquery.storage.v1beta2.ReadRowsResponse} [response] ReadRowsResponse + */ + + /** + * Calls ReadRows. + * @function readRows + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryRead + * @instance + * @param {google.cloud.bigquery.storage.v1beta2.IReadRowsRequest} request ReadRowsRequest message or plain object + * @param {google.cloud.bigquery.storage.v1beta2.BigQueryRead.ReadRowsCallback} callback Node-style callback called with the error, if any, and ReadRowsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(BigQueryRead.prototype.readRows = function readRows(request, callback) { + return this.rpcCall(readRows, $root.google.cloud.bigquery.storage.v1beta2.ReadRowsRequest, $root.google.cloud.bigquery.storage.v1beta2.ReadRowsResponse, request, callback); + }, "name", { value: "ReadRows" }); + + /** + * Calls ReadRows. + * @function readRows + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryRead + * @instance + * @param {google.cloud.bigquery.storage.v1beta2.IReadRowsRequest} request ReadRowsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.bigquery.storage.v1beta2.BigQueryRead|splitReadStream}. + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryRead + * @typedef SplitReadStreamCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse} [response] SplitReadStreamResponse + */ + + /** + * Calls SplitReadStream. + * @function splitReadStream + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryRead + * @instance + * @param {google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest} request SplitReadStreamRequest message or plain object + * @param {google.cloud.bigquery.storage.v1beta2.BigQueryRead.SplitReadStreamCallback} callback Node-style callback called with the error, if any, and SplitReadStreamResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(BigQueryRead.prototype.splitReadStream = function splitReadStream(request, callback) { + return this.rpcCall(splitReadStream, $root.google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest, $root.google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse, request, callback); + }, "name", { value: "SplitReadStream" }); + + /** + * Calls SplitReadStream. + * @function splitReadStream + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryRead + * @instance + * @param {google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest} request SplitReadStreamRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + return BigQueryRead; + })(); + + v1beta2.BigQueryWrite = (function() { + + /** + * Constructs a new BigQueryWrite service. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a BigQueryWrite + * @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 BigQueryWrite(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + + (BigQueryWrite.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = BigQueryWrite; + + /** + * Creates new BigQueryWrite service using the specified rpc implementation. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryWrite + * @static + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {BigQueryWrite} RPC service. Useful where requests and/or responses are streamed. + */ + BigQueryWrite.create = function create(rpcImpl, requestDelimited, responseDelimited) { + return new this(rpcImpl, requestDelimited, responseDelimited); + }; + + /** + * Callback as used by {@link google.cloud.bigquery.storage.v1beta2.BigQueryWrite|createWriteStream}. + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryWrite + * @typedef CreateWriteStreamCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.bigquery.storage.v1beta2.WriteStream} [response] WriteStream + */ + + /** + * Calls CreateWriteStream. + * @function createWriteStream + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryWrite + * @instance + * @param {google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest} request CreateWriteStreamRequest message or plain object + * @param {google.cloud.bigquery.storage.v1beta2.BigQueryWrite.CreateWriteStreamCallback} callback Node-style callback called with the error, if any, and WriteStream + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(BigQueryWrite.prototype.createWriteStream = function createWriteStream(request, callback) { + return this.rpcCall(createWriteStream, $root.google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest, $root.google.cloud.bigquery.storage.v1beta2.WriteStream, request, callback); + }, "name", { value: "CreateWriteStream" }); + + /** + * Calls CreateWriteStream. + * @function createWriteStream + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryWrite + * @instance + * @param {google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest} request CreateWriteStreamRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.bigquery.storage.v1beta2.BigQueryWrite|appendRows}. + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryWrite + * @typedef AppendRowsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.bigquery.storage.v1beta2.AppendRowsResponse} [response] AppendRowsResponse + */ + + /** + * Calls AppendRows. + * @function appendRows + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryWrite + * @instance + * @param {google.cloud.bigquery.storage.v1beta2.IAppendRowsRequest} request AppendRowsRequest message or plain object + * @param {google.cloud.bigquery.storage.v1beta2.BigQueryWrite.AppendRowsCallback} callback Node-style callback called with the error, if any, and AppendRowsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(BigQueryWrite.prototype.appendRows = function appendRows(request, callback) { + return this.rpcCall(appendRows, $root.google.cloud.bigquery.storage.v1beta2.AppendRowsRequest, $root.google.cloud.bigquery.storage.v1beta2.AppendRowsResponse, request, callback); + }, "name", { value: "AppendRows" }); + + /** + * Calls AppendRows. + * @function appendRows + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryWrite + * @instance + * @param {google.cloud.bigquery.storage.v1beta2.IAppendRowsRequest} request AppendRowsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.bigquery.storage.v1beta2.BigQueryWrite|getWriteStream}. + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryWrite + * @typedef GetWriteStreamCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.bigquery.storage.v1beta2.WriteStream} [response] WriteStream + */ + + /** + * Calls GetWriteStream. + * @function getWriteStream + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryWrite + * @instance + * @param {google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest} request GetWriteStreamRequest message or plain object + * @param {google.cloud.bigquery.storage.v1beta2.BigQueryWrite.GetWriteStreamCallback} callback Node-style callback called with the error, if any, and WriteStream + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(BigQueryWrite.prototype.getWriteStream = function getWriteStream(request, callback) { + return this.rpcCall(getWriteStream, $root.google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest, $root.google.cloud.bigquery.storage.v1beta2.WriteStream, request, callback); + }, "name", { value: "GetWriteStream" }); + + /** + * Calls GetWriteStream. + * @function getWriteStream + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryWrite + * @instance + * @param {google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest} request GetWriteStreamRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.bigquery.storage.v1beta2.BigQueryWrite|finalizeWriteStream}. + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryWrite + * @typedef FinalizeWriteStreamCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse} [response] FinalizeWriteStreamResponse + */ + + /** + * Calls FinalizeWriteStream. + * @function finalizeWriteStream + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryWrite + * @instance + * @param {google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest} request FinalizeWriteStreamRequest message or plain object + * @param {google.cloud.bigquery.storage.v1beta2.BigQueryWrite.FinalizeWriteStreamCallback} callback Node-style callback called with the error, if any, and FinalizeWriteStreamResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(BigQueryWrite.prototype.finalizeWriteStream = function finalizeWriteStream(request, callback) { + return this.rpcCall(finalizeWriteStream, $root.google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest, $root.google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse, request, callback); + }, "name", { value: "FinalizeWriteStream" }); + + /** + * Calls FinalizeWriteStream. + * @function finalizeWriteStream + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryWrite + * @instance + * @param {google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest} request FinalizeWriteStreamRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.bigquery.storage.v1beta2.BigQueryWrite|batchCommitWriteStreams}. + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryWrite + * @typedef BatchCommitWriteStreamsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse} [response] BatchCommitWriteStreamsResponse + */ + + /** + * Calls BatchCommitWriteStreams. + * @function batchCommitWriteStreams + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryWrite + * @instance + * @param {google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest} request BatchCommitWriteStreamsRequest message or plain object + * @param {google.cloud.bigquery.storage.v1beta2.BigQueryWrite.BatchCommitWriteStreamsCallback} callback Node-style callback called with the error, if any, and BatchCommitWriteStreamsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(BigQueryWrite.prototype.batchCommitWriteStreams = function batchCommitWriteStreams(request, callback) { + return this.rpcCall(batchCommitWriteStreams, $root.google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest, $root.google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse, request, callback); + }, "name", { value: "BatchCommitWriteStreams" }); + + /** + * Calls BatchCommitWriteStreams. + * @function batchCommitWriteStreams + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryWrite + * @instance + * @param {google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest} request BatchCommitWriteStreamsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.cloud.bigquery.storage.v1beta2.BigQueryWrite|flushRows}. + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryWrite + * @typedef FlushRowsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.cloud.bigquery.storage.v1beta2.FlushRowsResponse} [response] FlushRowsResponse + */ + + /** + * Calls FlushRows. + * @function flushRows + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryWrite + * @instance + * @param {google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest} request FlushRowsRequest message or plain object + * @param {google.cloud.bigquery.storage.v1beta2.BigQueryWrite.FlushRowsCallback} callback Node-style callback called with the error, if any, and FlushRowsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(BigQueryWrite.prototype.flushRows = function flushRows(request, callback) { + return this.rpcCall(flushRows, $root.google.cloud.bigquery.storage.v1beta2.FlushRowsRequest, $root.google.cloud.bigquery.storage.v1beta2.FlushRowsResponse, request, callback); + }, "name", { value: "FlushRows" }); + + /** + * Calls FlushRows. + * @function flushRows + * @memberof google.cloud.bigquery.storage.v1beta2.BigQueryWrite + * @instance + * @param {google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest} request FlushRowsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + return BigQueryWrite; + })(); + + v1beta2.CreateReadSessionRequest = (function() { + + /** + * Properties of a CreateReadSessionRequest. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface ICreateReadSessionRequest + * @property {string|null} [parent] CreateReadSessionRequest parent + * @property {google.cloud.bigquery.storage.v1beta2.IReadSession|null} [readSession] CreateReadSessionRequest readSession + * @property {number|null} [maxStreamCount] CreateReadSessionRequest maxStreamCount + */ + + /** + * Constructs a new CreateReadSessionRequest. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a CreateReadSessionRequest. + * @implements ICreateReadSessionRequest + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest=} [properties] Properties to set + */ + function CreateReadSessionRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateReadSessionRequest parent. + * @member {string} parent + * @memberof google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest + * @instance + */ + CreateReadSessionRequest.prototype.parent = ""; + + /** + * CreateReadSessionRequest readSession. + * @member {google.cloud.bigquery.storage.v1beta2.IReadSession|null|undefined} readSession + * @memberof google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest + * @instance + */ + CreateReadSessionRequest.prototype.readSession = null; + + /** + * CreateReadSessionRequest maxStreamCount. + * @member {number} maxStreamCount + * @memberof google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest + * @instance + */ + CreateReadSessionRequest.prototype.maxStreamCount = 0; + + /** + * Creates a new CreateReadSessionRequest instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest} CreateReadSessionRequest instance + */ + CreateReadSessionRequest.create = function create(properties) { + return new CreateReadSessionRequest(properties); + }; + + /** + * Encodes the specified CreateReadSessionRequest message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest} message CreateReadSessionRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateReadSessionRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.readSession != null && Object.hasOwnProperty.call(message, "readSession")) + $root.google.cloud.bigquery.storage.v1beta2.ReadSession.encode(message.readSession, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.maxStreamCount != null && Object.hasOwnProperty.call(message, "maxStreamCount")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.maxStreamCount); + return writer; + }; + + /** + * Encodes the specified CreateReadSessionRequest message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest} message CreateReadSessionRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateReadSessionRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CreateReadSessionRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest} CreateReadSessionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateReadSessionRequest.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.readSession = $root.google.cloud.bigquery.storage.v1beta2.ReadSession.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + case 3: { + message.maxStreamCount = reader.int32(); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a CreateReadSessionRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest} CreateReadSessionRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateReadSessionRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CreateReadSessionRequest message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CreateReadSessionRequest.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.readSession != null && message.hasOwnProperty("readSession")) { + var error = $root.google.cloud.bigquery.storage.v1beta2.ReadSession.verify(message.readSession, long + 1); + if (error) + return "readSession." + error; + } + if (message.maxStreamCount != null && message.hasOwnProperty("maxStreamCount")) + if (!$util.isInteger(message.maxStreamCount)) + return "maxStreamCount: integer expected"; + return null; + }; + + /** + * Creates a CreateReadSessionRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest} CreateReadSessionRequest + */ + CreateReadSessionRequest.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.readSession != null) { + if (typeof object.readSession !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest.readSession: object expected"); + message.readSession = $root.google.cloud.bigquery.storage.v1beta2.ReadSession.fromObject(object.readSession, long + 1); + } + if (object.maxStreamCount != null) + message.maxStreamCount = object.maxStreamCount | 0; + return message; + }; + + /** + * Creates a plain object from a CreateReadSessionRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest} message CreateReadSessionRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateReadSessionRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.readSession = null; + object.maxStreamCount = 0; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.readSession != null && message.hasOwnProperty("readSession")) + object.readSession = $root.google.cloud.bigquery.storage.v1beta2.ReadSession.toObject(message.readSession, options); + if (message.maxStreamCount != null && message.hasOwnProperty("maxStreamCount")) + object.maxStreamCount = message.maxStreamCount; + return object; + }; + + /** + * Converts this CreateReadSessionRequest to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest + * @instance + * @returns {Object.} JSON object + */ + CreateReadSessionRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateReadSessionRequest + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateReadSessionRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest"; + }; + + return CreateReadSessionRequest; + })(); + + v1beta2.ReadRowsRequest = (function() { + + /** + * Properties of a ReadRowsRequest. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IReadRowsRequest + * @property {string|null} [readStream] ReadRowsRequest readStream + * @property {number|Long|null} [offset] ReadRowsRequest offset + */ + + /** + * Constructs a new ReadRowsRequest. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a ReadRowsRequest. + * @implements IReadRowsRequest + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IReadRowsRequest=} [properties] Properties to set + */ + function ReadRowsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReadRowsRequest readStream. + * @member {string} readStream + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsRequest + * @instance + */ + ReadRowsRequest.prototype.readStream = ""; + + /** + * ReadRowsRequest offset. + * @member {number|Long} offset + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsRequest + * @instance + */ + ReadRowsRequest.prototype.offset = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Creates a new ReadRowsRequest instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IReadRowsRequest=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.ReadRowsRequest} ReadRowsRequest instance + */ + ReadRowsRequest.create = function create(properties) { + return new ReadRowsRequest(properties); + }; + + /** + * Encodes the specified ReadRowsRequest message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadRowsRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IReadRowsRequest} message ReadRowsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReadRowsRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.readStream != null && Object.hasOwnProperty.call(message, "readStream")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.readStream); + if (message.offset != null && Object.hasOwnProperty.call(message, "offset")) + writer.uint32(/* id 2, wireType 0 =*/16).int64(message.offset); + return writer; + }; + + /** + * Encodes the specified ReadRowsRequest message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadRowsRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IReadRowsRequest} message ReadRowsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReadRowsRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ReadRowsRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.ReadRowsRequest} ReadRowsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReadRowsRequest.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.ReadRowsRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.readStream = reader.string(); + break; + } + case 2: { + message.offset = reader.int64(); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a ReadRowsRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.ReadRowsRequest} ReadRowsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReadRowsRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ReadRowsRequest message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ReadRowsRequest.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.readStream != null && message.hasOwnProperty("readStream")) + if (!$util.isString(message.readStream)) + return "readStream: string expected"; + if (message.offset != null && message.hasOwnProperty("offset")) + if (!$util.isInteger(message.offset) && !(message.offset && $util.isInteger(message.offset.low) && $util.isInteger(message.offset.high))) + return "offset: integer|Long expected"; + return null; + }; + + /** + * Creates a ReadRowsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.ReadRowsRequest} ReadRowsRequest + */ + ReadRowsRequest.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.ReadRowsRequest) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.ReadRowsRequest(); + if (object.readStream != null) + message.readStream = String(object.readStream); + if (object.offset != null) + if ($util.Long) + (message.offset = $util.Long.fromValue(object.offset)).unsigned = false; + else if (typeof object.offset === "string") + message.offset = parseInt(object.offset, 10); + else if (typeof object.offset === "number") + message.offset = object.offset; + else if (typeof object.offset === "object") + message.offset = new $util.LongBits(object.offset.low >>> 0, object.offset.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from a ReadRowsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ReadRowsRequest} message ReadRowsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReadRowsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.readStream = ""; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.offset = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.offset = options.longs === String ? "0" : 0; + } + if (message.readStream != null && message.hasOwnProperty("readStream")) + object.readStream = message.readStream; + if (message.offset != null && message.hasOwnProperty("offset")) + if (typeof message.offset === "number") + object.offset = options.longs === String ? String(message.offset) : message.offset; + else + object.offset = options.longs === String ? $util.Long.prototype.toString.call(message.offset) : options.longs === Number ? new $util.LongBits(message.offset.low >>> 0, message.offset.high >>> 0).toNumber() : message.offset; + return object; + }; + + /** + * Converts this ReadRowsRequest to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsRequest + * @instance + * @returns {Object.} JSON object + */ + ReadRowsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReadRowsRequest + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReadRowsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.ReadRowsRequest"; + }; + + return ReadRowsRequest; + })(); + + v1beta2.ThrottleState = (function() { + + /** + * Properties of a ThrottleState. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IThrottleState + * @property {number|null} [throttlePercent] ThrottleState throttlePercent + */ + + /** + * Constructs a new ThrottleState. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a ThrottleState. + * @implements IThrottleState + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IThrottleState=} [properties] Properties to set + */ + function ThrottleState(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * ThrottleState throttlePercent. + * @member {number} throttlePercent + * @memberof google.cloud.bigquery.storage.v1beta2.ThrottleState + * @instance + */ + ThrottleState.prototype.throttlePercent = 0; + + /** + * Creates a new ThrottleState instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.ThrottleState + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IThrottleState=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.ThrottleState} ThrottleState instance + */ + ThrottleState.create = function create(properties) { + return new ThrottleState(properties); + }; + + /** + * Encodes the specified ThrottleState message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ThrottleState.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.ThrottleState + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IThrottleState} message ThrottleState message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ThrottleState.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.throttlePercent != null && Object.hasOwnProperty.call(message, "throttlePercent")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.throttlePercent); + return writer; + }; + + /** + * Encodes the specified ThrottleState message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ThrottleState.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ThrottleState + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IThrottleState} message ThrottleState message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ThrottleState.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ThrottleState message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.ThrottleState + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.ThrottleState} ThrottleState + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ThrottleState.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.ThrottleState(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.throttlePercent = reader.int32(); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a ThrottleState message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ThrottleState + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.ThrottleState} ThrottleState + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ThrottleState.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ThrottleState message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.ThrottleState + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ThrottleState.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.throttlePercent != null && message.hasOwnProperty("throttlePercent")) + if (!$util.isInteger(message.throttlePercent)) + return "throttlePercent: integer expected"; + return null; + }; + + /** + * Creates a ThrottleState message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.ThrottleState + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.ThrottleState} ThrottleState + */ + ThrottleState.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.ThrottleState) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.ThrottleState(); + if (object.throttlePercent != null) + message.throttlePercent = object.throttlePercent | 0; + return message; + }; + + /** + * Creates a plain object from a ThrottleState message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.ThrottleState + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ThrottleState} message ThrottleState + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ThrottleState.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.throttlePercent = 0; + if (message.throttlePercent != null && message.hasOwnProperty("throttlePercent")) + object.throttlePercent = message.throttlePercent; + return object; + }; + + /** + * Converts this ThrottleState to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.ThrottleState + * @instance + * @returns {Object.} JSON object + */ + ThrottleState.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ThrottleState + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.ThrottleState + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ThrottleState.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.ThrottleState"; + }; + + return ThrottleState; + })(); + + v1beta2.StreamStats = (function() { + + /** + * Properties of a StreamStats. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IStreamStats + * @property {google.cloud.bigquery.storage.v1beta2.StreamStats.IProgress|null} [progress] StreamStats progress + */ + + /** + * Constructs a new StreamStats. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a StreamStats. + * @implements IStreamStats + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IStreamStats=} [properties] Properties to set + */ + function StreamStats(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * StreamStats progress. + * @member {google.cloud.bigquery.storage.v1beta2.StreamStats.IProgress|null|undefined} progress + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats + * @instance + */ + StreamStats.prototype.progress = null; + + /** + * Creates a new StreamStats instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IStreamStats=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.StreamStats} StreamStats instance + */ + StreamStats.create = function create(properties) { + return new StreamStats(properties); + }; + + /** + * Encodes the specified StreamStats message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.StreamStats.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IStreamStats} message StreamStats message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + StreamStats.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.progress != null && Object.hasOwnProperty.call(message, "progress")) + $root.google.cloud.bigquery.storage.v1beta2.StreamStats.Progress.encode(message.progress, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified StreamStats message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.StreamStats.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IStreamStats} message StreamStats message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + StreamStats.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a StreamStats message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.StreamStats} StreamStats + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + StreamStats.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.StreamStats(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 2: { + message.progress = $root.google.cloud.bigquery.storage.v1beta2.StreamStats.Progress.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a StreamStats message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.StreamStats} StreamStats + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + StreamStats.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a StreamStats message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + StreamStats.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.progress != null && message.hasOwnProperty("progress")) { + var error = $root.google.cloud.bigquery.storage.v1beta2.StreamStats.Progress.verify(message.progress, long + 1); + if (error) + return "progress." + error; + } + return null; + }; + + /** + * Creates a StreamStats message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.StreamStats} StreamStats + */ + StreamStats.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.StreamStats) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.StreamStats(); + if (object.progress != null) { + if (typeof object.progress !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.StreamStats.progress: object expected"); + message.progress = $root.google.cloud.bigquery.storage.v1beta2.StreamStats.Progress.fromObject(object.progress, long + 1); + } + return message; + }; + + /** + * Creates a plain object from a StreamStats message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats + * @static + * @param {google.cloud.bigquery.storage.v1beta2.StreamStats} message StreamStats + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + StreamStats.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.progress = null; + if (message.progress != null && message.hasOwnProperty("progress")) + object.progress = $root.google.cloud.bigquery.storage.v1beta2.StreamStats.Progress.toObject(message.progress, options); + return object; + }; + + /** + * Converts this StreamStats to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats + * @instance + * @returns {Object.} JSON object + */ + StreamStats.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for StreamStats + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + StreamStats.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.StreamStats"; + }; + + StreamStats.Progress = (function() { + + /** + * Properties of a Progress. + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats + * @interface IProgress + * @property {number|null} [atResponseStart] Progress atResponseStart + * @property {number|null} [atResponseEnd] Progress atResponseEnd + */ + + /** + * Constructs a new Progress. + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats + * @classdesc Represents a Progress. + * @implements IProgress + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.StreamStats.IProgress=} [properties] Properties to set + */ + function Progress(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * Progress atResponseStart. + * @member {number} atResponseStart + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats.Progress + * @instance + */ + Progress.prototype.atResponseStart = 0; + + /** + * Progress atResponseEnd. + * @member {number} atResponseEnd + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats.Progress + * @instance + */ + Progress.prototype.atResponseEnd = 0; + + /** + * Creates a new Progress instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats.Progress + * @static + * @param {google.cloud.bigquery.storage.v1beta2.StreamStats.IProgress=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.StreamStats.Progress} Progress instance + */ + Progress.create = function create(properties) { + return new Progress(properties); + }; + + /** + * Encodes the specified Progress message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.StreamStats.Progress.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats.Progress + * @static + * @param {google.cloud.bigquery.storage.v1beta2.StreamStats.IProgress} message Progress message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Progress.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.atResponseStart != null && Object.hasOwnProperty.call(message, "atResponseStart")) + writer.uint32(/* id 1, wireType 1 =*/9).double(message.atResponseStart); + if (message.atResponseEnd != null && Object.hasOwnProperty.call(message, "atResponseEnd")) + writer.uint32(/* id 2, wireType 1 =*/17).double(message.atResponseEnd); + return writer; + }; + + /** + * Encodes the specified Progress message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.StreamStats.Progress.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats.Progress + * @static + * @param {google.cloud.bigquery.storage.v1beta2.StreamStats.IProgress} message Progress message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + Progress.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a Progress message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats.Progress + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.StreamStats.Progress} Progress + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Progress.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.StreamStats.Progress(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.atResponseStart = reader.double(); + break; + } + case 2: { + message.atResponseEnd = reader.double(); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a Progress message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats.Progress + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.StreamStats.Progress} Progress + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + Progress.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a Progress message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats.Progress + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Progress.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.atResponseStart != null && message.hasOwnProperty("atResponseStart")) + if (typeof message.atResponseStart !== "number") + return "atResponseStart: number expected"; + if (message.atResponseEnd != null && message.hasOwnProperty("atResponseEnd")) + if (typeof message.atResponseEnd !== "number") + return "atResponseEnd: number expected"; + return null; + }; + + /** + * Creates a Progress message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats.Progress + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.StreamStats.Progress} Progress + */ + Progress.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.StreamStats.Progress) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.StreamStats.Progress(); + if (object.atResponseStart != null) + message.atResponseStart = Number(object.atResponseStart); + if (object.atResponseEnd != null) + message.atResponseEnd = Number(object.atResponseEnd); + return message; + }; + + /** + * Creates a plain object from a Progress message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats.Progress + * @static + * @param {google.cloud.bigquery.storage.v1beta2.StreamStats.Progress} message Progress + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Progress.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.atResponseStart = 0; + object.atResponseEnd = 0; + } + if (message.atResponseStart != null && message.hasOwnProperty("atResponseStart")) + object.atResponseStart = options.json && !isFinite(message.atResponseStart) ? String(message.atResponseStart) : message.atResponseStart; + if (message.atResponseEnd != null && message.hasOwnProperty("atResponseEnd")) + object.atResponseEnd = options.json && !isFinite(message.atResponseEnd) ? String(message.atResponseEnd) : message.atResponseEnd; + return object; + }; + + /** + * Converts this Progress to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats.Progress + * @instance + * @returns {Object.} JSON object + */ + Progress.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Progress + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.StreamStats.Progress + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Progress.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.StreamStats.Progress"; + }; + + return Progress; + })(); + + return StreamStats; + })(); + + v1beta2.ReadRowsResponse = (function() { + + /** + * Properties of a ReadRowsResponse. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IReadRowsResponse + * @property {google.cloud.bigquery.storage.v1beta2.IAvroRows|null} [avroRows] ReadRowsResponse avroRows + * @property {google.cloud.bigquery.storage.v1beta2.IArrowRecordBatch|null} [arrowRecordBatch] ReadRowsResponse arrowRecordBatch + * @property {number|Long|null} [rowCount] ReadRowsResponse rowCount + * @property {google.cloud.bigquery.storage.v1beta2.IStreamStats|null} [stats] ReadRowsResponse stats + * @property {google.cloud.bigquery.storage.v1beta2.IThrottleState|null} [throttleState] ReadRowsResponse throttleState + * @property {google.cloud.bigquery.storage.v1beta2.IAvroSchema|null} [avroSchema] ReadRowsResponse avroSchema + * @property {google.cloud.bigquery.storage.v1beta2.IArrowSchema|null} [arrowSchema] ReadRowsResponse arrowSchema + */ + + /** + * Constructs a new ReadRowsResponse. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a ReadRowsResponse. + * @implements IReadRowsResponse + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IReadRowsResponse=} [properties] Properties to set + */ + function ReadRowsResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReadRowsResponse avroRows. + * @member {google.cloud.bigquery.storage.v1beta2.IAvroRows|null|undefined} avroRows + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsResponse + * @instance + */ + ReadRowsResponse.prototype.avroRows = null; + + /** + * ReadRowsResponse arrowRecordBatch. + * @member {google.cloud.bigquery.storage.v1beta2.IArrowRecordBatch|null|undefined} arrowRecordBatch + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsResponse + * @instance + */ + ReadRowsResponse.prototype.arrowRecordBatch = null; + + /** + * ReadRowsResponse rowCount. + * @member {number|Long} rowCount + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsResponse + * @instance + */ + ReadRowsResponse.prototype.rowCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * ReadRowsResponse stats. + * @member {google.cloud.bigquery.storage.v1beta2.IStreamStats|null|undefined} stats + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsResponse + * @instance + */ + ReadRowsResponse.prototype.stats = null; + + /** + * ReadRowsResponse throttleState. + * @member {google.cloud.bigquery.storage.v1beta2.IThrottleState|null|undefined} throttleState + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsResponse + * @instance + */ + ReadRowsResponse.prototype.throttleState = null; + + /** + * ReadRowsResponse avroSchema. + * @member {google.cloud.bigquery.storage.v1beta2.IAvroSchema|null|undefined} avroSchema + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsResponse + * @instance + */ + ReadRowsResponse.prototype.avroSchema = null; + + /** + * ReadRowsResponse arrowSchema. + * @member {google.cloud.bigquery.storage.v1beta2.IArrowSchema|null|undefined} arrowSchema + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsResponse + * @instance + */ + ReadRowsResponse.prototype.arrowSchema = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * ReadRowsResponse rows. + * @member {"avroRows"|"arrowRecordBatch"|undefined} rows + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsResponse + * @instance + */ + Object.defineProperty(ReadRowsResponse.prototype, "rows", { + get: $util.oneOfGetter($oneOfFields = ["avroRows", "arrowRecordBatch"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * ReadRowsResponse schema. + * @member {"avroSchema"|"arrowSchema"|undefined} schema + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsResponse + * @instance + */ + Object.defineProperty(ReadRowsResponse.prototype, "schema", { + get: $util.oneOfGetter($oneOfFields = ["avroSchema", "arrowSchema"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ReadRowsResponse instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IReadRowsResponse=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.ReadRowsResponse} ReadRowsResponse instance + */ + ReadRowsResponse.create = function create(properties) { + return new ReadRowsResponse(properties); + }; + + /** + * Encodes the specified ReadRowsResponse message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadRowsResponse.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IReadRowsResponse} message ReadRowsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReadRowsResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.stats != null && Object.hasOwnProperty.call(message, "stats")) + $root.google.cloud.bigquery.storage.v1beta2.StreamStats.encode(message.stats, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.avroRows != null && Object.hasOwnProperty.call(message, "avroRows")) + $root.google.cloud.bigquery.storage.v1beta2.AvroRows.encode(message.avroRows, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.arrowRecordBatch != null && Object.hasOwnProperty.call(message, "arrowRecordBatch")) + $root.google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch.encode(message.arrowRecordBatch, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.throttleState != null && Object.hasOwnProperty.call(message, "throttleState")) + $root.google.cloud.bigquery.storage.v1beta2.ThrottleState.encode(message.throttleState, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + if (message.rowCount != null && Object.hasOwnProperty.call(message, "rowCount")) + writer.uint32(/* id 6, wireType 0 =*/48).int64(message.rowCount); + if (message.avroSchema != null && Object.hasOwnProperty.call(message, "avroSchema")) + $root.google.cloud.bigquery.storage.v1beta2.AvroSchema.encode(message.avroSchema, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); + if (message.arrowSchema != null && Object.hasOwnProperty.call(message, "arrowSchema")) + $root.google.cloud.bigquery.storage.v1beta2.ArrowSchema.encode(message.arrowSchema, writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ReadRowsResponse message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadRowsResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IReadRowsResponse} message ReadRowsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReadRowsResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ReadRowsResponse message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.ReadRowsResponse} ReadRowsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReadRowsResponse.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.ReadRowsResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 3: { + message.avroRows = $root.google.cloud.bigquery.storage.v1beta2.AvroRows.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + case 4: { + message.arrowRecordBatch = $root.google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + case 6: { + message.rowCount = reader.int64(); + break; + } + case 2: { + message.stats = $root.google.cloud.bigquery.storage.v1beta2.StreamStats.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + case 5: { + message.throttleState = $root.google.cloud.bigquery.storage.v1beta2.ThrottleState.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + case 7: { + message.avroSchema = $root.google.cloud.bigquery.storage.v1beta2.AvroSchema.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + case 8: { + message.arrowSchema = $root.google.cloud.bigquery.storage.v1beta2.ArrowSchema.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a ReadRowsResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.ReadRowsResponse} ReadRowsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReadRowsResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ReadRowsResponse message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ReadRowsResponse.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + var properties = {}; + if (message.avroRows != null && message.hasOwnProperty("avroRows")) { + properties.rows = 1; + { + var error = $root.google.cloud.bigquery.storage.v1beta2.AvroRows.verify(message.avroRows, long + 1); + if (error) + return "avroRows." + error; + } + } + if (message.arrowRecordBatch != null && message.hasOwnProperty("arrowRecordBatch")) { + if (properties.rows === 1) + return "rows: multiple values"; + properties.rows = 1; + { + var error = $root.google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch.verify(message.arrowRecordBatch, long + 1); + if (error) + return "arrowRecordBatch." + error; + } + } + if (message.rowCount != null && message.hasOwnProperty("rowCount")) + if (!$util.isInteger(message.rowCount) && !(message.rowCount && $util.isInteger(message.rowCount.low) && $util.isInteger(message.rowCount.high))) + return "rowCount: integer|Long expected"; + if (message.stats != null && message.hasOwnProperty("stats")) { + var error = $root.google.cloud.bigquery.storage.v1beta2.StreamStats.verify(message.stats, long + 1); + if (error) + return "stats." + error; + } + if (message.throttleState != null && message.hasOwnProperty("throttleState")) { + var error = $root.google.cloud.bigquery.storage.v1beta2.ThrottleState.verify(message.throttleState, long + 1); + if (error) + return "throttleState." + error; + } + if (message.avroSchema != null && message.hasOwnProperty("avroSchema")) { + properties.schema = 1; + { + var error = $root.google.cloud.bigquery.storage.v1beta2.AvroSchema.verify(message.avroSchema, long + 1); + if (error) + return "avroSchema." + error; + } + } + if (message.arrowSchema != null && message.hasOwnProperty("arrowSchema")) { + if (properties.schema === 1) + return "schema: multiple values"; + properties.schema = 1; + { + var error = $root.google.cloud.bigquery.storage.v1beta2.ArrowSchema.verify(message.arrowSchema, long + 1); + if (error) + return "arrowSchema." + error; + } + } + return null; + }; + + /** + * Creates a ReadRowsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.ReadRowsResponse} ReadRowsResponse + */ + ReadRowsResponse.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.ReadRowsResponse) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.ReadRowsResponse(); + if (object.avroRows != null) { + if (typeof object.avroRows !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.ReadRowsResponse.avroRows: object expected"); + message.avroRows = $root.google.cloud.bigquery.storage.v1beta2.AvroRows.fromObject(object.avroRows, long + 1); + } + if (object.arrowRecordBatch != null) { + if (typeof object.arrowRecordBatch !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.ReadRowsResponse.arrowRecordBatch: object expected"); + message.arrowRecordBatch = $root.google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch.fromObject(object.arrowRecordBatch, long + 1); + } + if (object.rowCount != null) + if ($util.Long) + (message.rowCount = $util.Long.fromValue(object.rowCount)).unsigned = false; + else if (typeof object.rowCount === "string") + message.rowCount = parseInt(object.rowCount, 10); + else if (typeof object.rowCount === "number") + message.rowCount = object.rowCount; + else if (typeof object.rowCount === "object") + message.rowCount = new $util.LongBits(object.rowCount.low >>> 0, object.rowCount.high >>> 0).toNumber(); + if (object.stats != null) { + if (typeof object.stats !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.ReadRowsResponse.stats: object expected"); + message.stats = $root.google.cloud.bigquery.storage.v1beta2.StreamStats.fromObject(object.stats, long + 1); + } + if (object.throttleState != null) { + if (typeof object.throttleState !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.ReadRowsResponse.throttleState: object expected"); + message.throttleState = $root.google.cloud.bigquery.storage.v1beta2.ThrottleState.fromObject(object.throttleState, long + 1); + } + if (object.avroSchema != null) { + if (typeof object.avroSchema !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.ReadRowsResponse.avroSchema: object expected"); + message.avroSchema = $root.google.cloud.bigquery.storage.v1beta2.AvroSchema.fromObject(object.avroSchema, long + 1); + } + if (object.arrowSchema != null) { + if (typeof object.arrowSchema !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.ReadRowsResponse.arrowSchema: object expected"); + message.arrowSchema = $root.google.cloud.bigquery.storage.v1beta2.ArrowSchema.fromObject(object.arrowSchema, long + 1); + } + return message; + }; + + /** + * Creates a plain object from a ReadRowsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ReadRowsResponse} message ReadRowsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReadRowsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.stats = null; + object.throttleState = null; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.rowCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.rowCount = options.longs === String ? "0" : 0; + } + if (message.stats != null && message.hasOwnProperty("stats")) + object.stats = $root.google.cloud.bigquery.storage.v1beta2.StreamStats.toObject(message.stats, options); + if (message.avroRows != null && message.hasOwnProperty("avroRows")) { + object.avroRows = $root.google.cloud.bigquery.storage.v1beta2.AvroRows.toObject(message.avroRows, options); + if (options.oneofs) + object.rows = "avroRows"; + } + if (message.arrowRecordBatch != null && message.hasOwnProperty("arrowRecordBatch")) { + object.arrowRecordBatch = $root.google.cloud.bigquery.storage.v1beta2.ArrowRecordBatch.toObject(message.arrowRecordBatch, options); + if (options.oneofs) + object.rows = "arrowRecordBatch"; + } + if (message.throttleState != null && message.hasOwnProperty("throttleState")) + object.throttleState = $root.google.cloud.bigquery.storage.v1beta2.ThrottleState.toObject(message.throttleState, options); + if (message.rowCount != null && message.hasOwnProperty("rowCount")) + if (typeof message.rowCount === "number") + object.rowCount = options.longs === String ? String(message.rowCount) : message.rowCount; + else + object.rowCount = options.longs === String ? $util.Long.prototype.toString.call(message.rowCount) : options.longs === Number ? new $util.LongBits(message.rowCount.low >>> 0, message.rowCount.high >>> 0).toNumber() : message.rowCount; + if (message.avroSchema != null && message.hasOwnProperty("avroSchema")) { + object.avroSchema = $root.google.cloud.bigquery.storage.v1beta2.AvroSchema.toObject(message.avroSchema, options); + if (options.oneofs) + object.schema = "avroSchema"; + } + if (message.arrowSchema != null && message.hasOwnProperty("arrowSchema")) { + object.arrowSchema = $root.google.cloud.bigquery.storage.v1beta2.ArrowSchema.toObject(message.arrowSchema, options); + if (options.oneofs) + object.schema = "arrowSchema"; + } + return object; + }; + + /** + * Converts this ReadRowsResponse to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsResponse + * @instance + * @returns {Object.} JSON object + */ + ReadRowsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReadRowsResponse + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.ReadRowsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReadRowsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.ReadRowsResponse"; + }; + + return ReadRowsResponse; + })(); + + v1beta2.SplitReadStreamRequest = (function() { + + /** + * Properties of a SplitReadStreamRequest. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface ISplitReadStreamRequest + * @property {string|null} [name] SplitReadStreamRequest name + * @property {number|null} [fraction] SplitReadStreamRequest fraction + */ + + /** + * Constructs a new SplitReadStreamRequest. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a SplitReadStreamRequest. + * @implements ISplitReadStreamRequest + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest=} [properties] Properties to set + */ + function SplitReadStreamRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * SplitReadStreamRequest name. + * @member {string} name + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest + * @instance + */ + SplitReadStreamRequest.prototype.name = ""; + + /** + * SplitReadStreamRequest fraction. + * @member {number} fraction + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest + * @instance + */ + SplitReadStreamRequest.prototype.fraction = 0; + + /** + * Creates a new SplitReadStreamRequest instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest} SplitReadStreamRequest instance + */ + SplitReadStreamRequest.create = function create(properties) { + return new SplitReadStreamRequest(properties); + }; + + /** + * Encodes the specified SplitReadStreamRequest message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest} message SplitReadStreamRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SplitReadStreamRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.fraction != null && Object.hasOwnProperty.call(message, "fraction")) + writer.uint32(/* id 2, wireType 1 =*/17).double(message.fraction); + return writer; + }; + + /** + * Encodes the specified SplitReadStreamRequest message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest} message SplitReadStreamRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SplitReadStreamRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SplitReadStreamRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest} SplitReadStreamRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SplitReadStreamRequest.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.fraction = reader.double(); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a SplitReadStreamRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest} SplitReadStreamRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SplitReadStreamRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SplitReadStreamRequest message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SplitReadStreamRequest.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.fraction != null && message.hasOwnProperty("fraction")) + if (typeof message.fraction !== "number") + return "fraction: number expected"; + return null; + }; + + /** + * Creates a SplitReadStreamRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest} SplitReadStreamRequest + */ + SplitReadStreamRequest.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.fraction != null) + message.fraction = Number(object.fraction); + return message; + }; + + /** + * Creates a plain object from a SplitReadStreamRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest} message SplitReadStreamRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SplitReadStreamRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.fraction = 0; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.fraction != null && message.hasOwnProperty("fraction")) + object.fraction = options.json && !isFinite(message.fraction) ? String(message.fraction) : message.fraction; + return object; + }; + + /** + * Converts this SplitReadStreamRequest to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest + * @instance + * @returns {Object.} JSON object + */ + SplitReadStreamRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SplitReadStreamRequest + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SplitReadStreamRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest"; + }; + + return SplitReadStreamRequest; + })(); + + v1beta2.SplitReadStreamResponse = (function() { + + /** + * Properties of a SplitReadStreamResponse. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface ISplitReadStreamResponse + * @property {google.cloud.bigquery.storage.v1beta2.IReadStream|null} [primaryStream] SplitReadStreamResponse primaryStream + * @property {google.cloud.bigquery.storage.v1beta2.IReadStream|null} [remainderStream] SplitReadStreamResponse remainderStream + */ + + /** + * Constructs a new SplitReadStreamResponse. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a SplitReadStreamResponse. + * @implements ISplitReadStreamResponse + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.ISplitReadStreamResponse=} [properties] Properties to set + */ + function SplitReadStreamResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * SplitReadStreamResponse primaryStream. + * @member {google.cloud.bigquery.storage.v1beta2.IReadStream|null|undefined} primaryStream + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse + * @instance + */ + SplitReadStreamResponse.prototype.primaryStream = null; + + /** + * SplitReadStreamResponse remainderStream. + * @member {google.cloud.bigquery.storage.v1beta2.IReadStream|null|undefined} remainderStream + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse + * @instance + */ + SplitReadStreamResponse.prototype.remainderStream = null; + + /** + * Creates a new SplitReadStreamResponse instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ISplitReadStreamResponse=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse} SplitReadStreamResponse instance + */ + SplitReadStreamResponse.create = function create(properties) { + return new SplitReadStreamResponse(properties); + }; + + /** + * Encodes the specified SplitReadStreamResponse message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ISplitReadStreamResponse} message SplitReadStreamResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SplitReadStreamResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.primaryStream != null && Object.hasOwnProperty.call(message, "primaryStream")) + $root.google.cloud.bigquery.storage.v1beta2.ReadStream.encode(message.primaryStream, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.remainderStream != null && Object.hasOwnProperty.call(message, "remainderStream")) + $root.google.cloud.bigquery.storage.v1beta2.ReadStream.encode(message.remainderStream, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified SplitReadStreamResponse message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ISplitReadStreamResponse} message SplitReadStreamResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SplitReadStreamResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SplitReadStreamResponse message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse} SplitReadStreamResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SplitReadStreamResponse.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.primaryStream = $root.google.cloud.bigquery.storage.v1beta2.ReadStream.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + case 2: { + message.remainderStream = $root.google.cloud.bigquery.storage.v1beta2.ReadStream.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a SplitReadStreamResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse} SplitReadStreamResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SplitReadStreamResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SplitReadStreamResponse message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SplitReadStreamResponse.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.primaryStream != null && message.hasOwnProperty("primaryStream")) { + var error = $root.google.cloud.bigquery.storage.v1beta2.ReadStream.verify(message.primaryStream, long + 1); + if (error) + return "primaryStream." + error; + } + if (message.remainderStream != null && message.hasOwnProperty("remainderStream")) { + var error = $root.google.cloud.bigquery.storage.v1beta2.ReadStream.verify(message.remainderStream, long + 1); + if (error) + return "remainderStream." + error; + } + return null; + }; + + /** + * Creates a SplitReadStreamResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse} SplitReadStreamResponse + */ + SplitReadStreamResponse.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse(); + if (object.primaryStream != null) { + if (typeof object.primaryStream !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse.primaryStream: object expected"); + message.primaryStream = $root.google.cloud.bigquery.storage.v1beta2.ReadStream.fromObject(object.primaryStream, long + 1); + } + if (object.remainderStream != null) { + if (typeof object.remainderStream !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse.remainderStream: object expected"); + message.remainderStream = $root.google.cloud.bigquery.storage.v1beta2.ReadStream.fromObject(object.remainderStream, long + 1); + } + return message; + }; + + /** + * Creates a plain object from a SplitReadStreamResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse} message SplitReadStreamResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SplitReadStreamResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.primaryStream = null; + object.remainderStream = null; + } + if (message.primaryStream != null && message.hasOwnProperty("primaryStream")) + object.primaryStream = $root.google.cloud.bigquery.storage.v1beta2.ReadStream.toObject(message.primaryStream, options); + if (message.remainderStream != null && message.hasOwnProperty("remainderStream")) + object.remainderStream = $root.google.cloud.bigquery.storage.v1beta2.ReadStream.toObject(message.remainderStream, options); + return object; + }; + + /** + * Converts this SplitReadStreamResponse to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse + * @instance + * @returns {Object.} JSON object + */ + SplitReadStreamResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SplitReadStreamResponse + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SplitReadStreamResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse"; + }; + + return SplitReadStreamResponse; + })(); + + v1beta2.CreateWriteStreamRequest = (function() { + + /** + * Properties of a CreateWriteStreamRequest. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface ICreateWriteStreamRequest + * @property {string|null} [parent] CreateWriteStreamRequest parent + * @property {google.cloud.bigquery.storage.v1beta2.IWriteStream|null} [writeStream] CreateWriteStreamRequest writeStream + */ + + /** + * Constructs a new CreateWriteStreamRequest. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a CreateWriteStreamRequest. + * @implements ICreateWriteStreamRequest + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest=} [properties] Properties to set + */ + function CreateWriteStreamRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateWriteStreamRequest parent. + * @member {string} parent + * @memberof google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest + * @instance + */ + CreateWriteStreamRequest.prototype.parent = ""; + + /** + * CreateWriteStreamRequest writeStream. + * @member {google.cloud.bigquery.storage.v1beta2.IWriteStream|null|undefined} writeStream + * @memberof google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest + * @instance + */ + CreateWriteStreamRequest.prototype.writeStream = null; + + /** + * Creates a new CreateWriteStreamRequest instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest} CreateWriteStreamRequest instance + */ + CreateWriteStreamRequest.create = function create(properties) { + return new CreateWriteStreamRequest(properties); + }; + + /** + * Encodes the specified CreateWriteStreamRequest message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest} message CreateWriteStreamRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateWriteStreamRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.writeStream != null && Object.hasOwnProperty.call(message, "writeStream")) + $root.google.cloud.bigquery.storage.v1beta2.WriteStream.encode(message.writeStream, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified CreateWriteStreamRequest message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest} message CreateWriteStreamRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + CreateWriteStreamRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a CreateWriteStreamRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest} CreateWriteStreamRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateWriteStreamRequest.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + message.writeStream = $root.google.cloud.bigquery.storage.v1beta2.WriteStream.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a CreateWriteStreamRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest} CreateWriteStreamRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + CreateWriteStreamRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a CreateWriteStreamRequest message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + CreateWriteStreamRequest.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.writeStream != null && message.hasOwnProperty("writeStream")) { + var error = $root.google.cloud.bigquery.storage.v1beta2.WriteStream.verify(message.writeStream, long + 1); + if (error) + return "writeStream." + error; + } + return null; + }; + + /** + * Creates a CreateWriteStreamRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest} CreateWriteStreamRequest + */ + CreateWriteStreamRequest.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.writeStream != null) { + if (typeof object.writeStream !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest.writeStream: object expected"); + message.writeStream = $root.google.cloud.bigquery.storage.v1beta2.WriteStream.fromObject(object.writeStream, long + 1); + } + return message; + }; + + /** + * Creates a plain object from a CreateWriteStreamRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest} message CreateWriteStreamRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateWriteStreamRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.writeStream = null; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.writeStream != null && message.hasOwnProperty("writeStream")) + object.writeStream = $root.google.cloud.bigquery.storage.v1beta2.WriteStream.toObject(message.writeStream, options); + return object; + }; + + /** + * Converts this CreateWriteStreamRequest to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest + * @instance + * @returns {Object.} JSON object + */ + CreateWriteStreamRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateWriteStreamRequest + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateWriteStreamRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.CreateWriteStreamRequest"; + }; + + return CreateWriteStreamRequest; + })(); + + v1beta2.AppendRowsRequest = (function() { + + /** + * Properties of an AppendRowsRequest. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IAppendRowsRequest + * @property {string|null} [writeStream] AppendRowsRequest writeStream + * @property {google.protobuf.IInt64Value|null} [offset] AppendRowsRequest offset + * @property {google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.IProtoData|null} [protoRows] AppendRowsRequest protoRows + * @property {string|null} [traceId] AppendRowsRequest traceId + */ + + /** + * Constructs a new AppendRowsRequest. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents an AppendRowsRequest. + * @implements IAppendRowsRequest + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IAppendRowsRequest=} [properties] Properties to set + */ + function AppendRowsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * AppendRowsRequest writeStream. + * @member {string} writeStream + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest + * @instance + */ + AppendRowsRequest.prototype.writeStream = ""; + + /** + * AppendRowsRequest offset. + * @member {google.protobuf.IInt64Value|null|undefined} offset + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest + * @instance + */ + AppendRowsRequest.prototype.offset = null; + + /** + * AppendRowsRequest protoRows. + * @member {google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.IProtoData|null|undefined} protoRows + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest + * @instance + */ + AppendRowsRequest.prototype.protoRows = null; + + /** + * AppendRowsRequest traceId. + * @member {string} traceId + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest + * @instance + */ + AppendRowsRequest.prototype.traceId = ""; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * AppendRowsRequest rows. + * @member {"protoRows"|undefined} rows + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest + * @instance + */ + Object.defineProperty(AppendRowsRequest.prototype, "rows", { + get: $util.oneOfGetter($oneOfFields = ["protoRows"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new AppendRowsRequest instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IAppendRowsRequest=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.AppendRowsRequest} AppendRowsRequest instance + */ + AppendRowsRequest.create = function create(properties) { + return new AppendRowsRequest(properties); + }; + + /** + * Encodes the specified AppendRowsRequest message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IAppendRowsRequest} message AppendRowsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AppendRowsRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.writeStream != null && Object.hasOwnProperty.call(message, "writeStream")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.writeStream); + if (message.offset != null && Object.hasOwnProperty.call(message, "offset")) + $root.google.protobuf.Int64Value.encode(message.offset, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.protoRows != null && Object.hasOwnProperty.call(message, "protoRows")) + $root.google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData.encode(message.protoRows, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.traceId != null && Object.hasOwnProperty.call(message, "traceId")) + writer.uint32(/* id 6, wireType 2 =*/50).string(message.traceId); + return writer; + }; + + /** + * Encodes the specified AppendRowsRequest message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IAppendRowsRequest} message AppendRowsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AppendRowsRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an AppendRowsRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.AppendRowsRequest} AppendRowsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AppendRowsRequest.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.AppendRowsRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.writeStream = reader.string(); + break; + } + case 2: { + message.offset = $root.google.protobuf.Int64Value.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + case 4: { + message.protoRows = $root.google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + case 6: { + message.traceId = reader.string(); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes an AppendRowsRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.AppendRowsRequest} AppendRowsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AppendRowsRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an AppendRowsRequest message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + AppendRowsRequest.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + var properties = {}; + if (message.writeStream != null && message.hasOwnProperty("writeStream")) + if (!$util.isString(message.writeStream)) + return "writeStream: string expected"; + if (message.offset != null && message.hasOwnProperty("offset")) { + var error = $root.google.protobuf.Int64Value.verify(message.offset, long + 1); + if (error) + return "offset." + error; + } + if (message.protoRows != null && message.hasOwnProperty("protoRows")) { + properties.rows = 1; + { + var error = $root.google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData.verify(message.protoRows, long + 1); + if (error) + return "protoRows." + error; + } + } + if (message.traceId != null && message.hasOwnProperty("traceId")) + if (!$util.isString(message.traceId)) + return "traceId: string expected"; + return null; + }; + + /** + * Creates an AppendRowsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.AppendRowsRequest} AppendRowsRequest + */ + AppendRowsRequest.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.AppendRowsRequest) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.AppendRowsRequest(); + if (object.writeStream != null) + message.writeStream = String(object.writeStream); + if (object.offset != null) { + if (typeof object.offset !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.offset: object expected"); + message.offset = $root.google.protobuf.Int64Value.fromObject(object.offset, long + 1); + } + if (object.protoRows != null) { + if (typeof object.protoRows !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.protoRows: object expected"); + message.protoRows = $root.google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData.fromObject(object.protoRows, long + 1); + } + if (object.traceId != null) + message.traceId = String(object.traceId); + return message; + }; + + /** + * Creates a plain object from an AppendRowsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.AppendRowsRequest} message AppendRowsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + AppendRowsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.writeStream = ""; + object.offset = null; + object.traceId = ""; + } + if (message.writeStream != null && message.hasOwnProperty("writeStream")) + object.writeStream = message.writeStream; + if (message.offset != null && message.hasOwnProperty("offset")) + object.offset = $root.google.protobuf.Int64Value.toObject(message.offset, options); + if (message.protoRows != null && message.hasOwnProperty("protoRows")) { + object.protoRows = $root.google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData.toObject(message.protoRows, options); + if (options.oneofs) + object.rows = "protoRows"; + } + if (message.traceId != null && message.hasOwnProperty("traceId")) + object.traceId = message.traceId; + return object; + }; + + /** + * Converts this AppendRowsRequest to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest + * @instance + * @returns {Object.} JSON object + */ + AppendRowsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for AppendRowsRequest + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + AppendRowsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.AppendRowsRequest"; + }; + + AppendRowsRequest.ProtoData = (function() { + + /** + * Properties of a ProtoData. + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest + * @interface IProtoData + * @property {google.cloud.bigquery.storage.v1beta2.IProtoSchema|null} [writerSchema] ProtoData writerSchema + * @property {google.cloud.bigquery.storage.v1beta2.IProtoRows|null} [rows] ProtoData rows + */ + + /** + * Constructs a new ProtoData. + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest + * @classdesc Represents a ProtoData. + * @implements IProtoData + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.IProtoData=} [properties] Properties to set + */ + function ProtoData(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * ProtoData writerSchema. + * @member {google.cloud.bigquery.storage.v1beta2.IProtoSchema|null|undefined} writerSchema + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData + * @instance + */ + ProtoData.prototype.writerSchema = null; + + /** + * ProtoData rows. + * @member {google.cloud.bigquery.storage.v1beta2.IProtoRows|null|undefined} rows + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData + * @instance + */ + ProtoData.prototype.rows = null; + + /** + * Creates a new ProtoData instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData + * @static + * @param {google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.IProtoData=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData} ProtoData instance + */ + ProtoData.create = function create(properties) { + return new ProtoData(properties); + }; + + /** + * Encodes the specified ProtoData message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData + * @static + * @param {google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.IProtoData} message ProtoData message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ProtoData.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.writerSchema != null && Object.hasOwnProperty.call(message, "writerSchema")) + $root.google.cloud.bigquery.storage.v1beta2.ProtoSchema.encode(message.writerSchema, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.rows != null && Object.hasOwnProperty.call(message, "rows")) + $root.google.cloud.bigquery.storage.v1beta2.ProtoRows.encode(message.rows, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ProtoData message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData + * @static + * @param {google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.IProtoData} message ProtoData message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ProtoData.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ProtoData message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData} ProtoData + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ProtoData.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.writerSchema = $root.google.cloud.bigquery.storage.v1beta2.ProtoSchema.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + case 2: { + message.rows = $root.google.cloud.bigquery.storage.v1beta2.ProtoRows.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a ProtoData message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData} ProtoData + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ProtoData.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ProtoData message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ProtoData.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.writerSchema != null && message.hasOwnProperty("writerSchema")) { + var error = $root.google.cloud.bigquery.storage.v1beta2.ProtoSchema.verify(message.writerSchema, long + 1); + if (error) + return "writerSchema." + error; + } + if (message.rows != null && message.hasOwnProperty("rows")) { + var error = $root.google.cloud.bigquery.storage.v1beta2.ProtoRows.verify(message.rows, long + 1); + if (error) + return "rows." + error; + } + return null; + }; + + /** + * Creates a ProtoData message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData} ProtoData + */ + ProtoData.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData(); + if (object.writerSchema != null) { + if (typeof object.writerSchema !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData.writerSchema: object expected"); + message.writerSchema = $root.google.cloud.bigquery.storage.v1beta2.ProtoSchema.fromObject(object.writerSchema, long + 1); + } + if (object.rows != null) { + if (typeof object.rows !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData.rows: object expected"); + message.rows = $root.google.cloud.bigquery.storage.v1beta2.ProtoRows.fromObject(object.rows, long + 1); + } + return message; + }; + + /** + * Creates a plain object from a ProtoData message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData + * @static + * @param {google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData} message ProtoData + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ProtoData.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.writerSchema = null; + object.rows = null; + } + if (message.writerSchema != null && message.hasOwnProperty("writerSchema")) + object.writerSchema = $root.google.cloud.bigquery.storage.v1beta2.ProtoSchema.toObject(message.writerSchema, options); + if (message.rows != null && message.hasOwnProperty("rows")) + object.rows = $root.google.cloud.bigquery.storage.v1beta2.ProtoRows.toObject(message.rows, options); + return object; + }; + + /** + * Converts this ProtoData to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData + * @instance + * @returns {Object.} JSON object + */ + ProtoData.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ProtoData + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ProtoData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData"; + }; + + return ProtoData; + })(); + + return AppendRowsRequest; + })(); + + v1beta2.AppendRowsResponse = (function() { + + /** + * Properties of an AppendRowsResponse. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IAppendRowsResponse + * @property {google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.IAppendResult|null} [appendResult] AppendRowsResponse appendResult + * @property {google.rpc.IStatus|null} [error] AppendRowsResponse error + * @property {google.cloud.bigquery.storage.v1beta2.ITableSchema|null} [updatedSchema] AppendRowsResponse updatedSchema + */ + + /** + * Constructs a new AppendRowsResponse. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents an AppendRowsResponse. + * @implements IAppendRowsResponse + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IAppendRowsResponse=} [properties] Properties to set + */ + function AppendRowsResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * AppendRowsResponse appendResult. + * @member {google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.IAppendResult|null|undefined} appendResult + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse + * @instance + */ + AppendRowsResponse.prototype.appendResult = null; + + /** + * AppendRowsResponse error. + * @member {google.rpc.IStatus|null|undefined} error + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse + * @instance + */ + AppendRowsResponse.prototype.error = null; + + /** + * AppendRowsResponse updatedSchema. + * @member {google.cloud.bigquery.storage.v1beta2.ITableSchema|null|undefined} updatedSchema + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse + * @instance + */ + AppendRowsResponse.prototype.updatedSchema = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * AppendRowsResponse response. + * @member {"appendResult"|"error"|undefined} response + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse + * @instance + */ + Object.defineProperty(AppendRowsResponse.prototype, "response", { + get: $util.oneOfGetter($oneOfFields = ["appendResult", "error"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new AppendRowsResponse instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IAppendRowsResponse=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.AppendRowsResponse} AppendRowsResponse instance + */ + AppendRowsResponse.create = function create(properties) { + return new AppendRowsResponse(properties); + }; + + /** + * Encodes the specified AppendRowsResponse message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IAppendRowsResponse} message AppendRowsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AppendRowsResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.appendResult != null && Object.hasOwnProperty.call(message, "appendResult")) + $root.google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult.encode(message.appendResult, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.error != null && Object.hasOwnProperty.call(message, "error")) + $root.google.rpc.Status.encode(message.error, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.updatedSchema != null && Object.hasOwnProperty.call(message, "updatedSchema")) + $root.google.cloud.bigquery.storage.v1beta2.TableSchema.encode(message.updatedSchema, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified AppendRowsResponse message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IAppendRowsResponse} message AppendRowsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AppendRowsResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an AppendRowsResponse message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.AppendRowsResponse} AppendRowsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AppendRowsResponse.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.AppendRowsResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.appendResult = $root.google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + case 2: { + message.error = $root.google.rpc.Status.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + case 3: { + message.updatedSchema = $root.google.cloud.bigquery.storage.v1beta2.TableSchema.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes an AppendRowsResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.AppendRowsResponse} AppendRowsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AppendRowsResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an AppendRowsResponse message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + AppendRowsResponse.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + var properties = {}; + if (message.appendResult != null && message.hasOwnProperty("appendResult")) { + properties.response = 1; + { + var error = $root.google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult.verify(message.appendResult, long + 1); + if (error) + return "appendResult." + error; + } + } + if (message.error != null && message.hasOwnProperty("error")) { + if (properties.response === 1) + return "response: multiple values"; + properties.response = 1; + { + var error = $root.google.rpc.Status.verify(message.error, long + 1); + if (error) + return "error." + error; + } + } + if (message.updatedSchema != null && message.hasOwnProperty("updatedSchema")) { + var error = $root.google.cloud.bigquery.storage.v1beta2.TableSchema.verify(message.updatedSchema, long + 1); + if (error) + return "updatedSchema." + error; + } + return null; + }; + + /** + * Creates an AppendRowsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.AppendRowsResponse} AppendRowsResponse + */ + AppendRowsResponse.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.AppendRowsResponse) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.AppendRowsResponse(); + if (object.appendResult != null) { + if (typeof object.appendResult !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.appendResult: object expected"); + message.appendResult = $root.google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult.fromObject(object.appendResult, long + 1); + } + if (object.error != null) { + if (typeof object.error !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.error: object expected"); + message.error = $root.google.rpc.Status.fromObject(object.error, long + 1); + } + if (object.updatedSchema != null) { + if (typeof object.updatedSchema !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.updatedSchema: object expected"); + message.updatedSchema = $root.google.cloud.bigquery.storage.v1beta2.TableSchema.fromObject(object.updatedSchema, long + 1); + } + return message; + }; + + /** + * Creates a plain object from an AppendRowsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.AppendRowsResponse} message AppendRowsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + AppendRowsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.updatedSchema = null; + if (message.appendResult != null && message.hasOwnProperty("appendResult")) { + object.appendResult = $root.google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult.toObject(message.appendResult, options); + if (options.oneofs) + object.response = "appendResult"; + } + if (message.error != null && message.hasOwnProperty("error")) { + object.error = $root.google.rpc.Status.toObject(message.error, options); + if (options.oneofs) + object.response = "error"; + } + if (message.updatedSchema != null && message.hasOwnProperty("updatedSchema")) + object.updatedSchema = $root.google.cloud.bigquery.storage.v1beta2.TableSchema.toObject(message.updatedSchema, options); + return object; + }; + + /** + * Converts this AppendRowsResponse to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse + * @instance + * @returns {Object.} JSON object + */ + AppendRowsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for AppendRowsResponse + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + AppendRowsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.AppendRowsResponse"; + }; + + AppendRowsResponse.AppendResult = (function() { + + /** + * Properties of an AppendResult. + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse + * @interface IAppendResult + * @property {google.protobuf.IInt64Value|null} [offset] AppendResult offset + */ + + /** + * Constructs a new AppendResult. + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse + * @classdesc Represents an AppendResult. + * @implements IAppendResult + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.IAppendResult=} [properties] Properties to set + */ + function AppendResult(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * AppendResult offset. + * @member {google.protobuf.IInt64Value|null|undefined} offset + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult + * @instance + */ + AppendResult.prototype.offset = null; + + /** + * Creates a new AppendResult instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult + * @static + * @param {google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.IAppendResult=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult} AppendResult instance + */ + AppendResult.create = function create(properties) { + return new AppendResult(properties); + }; + + /** + * Encodes the specified AppendResult message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult + * @static + * @param {google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.IAppendResult} message AppendResult message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AppendResult.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.offset != null && Object.hasOwnProperty.call(message, "offset")) + $root.google.protobuf.Int64Value.encode(message.offset, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified AppendResult message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult + * @static + * @param {google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.IAppendResult} message AppendResult message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + AppendResult.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an AppendResult message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult} AppendResult + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AppendResult.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.offset = $root.google.protobuf.Int64Value.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes an AppendResult message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult} AppendResult + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + AppendResult.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an AppendResult message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + AppendResult.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.offset != null && message.hasOwnProperty("offset")) { + var error = $root.google.protobuf.Int64Value.verify(message.offset, long + 1); + if (error) + return "offset." + error; + } + return null; + }; + + /** + * Creates an AppendResult message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult} AppendResult + */ + AppendResult.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult(); + if (object.offset != null) { + if (typeof object.offset !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult.offset: object expected"); + message.offset = $root.google.protobuf.Int64Value.fromObject(object.offset, long + 1); + } + return message; + }; + + /** + * Creates a plain object from an AppendResult message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult + * @static + * @param {google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult} message AppendResult + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + AppendResult.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.offset = null; + if (message.offset != null && message.hasOwnProperty("offset")) + object.offset = $root.google.protobuf.Int64Value.toObject(message.offset, options); + return object; + }; + + /** + * Converts this AppendResult to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult + * @instance + * @returns {Object.} JSON object + */ + AppendResult.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for AppendResult + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + AppendResult.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.AppendRowsResponse.AppendResult"; + }; + + return AppendResult; + })(); + + return AppendRowsResponse; + })(); + + v1beta2.GetWriteStreamRequest = (function() { + + /** + * Properties of a GetWriteStreamRequest. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IGetWriteStreamRequest + * @property {string|null} [name] GetWriteStreamRequest name + */ + + /** + * Constructs a new GetWriteStreamRequest. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a GetWriteStreamRequest. + * @implements IGetWriteStreamRequest + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest=} [properties] Properties to set + */ + function GetWriteStreamRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetWriteStreamRequest name. + * @member {string} name + * @memberof google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest + * @instance + */ + GetWriteStreamRequest.prototype.name = ""; + + /** + * Creates a new GetWriteStreamRequest instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest} GetWriteStreamRequest instance + */ + GetWriteStreamRequest.create = function create(properties) { + return new GetWriteStreamRequest(properties); + }; + + /** + * Encodes the specified GetWriteStreamRequest message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest} message GetWriteStreamRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetWriteStreamRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + return writer; + }; + + /** + * Encodes the specified GetWriteStreamRequest message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest} message GetWriteStreamRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + GetWriteStreamRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a GetWriteStreamRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest} GetWriteStreamRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetWriteStreamRequest.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a GetWriteStreamRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest} GetWriteStreamRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + GetWriteStreamRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a GetWriteStreamRequest message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + GetWriteStreamRequest.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + return null; + }; + + /** + * Creates a GetWriteStreamRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest} GetWriteStreamRequest + */ + GetWriteStreamRequest.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a GetWriteStreamRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest} message GetWriteStreamRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetWriteStreamRequest.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 GetWriteStreamRequest to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest + * @instance + * @returns {Object.} JSON object + */ + GetWriteStreamRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetWriteStreamRequest + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetWriteStreamRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.GetWriteStreamRequest"; + }; + + return GetWriteStreamRequest; + })(); + + v1beta2.BatchCommitWriteStreamsRequest = (function() { + + /** + * Properties of a BatchCommitWriteStreamsRequest. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IBatchCommitWriteStreamsRequest + * @property {string|null} [parent] BatchCommitWriteStreamsRequest parent + * @property {Array.|null} [writeStreams] BatchCommitWriteStreamsRequest writeStreams + */ + + /** + * Constructs a new BatchCommitWriteStreamsRequest. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a BatchCommitWriteStreamsRequest. + * @implements IBatchCommitWriteStreamsRequest + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest=} [properties] Properties to set + */ + function BatchCommitWriteStreamsRequest(properties) { + this.writeStreams = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * BatchCommitWriteStreamsRequest parent. + * @member {string} parent + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest + * @instance + */ + BatchCommitWriteStreamsRequest.prototype.parent = ""; + + /** + * BatchCommitWriteStreamsRequest writeStreams. + * @member {Array.} writeStreams + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest + * @instance + */ + BatchCommitWriteStreamsRequest.prototype.writeStreams = $util.emptyArray; + + /** + * Creates a new BatchCommitWriteStreamsRequest instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest} BatchCommitWriteStreamsRequest instance + */ + BatchCommitWriteStreamsRequest.create = function create(properties) { + return new BatchCommitWriteStreamsRequest(properties); + }; + + /** + * Encodes the specified BatchCommitWriteStreamsRequest message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest} message BatchCommitWriteStreamsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BatchCommitWriteStreamsRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.parent != null && Object.hasOwnProperty.call(message, "parent")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.parent); + if (message.writeStreams != null && message.writeStreams.length) + for (var i = 0; i < message.writeStreams.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.writeStreams[i]); + return writer; + }; + + /** + * Encodes the specified BatchCommitWriteStreamsRequest message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest} message BatchCommitWriteStreamsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BatchCommitWriteStreamsRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a BatchCommitWriteStreamsRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest} BatchCommitWriteStreamsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BatchCommitWriteStreamsRequest.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.parent = reader.string(); + break; + } + case 2: { + if (!(message.writeStreams && message.writeStreams.length)) + message.writeStreams = []; + message.writeStreams.push(reader.string()); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a BatchCommitWriteStreamsRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest} BatchCommitWriteStreamsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BatchCommitWriteStreamsRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a BatchCommitWriteStreamsRequest message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + BatchCommitWriteStreamsRequest.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.parent != null && message.hasOwnProperty("parent")) + if (!$util.isString(message.parent)) + return "parent: string expected"; + if (message.writeStreams != null && message.hasOwnProperty("writeStreams")) { + if (!Array.isArray(message.writeStreams)) + return "writeStreams: array expected"; + for (var i = 0; i < message.writeStreams.length; ++i) + if (!$util.isString(message.writeStreams[i])) + return "writeStreams: string[] expected"; + } + return null; + }; + + /** + * Creates a BatchCommitWriteStreamsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest} BatchCommitWriteStreamsRequest + */ + BatchCommitWriteStreamsRequest.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.writeStreams) { + if (!Array.isArray(object.writeStreams)) + throw TypeError(".google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest.writeStreams: array expected"); + message.writeStreams = []; + for (var i = 0; i < object.writeStreams.length; ++i) + message.writeStreams[i] = String(object.writeStreams[i]); + } + return message; + }; + + /** + * Creates a plain object from a BatchCommitWriteStreamsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest} message BatchCommitWriteStreamsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BatchCommitWriteStreamsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.writeStreams = []; + if (options.defaults) + object.parent = ""; + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.writeStreams && message.writeStreams.length) { + object.writeStreams = []; + for (var j = 0; j < message.writeStreams.length; ++j) + object.writeStreams[j] = message.writeStreams[j]; + } + return object; + }; + + /** + * Converts this BatchCommitWriteStreamsRequest to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest + * @instance + * @returns {Object.} JSON object + */ + BatchCommitWriteStreamsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BatchCommitWriteStreamsRequest + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BatchCommitWriteStreamsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsRequest"; + }; + + return BatchCommitWriteStreamsRequest; + })(); + + v1beta2.BatchCommitWriteStreamsResponse = (function() { + + /** + * Properties of a BatchCommitWriteStreamsResponse. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IBatchCommitWriteStreamsResponse + * @property {google.protobuf.ITimestamp|null} [commitTime] BatchCommitWriteStreamsResponse commitTime + * @property {Array.|null} [streamErrors] BatchCommitWriteStreamsResponse streamErrors + */ + + /** + * Constructs a new BatchCommitWriteStreamsResponse. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a BatchCommitWriteStreamsResponse. + * @implements IBatchCommitWriteStreamsResponse + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsResponse=} [properties] Properties to set + */ + function BatchCommitWriteStreamsResponse(properties) { + this.streamErrors = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * BatchCommitWriteStreamsResponse commitTime. + * @member {google.protobuf.ITimestamp|null|undefined} commitTime + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse + * @instance + */ + BatchCommitWriteStreamsResponse.prototype.commitTime = null; + + /** + * BatchCommitWriteStreamsResponse streamErrors. + * @member {Array.} streamErrors + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse + * @instance + */ + BatchCommitWriteStreamsResponse.prototype.streamErrors = $util.emptyArray; + + /** + * Creates a new BatchCommitWriteStreamsResponse instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsResponse=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse} BatchCommitWriteStreamsResponse instance + */ + BatchCommitWriteStreamsResponse.create = function create(properties) { + return new BatchCommitWriteStreamsResponse(properties); + }; + + /** + * Encodes the specified BatchCommitWriteStreamsResponse message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsResponse} message BatchCommitWriteStreamsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BatchCommitWriteStreamsResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.commitTime != null && Object.hasOwnProperty.call(message, "commitTime")) + $root.google.protobuf.Timestamp.encode(message.commitTime, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.streamErrors != null && message.streamErrors.length) + for (var i = 0; i < message.streamErrors.length; ++i) + $root.google.cloud.bigquery.storage.v1beta2.StorageError.encode(message.streamErrors[i], writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified BatchCommitWriteStreamsResponse message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsResponse} message BatchCommitWriteStreamsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + BatchCommitWriteStreamsResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a BatchCommitWriteStreamsResponse message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse} BatchCommitWriteStreamsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BatchCommitWriteStreamsResponse.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.commitTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + case 2: { + if (!(message.streamErrors && message.streamErrors.length)) + message.streamErrors = []; + message.streamErrors.push($root.google.cloud.bigquery.storage.v1beta2.StorageError.decode(reader, reader.uint32(), undefined, long + 1)); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a BatchCommitWriteStreamsResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse} BatchCommitWriteStreamsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + BatchCommitWriteStreamsResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a BatchCommitWriteStreamsResponse message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + BatchCommitWriteStreamsResponse.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.commitTime != null && message.hasOwnProperty("commitTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.commitTime, long + 1); + if (error) + return "commitTime." + error; + } + if (message.streamErrors != null && message.hasOwnProperty("streamErrors")) { + if (!Array.isArray(message.streamErrors)) + return "streamErrors: array expected"; + for (var i = 0; i < message.streamErrors.length; ++i) { + var error = $root.google.cloud.bigquery.storage.v1beta2.StorageError.verify(message.streamErrors[i], long + 1); + if (error) + return "streamErrors." + error; + } + } + return null; + }; + + /** + * Creates a BatchCommitWriteStreamsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse} BatchCommitWriteStreamsResponse + */ + BatchCommitWriteStreamsResponse.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse(); + if (object.commitTime != null) { + if (typeof object.commitTime !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse.commitTime: object expected"); + message.commitTime = $root.google.protobuf.Timestamp.fromObject(object.commitTime, long + 1); + } + if (object.streamErrors) { + if (!Array.isArray(object.streamErrors)) + throw TypeError(".google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse.streamErrors: array expected"); + message.streamErrors = []; + for (var i = 0; i < object.streamErrors.length; ++i) { + if (typeof object.streamErrors[i] !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse.streamErrors: object expected"); + message.streamErrors[i] = $root.google.cloud.bigquery.storage.v1beta2.StorageError.fromObject(object.streamErrors[i], long + 1); + } + } + return message; + }; + + /** + * Creates a plain object from a BatchCommitWriteStreamsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse} message BatchCommitWriteStreamsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BatchCommitWriteStreamsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.streamErrors = []; + if (options.defaults) + object.commitTime = null; + if (message.commitTime != null && message.hasOwnProperty("commitTime")) + object.commitTime = $root.google.protobuf.Timestamp.toObject(message.commitTime, options); + if (message.streamErrors && message.streamErrors.length) { + object.streamErrors = []; + for (var j = 0; j < message.streamErrors.length; ++j) + object.streamErrors[j] = $root.google.cloud.bigquery.storage.v1beta2.StorageError.toObject(message.streamErrors[j], options); + } + return object; + }; + + /** + * Converts this BatchCommitWriteStreamsResponse to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse + * @instance + * @returns {Object.} JSON object + */ + BatchCommitWriteStreamsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BatchCommitWriteStreamsResponse + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BatchCommitWriteStreamsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse"; + }; + + return BatchCommitWriteStreamsResponse; + })(); + + v1beta2.FinalizeWriteStreamRequest = (function() { + + /** + * Properties of a FinalizeWriteStreamRequest. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IFinalizeWriteStreamRequest + * @property {string|null} [name] FinalizeWriteStreamRequest name + */ + + /** + * Constructs a new FinalizeWriteStreamRequest. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a FinalizeWriteStreamRequest. + * @implements IFinalizeWriteStreamRequest + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest=} [properties] Properties to set + */ + function FinalizeWriteStreamRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * FinalizeWriteStreamRequest name. + * @member {string} name + * @memberof google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest + * @instance + */ + FinalizeWriteStreamRequest.prototype.name = ""; + + /** + * Creates a new FinalizeWriteStreamRequest instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest} FinalizeWriteStreamRequest instance + */ + FinalizeWriteStreamRequest.create = function create(properties) { + return new FinalizeWriteStreamRequest(properties); + }; + + /** + * Encodes the specified FinalizeWriteStreamRequest message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest} message FinalizeWriteStreamRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FinalizeWriteStreamRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + return writer; + }; + + /** + * Encodes the specified FinalizeWriteStreamRequest message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest} message FinalizeWriteStreamRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FinalizeWriteStreamRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FinalizeWriteStreamRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest} FinalizeWriteStreamRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FinalizeWriteStreamRequest.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a FinalizeWriteStreamRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest} FinalizeWriteStreamRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FinalizeWriteStreamRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FinalizeWriteStreamRequest message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FinalizeWriteStreamRequest.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + return null; + }; + + /** + * Creates a FinalizeWriteStreamRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest} FinalizeWriteStreamRequest + */ + FinalizeWriteStreamRequest.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a FinalizeWriteStreamRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest} message FinalizeWriteStreamRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FinalizeWriteStreamRequest.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 FinalizeWriteStreamRequest to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest + * @instance + * @returns {Object.} JSON object + */ + FinalizeWriteStreamRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FinalizeWriteStreamRequest + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FinalizeWriteStreamRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamRequest"; + }; + + return FinalizeWriteStreamRequest; + })(); + + v1beta2.FinalizeWriteStreamResponse = (function() { + + /** + * Properties of a FinalizeWriteStreamResponse. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IFinalizeWriteStreamResponse + * @property {number|Long|null} [rowCount] FinalizeWriteStreamResponse rowCount + */ + + /** + * Constructs a new FinalizeWriteStreamResponse. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a FinalizeWriteStreamResponse. + * @implements IFinalizeWriteStreamResponse + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamResponse=} [properties] Properties to set + */ + function FinalizeWriteStreamResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * FinalizeWriteStreamResponse rowCount. + * @member {number|Long} rowCount + * @memberof google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse + * @instance + */ + FinalizeWriteStreamResponse.prototype.rowCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Creates a new FinalizeWriteStreamResponse instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamResponse=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse} FinalizeWriteStreamResponse instance + */ + FinalizeWriteStreamResponse.create = function create(properties) { + return new FinalizeWriteStreamResponse(properties); + }; + + /** + * Encodes the specified FinalizeWriteStreamResponse message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamResponse} message FinalizeWriteStreamResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FinalizeWriteStreamResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.rowCount != null && Object.hasOwnProperty.call(message, "rowCount")) + writer.uint32(/* id 1, wireType 0 =*/8).int64(message.rowCount); + return writer; + }; + + /** + * Encodes the specified FinalizeWriteStreamResponse message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamResponse} message FinalizeWriteStreamResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FinalizeWriteStreamResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FinalizeWriteStreamResponse message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse} FinalizeWriteStreamResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FinalizeWriteStreamResponse.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.rowCount = reader.int64(); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a FinalizeWriteStreamResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse} FinalizeWriteStreamResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FinalizeWriteStreamResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FinalizeWriteStreamResponse message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FinalizeWriteStreamResponse.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.rowCount != null && message.hasOwnProperty("rowCount")) + if (!$util.isInteger(message.rowCount) && !(message.rowCount && $util.isInteger(message.rowCount.low) && $util.isInteger(message.rowCount.high))) + return "rowCount: integer|Long expected"; + return null; + }; + + /** + * Creates a FinalizeWriteStreamResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse} FinalizeWriteStreamResponse + */ + FinalizeWriteStreamResponse.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse(); + if (object.rowCount != null) + if ($util.Long) + (message.rowCount = $util.Long.fromValue(object.rowCount)).unsigned = false; + else if (typeof object.rowCount === "string") + message.rowCount = parseInt(object.rowCount, 10); + else if (typeof object.rowCount === "number") + message.rowCount = object.rowCount; + else if (typeof object.rowCount === "object") + message.rowCount = new $util.LongBits(object.rowCount.low >>> 0, object.rowCount.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from a FinalizeWriteStreamResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse} message FinalizeWriteStreamResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FinalizeWriteStreamResponse.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.rowCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.rowCount = options.longs === String ? "0" : 0; + if (message.rowCount != null && message.hasOwnProperty("rowCount")) + if (typeof message.rowCount === "number") + object.rowCount = options.longs === String ? String(message.rowCount) : message.rowCount; + else + object.rowCount = options.longs === String ? $util.Long.prototype.toString.call(message.rowCount) : options.longs === Number ? new $util.LongBits(message.rowCount.low >>> 0, message.rowCount.high >>> 0).toNumber() : message.rowCount; + return object; + }; + + /** + * Converts this FinalizeWriteStreamResponse to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse + * @instance + * @returns {Object.} JSON object + */ + FinalizeWriteStreamResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FinalizeWriteStreamResponse + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FinalizeWriteStreamResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse"; + }; + + return FinalizeWriteStreamResponse; + })(); + + v1beta2.FlushRowsRequest = (function() { + + /** + * Properties of a FlushRowsRequest. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IFlushRowsRequest + * @property {string|null} [writeStream] FlushRowsRequest writeStream + * @property {google.protobuf.IInt64Value|null} [offset] FlushRowsRequest offset + */ + + /** + * Constructs a new FlushRowsRequest. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a FlushRowsRequest. + * @implements IFlushRowsRequest + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest=} [properties] Properties to set + */ + function FlushRowsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * FlushRowsRequest writeStream. + * @member {string} writeStream + * @memberof google.cloud.bigquery.storage.v1beta2.FlushRowsRequest + * @instance + */ + FlushRowsRequest.prototype.writeStream = ""; + + /** + * FlushRowsRequest offset. + * @member {google.protobuf.IInt64Value|null|undefined} offset + * @memberof google.cloud.bigquery.storage.v1beta2.FlushRowsRequest + * @instance + */ + FlushRowsRequest.prototype.offset = null; + + /** + * Creates a new FlushRowsRequest instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.FlushRowsRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.FlushRowsRequest} FlushRowsRequest instance + */ + FlushRowsRequest.create = function create(properties) { + return new FlushRowsRequest(properties); + }; + + /** + * Encodes the specified FlushRowsRequest message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.FlushRowsRequest.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.FlushRowsRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest} message FlushRowsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FlushRowsRequest.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.writeStream != null && Object.hasOwnProperty.call(message, "writeStream")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.writeStream); + if (message.offset != null && Object.hasOwnProperty.call(message, "offset")) + $root.google.protobuf.Int64Value.encode(message.offset, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified FlushRowsRequest message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.FlushRowsRequest.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.FlushRowsRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest} message FlushRowsRequest message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FlushRowsRequest.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FlushRowsRequest message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.FlushRowsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.FlushRowsRequest} FlushRowsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FlushRowsRequest.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.FlushRowsRequest(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.writeStream = reader.string(); + break; + } + case 2: { + message.offset = $root.google.protobuf.Int64Value.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a FlushRowsRequest message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.FlushRowsRequest + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.FlushRowsRequest} FlushRowsRequest + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FlushRowsRequest.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FlushRowsRequest message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.FlushRowsRequest + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FlushRowsRequest.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.writeStream != null && message.hasOwnProperty("writeStream")) + if (!$util.isString(message.writeStream)) + return "writeStream: string expected"; + if (message.offset != null && message.hasOwnProperty("offset")) { + var error = $root.google.protobuf.Int64Value.verify(message.offset, long + 1); + if (error) + return "offset." + error; + } + return null; + }; + + /** + * Creates a FlushRowsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.FlushRowsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.FlushRowsRequest} FlushRowsRequest + */ + FlushRowsRequest.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.FlushRowsRequest) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.FlushRowsRequest(); + if (object.writeStream != null) + message.writeStream = String(object.writeStream); + if (object.offset != null) { + if (typeof object.offset !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.FlushRowsRequest.offset: object expected"); + message.offset = $root.google.protobuf.Int64Value.fromObject(object.offset, long + 1); + } + return message; + }; + + /** + * Creates a plain object from a FlushRowsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.FlushRowsRequest + * @static + * @param {google.cloud.bigquery.storage.v1beta2.FlushRowsRequest} message FlushRowsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FlushRowsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.writeStream = ""; + object.offset = null; + } + if (message.writeStream != null && message.hasOwnProperty("writeStream")) + object.writeStream = message.writeStream; + if (message.offset != null && message.hasOwnProperty("offset")) + object.offset = $root.google.protobuf.Int64Value.toObject(message.offset, options); + return object; + }; + + /** + * Converts this FlushRowsRequest to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.FlushRowsRequest + * @instance + * @returns {Object.} JSON object + */ + FlushRowsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FlushRowsRequest + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.FlushRowsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FlushRowsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.FlushRowsRequest"; + }; + + return FlushRowsRequest; + })(); + + v1beta2.FlushRowsResponse = (function() { + + /** + * Properties of a FlushRowsResponse. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IFlushRowsResponse + * @property {number|Long|null} [offset] FlushRowsResponse offset + */ + + /** + * Constructs a new FlushRowsResponse. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a FlushRowsResponse. + * @implements IFlushRowsResponse + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IFlushRowsResponse=} [properties] Properties to set + */ + function FlushRowsResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * FlushRowsResponse offset. + * @member {number|Long} offset + * @memberof google.cloud.bigquery.storage.v1beta2.FlushRowsResponse + * @instance + */ + FlushRowsResponse.prototype.offset = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * Creates a new FlushRowsResponse instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.FlushRowsResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IFlushRowsResponse=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.FlushRowsResponse} FlushRowsResponse instance + */ + FlushRowsResponse.create = function create(properties) { + return new FlushRowsResponse(properties); + }; + + /** + * Encodes the specified FlushRowsResponse message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.FlushRowsResponse.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.FlushRowsResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IFlushRowsResponse} message FlushRowsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FlushRowsResponse.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.offset != null && Object.hasOwnProperty.call(message, "offset")) + writer.uint32(/* id 1, wireType 0 =*/8).int64(message.offset); + return writer; + }; + + /** + * Encodes the specified FlushRowsResponse message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.FlushRowsResponse.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.FlushRowsResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IFlushRowsResponse} message FlushRowsResponse message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FlushRowsResponse.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FlushRowsResponse message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.FlushRowsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.FlushRowsResponse} FlushRowsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FlushRowsResponse.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.FlushRowsResponse(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.offset = reader.int64(); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a FlushRowsResponse message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.FlushRowsResponse + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.FlushRowsResponse} FlushRowsResponse + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FlushRowsResponse.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FlushRowsResponse message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.FlushRowsResponse + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FlushRowsResponse.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.offset != null && message.hasOwnProperty("offset")) + if (!$util.isInteger(message.offset) && !(message.offset && $util.isInteger(message.offset.low) && $util.isInteger(message.offset.high))) + return "offset: integer|Long expected"; + return null; + }; + + /** + * Creates a FlushRowsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.FlushRowsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.FlushRowsResponse} FlushRowsResponse + */ + FlushRowsResponse.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.FlushRowsResponse) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.FlushRowsResponse(); + if (object.offset != null) + if ($util.Long) + (message.offset = $util.Long.fromValue(object.offset)).unsigned = false; + else if (typeof object.offset === "string") + message.offset = parseInt(object.offset, 10); + else if (typeof object.offset === "number") + message.offset = object.offset; + else if (typeof object.offset === "object") + message.offset = new $util.LongBits(object.offset.low >>> 0, object.offset.high >>> 0).toNumber(); + return message; + }; + + /** + * Creates a plain object from a FlushRowsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.FlushRowsResponse + * @static + * @param {google.cloud.bigquery.storage.v1beta2.FlushRowsResponse} message FlushRowsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FlushRowsResponse.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.offset = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.offset = options.longs === String ? "0" : 0; + if (message.offset != null && message.hasOwnProperty("offset")) + if (typeof message.offset === "number") + object.offset = options.longs === String ? String(message.offset) : message.offset; + else + object.offset = options.longs === String ? $util.Long.prototype.toString.call(message.offset) : options.longs === Number ? new $util.LongBits(message.offset.low >>> 0, message.offset.high >>> 0).toNumber() : message.offset; + return object; + }; + + /** + * Converts this FlushRowsResponse to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.FlushRowsResponse + * @instance + * @returns {Object.} JSON object + */ + FlushRowsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FlushRowsResponse + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.FlushRowsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FlushRowsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.FlushRowsResponse"; + }; + + return FlushRowsResponse; + })(); + + v1beta2.StorageError = (function() { + + /** + * Properties of a StorageError. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IStorageError + * @property {google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode|null} [code] StorageError code + * @property {string|null} [entity] StorageError entity + * @property {string|null} [errorMessage] StorageError errorMessage + */ + + /** + * Constructs a new StorageError. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a StorageError. + * @implements IStorageError + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IStorageError=} [properties] Properties to set + */ + function StorageError(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * StorageError code. + * @member {google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode} code + * @memberof google.cloud.bigquery.storage.v1beta2.StorageError + * @instance + */ + StorageError.prototype.code = 0; + + /** + * StorageError entity. + * @member {string} entity + * @memberof google.cloud.bigquery.storage.v1beta2.StorageError + * @instance + */ + StorageError.prototype.entity = ""; + + /** + * StorageError errorMessage. + * @member {string} errorMessage + * @memberof google.cloud.bigquery.storage.v1beta2.StorageError + * @instance + */ + StorageError.prototype.errorMessage = ""; + + /** + * Creates a new StorageError instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.StorageError + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IStorageError=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.StorageError} StorageError instance + */ + StorageError.create = function create(properties) { + return new StorageError(properties); + }; + + /** + * Encodes the specified StorageError message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.StorageError.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.StorageError + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IStorageError} message StorageError message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + StorageError.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.code != null && Object.hasOwnProperty.call(message, "code")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.code); + if (message.entity != null && Object.hasOwnProperty.call(message, "entity")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.entity); + if (message.errorMessage != null && Object.hasOwnProperty.call(message, "errorMessage")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.errorMessage); + return writer; + }; + + /** + * Encodes the specified StorageError message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.StorageError.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.StorageError + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IStorageError} message StorageError message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + StorageError.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a StorageError message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.StorageError + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.StorageError} StorageError + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + StorageError.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.StorageError(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.code = reader.int32(); + break; + } + case 2: { + message.entity = reader.string(); + break; + } + case 3: { + message.errorMessage = reader.string(); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a StorageError message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.StorageError + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.StorageError} StorageError + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + StorageError.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a StorageError message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.StorageError + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + StorageError.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.code != null && message.hasOwnProperty("code")) + switch (message.code) { + default: + return "code: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + break; + } + if (message.entity != null && message.hasOwnProperty("entity")) + if (!$util.isString(message.entity)) + return "entity: string expected"; + if (message.errorMessage != null && message.hasOwnProperty("errorMessage")) + if (!$util.isString(message.errorMessage)) + return "errorMessage: string expected"; + return null; + }; + + /** + * Creates a StorageError message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.StorageError + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.StorageError} StorageError + */ + StorageError.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.StorageError) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.StorageError(); + switch (object.code) { + default: + if (typeof object.code === "number") { + message.code = object.code; + break; + } + break; + case "STORAGE_ERROR_CODE_UNSPECIFIED": + case 0: + message.code = 0; + break; + case "TABLE_NOT_FOUND": + case 1: + message.code = 1; + break; + case "STREAM_ALREADY_COMMITTED": + case 2: + message.code = 2; + break; + case "STREAM_NOT_FOUND": + case 3: + message.code = 3; + break; + case "INVALID_STREAM_TYPE": + case 4: + message.code = 4; + break; + case "INVALID_STREAM_STATE": + case 5: + message.code = 5; + break; + case "STREAM_FINALIZED": + case 6: + message.code = 6; + break; + } + if (object.entity != null) + message.entity = String(object.entity); + if (object.errorMessage != null) + message.errorMessage = String(object.errorMessage); + return message; + }; + + /** + * Creates a plain object from a StorageError message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.StorageError + * @static + * @param {google.cloud.bigquery.storage.v1beta2.StorageError} message StorageError + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + StorageError.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.code = options.enums === String ? "STORAGE_ERROR_CODE_UNSPECIFIED" : 0; + object.entity = ""; + object.errorMessage = ""; + } + if (message.code != null && message.hasOwnProperty("code")) + object.code = options.enums === String ? $root.google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode[message.code] === undefined ? message.code : $root.google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode[message.code] : message.code; + if (message.entity != null && message.hasOwnProperty("entity")) + object.entity = message.entity; + if (message.errorMessage != null && message.hasOwnProperty("errorMessage")) + object.errorMessage = message.errorMessage; + return object; + }; + + /** + * Converts this StorageError to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.StorageError + * @instance + * @returns {Object.} JSON object + */ + StorageError.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for StorageError + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.StorageError + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + StorageError.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.StorageError"; + }; + + /** + * StorageErrorCode enum. + * @name google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode + * @enum {number} + * @property {number} STORAGE_ERROR_CODE_UNSPECIFIED=0 STORAGE_ERROR_CODE_UNSPECIFIED value + * @property {number} TABLE_NOT_FOUND=1 TABLE_NOT_FOUND value + * @property {number} STREAM_ALREADY_COMMITTED=2 STREAM_ALREADY_COMMITTED value + * @property {number} STREAM_NOT_FOUND=3 STREAM_NOT_FOUND value + * @property {number} INVALID_STREAM_TYPE=4 INVALID_STREAM_TYPE value + * @property {number} INVALID_STREAM_STATE=5 INVALID_STREAM_STATE value + * @property {number} STREAM_FINALIZED=6 STREAM_FINALIZED value + */ + StorageError.StorageErrorCode = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "STORAGE_ERROR_CODE_UNSPECIFIED"] = 0; + values[valuesById[1] = "TABLE_NOT_FOUND"] = 1; + values[valuesById[2] = "STREAM_ALREADY_COMMITTED"] = 2; + values[valuesById[3] = "STREAM_NOT_FOUND"] = 3; + values[valuesById[4] = "INVALID_STREAM_TYPE"] = 4; + values[valuesById[5] = "INVALID_STREAM_STATE"] = 5; + values[valuesById[6] = "STREAM_FINALIZED"] = 6; + return values; + })(); + + return StorageError; + })(); + + /** + * DataFormat enum. + * @name google.cloud.bigquery.storage.v1beta2.DataFormat + * @enum {number} + * @property {number} DATA_FORMAT_UNSPECIFIED=0 DATA_FORMAT_UNSPECIFIED value + * @property {number} AVRO=1 AVRO value + * @property {number} ARROW=2 ARROW value + */ + v1beta2.DataFormat = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DATA_FORMAT_UNSPECIFIED"] = 0; + values[valuesById[1] = "AVRO"] = 1; + values[valuesById[2] = "ARROW"] = 2; + return values; + })(); + + v1beta2.ReadSession = (function() { + + /** + * Properties of a ReadSession. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IReadSession + * @property {string|null} [name] ReadSession name + * @property {google.protobuf.ITimestamp|null} [expireTime] ReadSession expireTime + * @property {google.cloud.bigquery.storage.v1beta2.DataFormat|null} [dataFormat] ReadSession dataFormat + * @property {google.cloud.bigquery.storage.v1beta2.IAvroSchema|null} [avroSchema] ReadSession avroSchema + * @property {google.cloud.bigquery.storage.v1beta2.IArrowSchema|null} [arrowSchema] ReadSession arrowSchema + * @property {string|null} [table] ReadSession table + * @property {google.cloud.bigquery.storage.v1beta2.ReadSession.ITableModifiers|null} [tableModifiers] ReadSession tableModifiers + * @property {google.cloud.bigquery.storage.v1beta2.ReadSession.ITableReadOptions|null} [readOptions] ReadSession readOptions + * @property {Array.|null} [streams] ReadSession streams + */ + + /** + * Constructs a new ReadSession. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a ReadSession. + * @implements IReadSession + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IReadSession=} [properties] Properties to set + */ + function ReadSession(properties) { + this.streams = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReadSession name. + * @member {string} name + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @instance + */ + ReadSession.prototype.name = ""; + + /** + * ReadSession expireTime. + * @member {google.protobuf.ITimestamp|null|undefined} expireTime + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @instance + */ + ReadSession.prototype.expireTime = null; + + /** + * ReadSession dataFormat. + * @member {google.cloud.bigquery.storage.v1beta2.DataFormat} dataFormat + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @instance + */ + ReadSession.prototype.dataFormat = 0; + + /** + * ReadSession avroSchema. + * @member {google.cloud.bigquery.storage.v1beta2.IAvroSchema|null|undefined} avroSchema + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @instance + */ + ReadSession.prototype.avroSchema = null; + + /** + * ReadSession arrowSchema. + * @member {google.cloud.bigquery.storage.v1beta2.IArrowSchema|null|undefined} arrowSchema + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @instance + */ + ReadSession.prototype.arrowSchema = null; + + /** + * ReadSession table. + * @member {string} table + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @instance + */ + ReadSession.prototype.table = ""; + + /** + * ReadSession tableModifiers. + * @member {google.cloud.bigquery.storage.v1beta2.ReadSession.ITableModifiers|null|undefined} tableModifiers + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @instance + */ + ReadSession.prototype.tableModifiers = null; + + /** + * ReadSession readOptions. + * @member {google.cloud.bigquery.storage.v1beta2.ReadSession.ITableReadOptions|null|undefined} readOptions + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @instance + */ + ReadSession.prototype.readOptions = null; + + /** + * ReadSession streams. + * @member {Array.} streams + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @instance + */ + ReadSession.prototype.streams = $util.emptyArray; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * ReadSession schema. + * @member {"avroSchema"|"arrowSchema"|undefined} schema + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @instance + */ + Object.defineProperty(ReadSession.prototype, "schema", { + get: $util.oneOfGetter($oneOfFields = ["avroSchema", "arrowSchema"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a new ReadSession instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IReadSession=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.ReadSession} ReadSession instance + */ + ReadSession.create = function create(properties) { + return new ReadSession(properties); + }; + + /** + * Encodes the specified ReadSession message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadSession.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IReadSession} message ReadSession message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReadSession.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.expireTime != null && Object.hasOwnProperty.call(message, "expireTime")) + $root.google.protobuf.Timestamp.encode(message.expireTime, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); + if (message.dataFormat != null && Object.hasOwnProperty.call(message, "dataFormat")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.dataFormat); + if (message.avroSchema != null && Object.hasOwnProperty.call(message, "avroSchema")) + $root.google.cloud.bigquery.storage.v1beta2.AvroSchema.encode(message.avroSchema, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.arrowSchema != null && Object.hasOwnProperty.call(message, "arrowSchema")) + $root.google.cloud.bigquery.storage.v1beta2.ArrowSchema.encode(message.arrowSchema, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + if (message.table != null && Object.hasOwnProperty.call(message, "table")) + writer.uint32(/* id 6, wireType 2 =*/50).string(message.table); + if (message.tableModifiers != null && Object.hasOwnProperty.call(message, "tableModifiers")) + $root.google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers.encode(message.tableModifiers, writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim(); + if (message.readOptions != null && Object.hasOwnProperty.call(message, "readOptions")) + $root.google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions.encode(message.readOptions, writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim(); + if (message.streams != null && message.streams.length) + for (var i = 0; i < message.streams.length; ++i) + $root.google.cloud.bigquery.storage.v1beta2.ReadStream.encode(message.streams[i], writer.uint32(/* id 10, wireType 2 =*/82).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified ReadSession message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadSession.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IReadSession} message ReadSession message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReadSession.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ReadSession message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.ReadSession} ReadSession + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReadSession.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.ReadSession(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.expireTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + case 3: { + message.dataFormat = reader.int32(); + break; + } + case 4: { + message.avroSchema = $root.google.cloud.bigquery.storage.v1beta2.AvroSchema.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + case 5: { + message.arrowSchema = $root.google.cloud.bigquery.storage.v1beta2.ArrowSchema.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + case 6: { + message.table = reader.string(); + break; + } + case 7: { + message.tableModifiers = $root.google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + case 8: { + message.readOptions = $root.google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + case 10: { + if (!(message.streams && message.streams.length)) + message.streams = []; + message.streams.push($root.google.cloud.bigquery.storage.v1beta2.ReadStream.decode(reader, reader.uint32(), undefined, long + 1)); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a ReadSession message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.ReadSession} ReadSession + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReadSession.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ReadSession message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ReadSession.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + var properties = {}; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.expireTime != null && message.hasOwnProperty("expireTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.expireTime, long + 1); + if (error) + return "expireTime." + error; + } + if (message.dataFormat != null && message.hasOwnProperty("dataFormat")) + switch (message.dataFormat) { + default: + return "dataFormat: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.avroSchema != null && message.hasOwnProperty("avroSchema")) { + properties.schema = 1; + { + var error = $root.google.cloud.bigquery.storage.v1beta2.AvroSchema.verify(message.avroSchema, long + 1); + if (error) + return "avroSchema." + error; + } + } + if (message.arrowSchema != null && message.hasOwnProperty("arrowSchema")) { + if (properties.schema === 1) + return "schema: multiple values"; + properties.schema = 1; + { + var error = $root.google.cloud.bigquery.storage.v1beta2.ArrowSchema.verify(message.arrowSchema, long + 1); + if (error) + return "arrowSchema." + error; + } + } + if (message.table != null && message.hasOwnProperty("table")) + if (!$util.isString(message.table)) + return "table: string expected"; + if (message.tableModifiers != null && message.hasOwnProperty("tableModifiers")) { + var error = $root.google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers.verify(message.tableModifiers, long + 1); + if (error) + return "tableModifiers." + error; + } + if (message.readOptions != null && message.hasOwnProperty("readOptions")) { + var error = $root.google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions.verify(message.readOptions, long + 1); + if (error) + return "readOptions." + error; + } + if (message.streams != null && message.hasOwnProperty("streams")) { + if (!Array.isArray(message.streams)) + return "streams: array expected"; + for (var i = 0; i < message.streams.length; ++i) { + var error = $root.google.cloud.bigquery.storage.v1beta2.ReadStream.verify(message.streams[i], long + 1); + if (error) + return "streams." + error; + } + } + return null; + }; + + /** + * Creates a ReadSession message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.ReadSession} ReadSession + */ + ReadSession.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.ReadSession) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.ReadSession(); + if (object.name != null) + message.name = String(object.name); + if (object.expireTime != null) { + if (typeof object.expireTime !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.ReadSession.expireTime: object expected"); + message.expireTime = $root.google.protobuf.Timestamp.fromObject(object.expireTime, long + 1); + } + switch (object.dataFormat) { + default: + if (typeof object.dataFormat === "number") { + message.dataFormat = object.dataFormat; + break; + } + break; + case "DATA_FORMAT_UNSPECIFIED": + case 0: + message.dataFormat = 0; + break; + case "AVRO": + case 1: + message.dataFormat = 1; + break; + case "ARROW": + case 2: + message.dataFormat = 2; + break; + } + if (object.avroSchema != null) { + if (typeof object.avroSchema !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.ReadSession.avroSchema: object expected"); + message.avroSchema = $root.google.cloud.bigquery.storage.v1beta2.AvroSchema.fromObject(object.avroSchema, long + 1); + } + if (object.arrowSchema != null) { + if (typeof object.arrowSchema !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.ReadSession.arrowSchema: object expected"); + message.arrowSchema = $root.google.cloud.bigquery.storage.v1beta2.ArrowSchema.fromObject(object.arrowSchema, long + 1); + } + if (object.table != null) + message.table = String(object.table); + if (object.tableModifiers != null) { + if (typeof object.tableModifiers !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.ReadSession.tableModifiers: object expected"); + message.tableModifiers = $root.google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers.fromObject(object.tableModifiers, long + 1); + } + if (object.readOptions != null) { + if (typeof object.readOptions !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.ReadSession.readOptions: object expected"); + message.readOptions = $root.google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions.fromObject(object.readOptions, long + 1); + } + if (object.streams) { + if (!Array.isArray(object.streams)) + throw TypeError(".google.cloud.bigquery.storage.v1beta2.ReadSession.streams: array expected"); + message.streams = []; + for (var i = 0; i < object.streams.length; ++i) { + if (typeof object.streams[i] !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.ReadSession.streams: object expected"); + message.streams[i] = $root.google.cloud.bigquery.storage.v1beta2.ReadStream.fromObject(object.streams[i], long + 1); + } + } + return message; + }; + + /** + * Creates a plain object from a ReadSession message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ReadSession} message ReadSession + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReadSession.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.streams = []; + if (options.defaults) { + object.name = ""; + object.expireTime = null; + object.dataFormat = options.enums === String ? "DATA_FORMAT_UNSPECIFIED" : 0; + object.table = ""; + object.tableModifiers = null; + object.readOptions = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.expireTime != null && message.hasOwnProperty("expireTime")) + object.expireTime = $root.google.protobuf.Timestamp.toObject(message.expireTime, options); + if (message.dataFormat != null && message.hasOwnProperty("dataFormat")) + object.dataFormat = options.enums === String ? $root.google.cloud.bigquery.storage.v1beta2.DataFormat[message.dataFormat] === undefined ? message.dataFormat : $root.google.cloud.bigquery.storage.v1beta2.DataFormat[message.dataFormat] : message.dataFormat; + if (message.avroSchema != null && message.hasOwnProperty("avroSchema")) { + object.avroSchema = $root.google.cloud.bigquery.storage.v1beta2.AvroSchema.toObject(message.avroSchema, options); + if (options.oneofs) + object.schema = "avroSchema"; + } + if (message.arrowSchema != null && message.hasOwnProperty("arrowSchema")) { + object.arrowSchema = $root.google.cloud.bigquery.storage.v1beta2.ArrowSchema.toObject(message.arrowSchema, options); + if (options.oneofs) + object.schema = "arrowSchema"; + } + if (message.table != null && message.hasOwnProperty("table")) + object.table = message.table; + if (message.tableModifiers != null && message.hasOwnProperty("tableModifiers")) + object.tableModifiers = $root.google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers.toObject(message.tableModifiers, options); + if (message.readOptions != null && message.hasOwnProperty("readOptions")) + object.readOptions = $root.google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions.toObject(message.readOptions, options); + if (message.streams && message.streams.length) { + object.streams = []; + for (var j = 0; j < message.streams.length; ++j) + object.streams[j] = $root.google.cloud.bigquery.storage.v1beta2.ReadStream.toObject(message.streams[j], options); + } + return object; + }; + + /** + * Converts this ReadSession to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @instance + * @returns {Object.} JSON object + */ + ReadSession.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReadSession + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReadSession.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.ReadSession"; + }; + + ReadSession.TableModifiers = (function() { + + /** + * Properties of a TableModifiers. + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @interface ITableModifiers + * @property {google.protobuf.ITimestamp|null} [snapshotTime] TableModifiers snapshotTime + */ + + /** + * Constructs a new TableModifiers. + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @classdesc Represents a TableModifiers. + * @implements ITableModifiers + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.ReadSession.ITableModifiers=} [properties] Properties to set + */ + function TableModifiers(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * TableModifiers snapshotTime. + * @member {google.protobuf.ITimestamp|null|undefined} snapshotTime + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers + * @instance + */ + TableModifiers.prototype.snapshotTime = null; + + /** + * Creates a new TableModifiers instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ReadSession.ITableModifiers=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers} TableModifiers instance + */ + TableModifiers.create = function create(properties) { + return new TableModifiers(properties); + }; + + /** + * Encodes the specified TableModifiers message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ReadSession.ITableModifiers} message TableModifiers message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TableModifiers.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.snapshotTime != null && Object.hasOwnProperty.call(message, "snapshotTime")) + $root.google.protobuf.Timestamp.encode(message.snapshotTime, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified TableModifiers message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ReadSession.ITableModifiers} message TableModifiers message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TableModifiers.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a TableModifiers message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers} TableModifiers + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TableModifiers.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.snapshotTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a TableModifiers message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers} TableModifiers + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TableModifiers.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a TableModifiers message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + TableModifiers.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.snapshotTime != null && message.hasOwnProperty("snapshotTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.snapshotTime, long + 1); + if (error) + return "snapshotTime." + error; + } + return null; + }; + + /** + * Creates a TableModifiers message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers} TableModifiers + */ + TableModifiers.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers(); + if (object.snapshotTime != null) { + if (typeof object.snapshotTime !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers.snapshotTime: object expected"); + message.snapshotTime = $root.google.protobuf.Timestamp.fromObject(object.snapshotTime, long + 1); + } + return message; + }; + + /** + * Creates a plain object from a TableModifiers message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers} message TableModifiers + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TableModifiers.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.snapshotTime = null; + if (message.snapshotTime != null && message.hasOwnProperty("snapshotTime")) + object.snapshotTime = $root.google.protobuf.Timestamp.toObject(message.snapshotTime, options); + return object; + }; + + /** + * Converts this TableModifiers to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers + * @instance + * @returns {Object.} JSON object + */ + TableModifiers.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for TableModifiers + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TableModifiers.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.ReadSession.TableModifiers"; + }; + + return TableModifiers; + })(); + + ReadSession.TableReadOptions = (function() { + + /** + * Properties of a TableReadOptions. + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @interface ITableReadOptions + * @property {Array.|null} [selectedFields] TableReadOptions selectedFields + * @property {string|null} [rowRestriction] TableReadOptions rowRestriction + * @property {google.cloud.bigquery.storage.v1beta2.IArrowSerializationOptions|null} [arrowSerializationOptions] TableReadOptions arrowSerializationOptions + */ + + /** + * Constructs a new TableReadOptions. + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession + * @classdesc Represents a TableReadOptions. + * @implements ITableReadOptions + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.ReadSession.ITableReadOptions=} [properties] Properties to set + */ + function TableReadOptions(properties) { + this.selectedFields = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * TableReadOptions selectedFields. + * @member {Array.} selectedFields + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions + * @instance + */ + TableReadOptions.prototype.selectedFields = $util.emptyArray; + + /** + * TableReadOptions rowRestriction. + * @member {string} rowRestriction + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions + * @instance + */ + TableReadOptions.prototype.rowRestriction = ""; + + /** + * TableReadOptions arrowSerializationOptions. + * @member {google.cloud.bigquery.storage.v1beta2.IArrowSerializationOptions|null|undefined} arrowSerializationOptions + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions + * @instance + */ + TableReadOptions.prototype.arrowSerializationOptions = null; + + /** + * Creates a new TableReadOptions instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ReadSession.ITableReadOptions=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions} TableReadOptions instance + */ + TableReadOptions.create = function create(properties) { + return new TableReadOptions(properties); + }; + + /** + * Encodes the specified TableReadOptions message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ReadSession.ITableReadOptions} message TableReadOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TableReadOptions.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.selectedFields != null && message.selectedFields.length) + for (var i = 0; i < message.selectedFields.length; ++i) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.selectedFields[i]); + if (message.rowRestriction != null && Object.hasOwnProperty.call(message, "rowRestriction")) + writer.uint32(/* id 2, wireType 2 =*/18).string(message.rowRestriction); + if (message.arrowSerializationOptions != null && Object.hasOwnProperty.call(message, "arrowSerializationOptions")) + $root.google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions.encode(message.arrowSerializationOptions, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified TableReadOptions message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ReadSession.ITableReadOptions} message TableReadOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TableReadOptions.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a TableReadOptions message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions} TableReadOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TableReadOptions.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.selectedFields && message.selectedFields.length)) + message.selectedFields = []; + message.selectedFields.push(reader.string()); + break; + } + case 2: { + message.rowRestriction = reader.string(); + break; + } + case 3: { + message.arrowSerializationOptions = $root.google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a TableReadOptions message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions} TableReadOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TableReadOptions.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a TableReadOptions message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + TableReadOptions.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.selectedFields != null && message.hasOwnProperty("selectedFields")) { + if (!Array.isArray(message.selectedFields)) + return "selectedFields: array expected"; + for (var i = 0; i < message.selectedFields.length; ++i) + if (!$util.isString(message.selectedFields[i])) + return "selectedFields: string[] expected"; + } + if (message.rowRestriction != null && message.hasOwnProperty("rowRestriction")) + if (!$util.isString(message.rowRestriction)) + return "rowRestriction: string expected"; + if (message.arrowSerializationOptions != null && message.hasOwnProperty("arrowSerializationOptions")) { + var error = $root.google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions.verify(message.arrowSerializationOptions, long + 1); + if (error) + return "arrowSerializationOptions." + error; + } + return null; + }; + + /** + * Creates a TableReadOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions} TableReadOptions + */ + TableReadOptions.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions(); + if (object.selectedFields) { + if (!Array.isArray(object.selectedFields)) + throw TypeError(".google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions.selectedFields: array expected"); + message.selectedFields = []; + for (var i = 0; i < object.selectedFields.length; ++i) + message.selectedFields[i] = String(object.selectedFields[i]); + } + if (object.rowRestriction != null) + message.rowRestriction = String(object.rowRestriction); + if (object.arrowSerializationOptions != null) { + if (typeof object.arrowSerializationOptions !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions.arrowSerializationOptions: object expected"); + message.arrowSerializationOptions = $root.google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions.fromObject(object.arrowSerializationOptions, long + 1); + } + return message; + }; + + /** + * Creates a plain object from a TableReadOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions} message TableReadOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TableReadOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.selectedFields = []; + if (options.defaults) { + object.rowRestriction = ""; + object.arrowSerializationOptions = null; + } + if (message.selectedFields && message.selectedFields.length) { + object.selectedFields = []; + for (var j = 0; j < message.selectedFields.length; ++j) + object.selectedFields[j] = message.selectedFields[j]; + } + if (message.rowRestriction != null && message.hasOwnProperty("rowRestriction")) + object.rowRestriction = message.rowRestriction; + if (message.arrowSerializationOptions != null && message.hasOwnProperty("arrowSerializationOptions")) + object.arrowSerializationOptions = $root.google.cloud.bigquery.storage.v1beta2.ArrowSerializationOptions.toObject(message.arrowSerializationOptions, options); + return object; + }; + + /** + * Converts this TableReadOptions to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions + * @instance + * @returns {Object.} JSON object + */ + TableReadOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for TableReadOptions + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TableReadOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.ReadSession.TableReadOptions"; + }; + + return TableReadOptions; + })(); + + return ReadSession; + })(); + + v1beta2.ReadStream = (function() { + + /** + * Properties of a ReadStream. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IReadStream + * @property {string|null} [name] ReadStream name + */ + + /** + * Constructs a new ReadStream. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a ReadStream. + * @implements IReadStream + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IReadStream=} [properties] Properties to set + */ + function ReadStream(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * ReadStream name. + * @member {string} name + * @memberof google.cloud.bigquery.storage.v1beta2.ReadStream + * @instance + */ + ReadStream.prototype.name = ""; + + /** + * Creates a new ReadStream instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.ReadStream + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IReadStream=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.ReadStream} ReadStream instance + */ + ReadStream.create = function create(properties) { + return new ReadStream(properties); + }; + + /** + * Encodes the specified ReadStream message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadStream.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.ReadStream + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IReadStream} message ReadStream message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReadStream.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + return writer; + }; + + /** + * Encodes the specified ReadStream message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.ReadStream.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ReadStream + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IReadStream} message ReadStream message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ReadStream.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a ReadStream message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.ReadStream + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.ReadStream} ReadStream + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReadStream.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.ReadStream(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a ReadStream message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.ReadStream + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.ReadStream} ReadStream + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ReadStream.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a ReadStream message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.ReadStream + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ReadStream.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + return null; + }; + + /** + * Creates a ReadStream message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.ReadStream + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.ReadStream} ReadStream + */ + ReadStream.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.ReadStream) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.ReadStream(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a ReadStream message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.ReadStream + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ReadStream} message ReadStream + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReadStream.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 ReadStream to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.ReadStream + * @instance + * @returns {Object.} JSON object + */ + ReadStream.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ReadStream + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.ReadStream + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReadStream.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.ReadStream"; + }; + + return ReadStream; + })(); + + v1beta2.WriteStream = (function() { + + /** + * Properties of a WriteStream. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface IWriteStream + * @property {string|null} [name] WriteStream name + * @property {google.cloud.bigquery.storage.v1beta2.WriteStream.Type|null} [type] WriteStream type + * @property {google.protobuf.ITimestamp|null} [createTime] WriteStream createTime + * @property {google.protobuf.ITimestamp|null} [commitTime] WriteStream commitTime + * @property {google.cloud.bigquery.storage.v1beta2.ITableSchema|null} [tableSchema] WriteStream tableSchema + */ + + /** + * Constructs a new WriteStream. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a WriteStream. + * @implements IWriteStream + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.IWriteStream=} [properties] Properties to set + */ + function WriteStream(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * WriteStream name. + * @member {string} name + * @memberof google.cloud.bigquery.storage.v1beta2.WriteStream + * @instance + */ + WriteStream.prototype.name = ""; + + /** + * WriteStream type. + * @member {google.cloud.bigquery.storage.v1beta2.WriteStream.Type} type + * @memberof google.cloud.bigquery.storage.v1beta2.WriteStream + * @instance + */ + WriteStream.prototype.type = 0; + + /** + * WriteStream createTime. + * @member {google.protobuf.ITimestamp|null|undefined} createTime + * @memberof google.cloud.bigquery.storage.v1beta2.WriteStream + * @instance + */ + WriteStream.prototype.createTime = null; + + /** + * WriteStream commitTime. + * @member {google.protobuf.ITimestamp|null|undefined} commitTime + * @memberof google.cloud.bigquery.storage.v1beta2.WriteStream + * @instance + */ + WriteStream.prototype.commitTime = null; + + /** + * WriteStream tableSchema. + * @member {google.cloud.bigquery.storage.v1beta2.ITableSchema|null|undefined} tableSchema + * @memberof google.cloud.bigquery.storage.v1beta2.WriteStream + * @instance + */ + WriteStream.prototype.tableSchema = null; + + /** + * Creates a new WriteStream instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.WriteStream + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IWriteStream=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.WriteStream} WriteStream instance + */ + WriteStream.create = function create(properties) { + return new WriteStream(properties); + }; + + /** + * Encodes the specified WriteStream message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.WriteStream.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.WriteStream + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IWriteStream} message WriteStream message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + WriteStream.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.type != null && Object.hasOwnProperty.call(message, "type")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.type); + if (message.createTime != null && Object.hasOwnProperty.call(message, "createTime")) + $root.google.protobuf.Timestamp.encode(message.createTime, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); + if (message.commitTime != null && Object.hasOwnProperty.call(message, "commitTime")) + $root.google.protobuf.Timestamp.encode(message.commitTime, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.tableSchema != null && Object.hasOwnProperty.call(message, "tableSchema")) + $root.google.cloud.bigquery.storage.v1beta2.TableSchema.encode(message.tableSchema, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified WriteStream message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.WriteStream.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.WriteStream + * @static + * @param {google.cloud.bigquery.storage.v1beta2.IWriteStream} message WriteStream message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + WriteStream.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a WriteStream message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.WriteStream + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.WriteStream} WriteStream + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + WriteStream.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.WriteStream(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.type = reader.int32(); + break; + } + case 3: { + message.createTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + case 4: { + message.commitTime = $root.google.protobuf.Timestamp.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + case 5: { + message.tableSchema = $root.google.cloud.bigquery.storage.v1beta2.TableSchema.decode(reader, reader.uint32(), undefined, long + 1); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a WriteStream message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.WriteStream + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.WriteStream} WriteStream + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + WriteStream.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a WriteStream message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.WriteStream + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + WriteStream.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.type != null && message.hasOwnProperty("type")) + switch (message.type) { + default: + return "type: enum value expected"; + case 0: + case 1: + case 2: + case 3: + break; + } + if (message.createTime != null && message.hasOwnProperty("createTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.createTime, long + 1); + if (error) + return "createTime." + error; + } + if (message.commitTime != null && message.hasOwnProperty("commitTime")) { + var error = $root.google.protobuf.Timestamp.verify(message.commitTime, long + 1); + if (error) + return "commitTime." + error; + } + if (message.tableSchema != null && message.hasOwnProperty("tableSchema")) { + var error = $root.google.cloud.bigquery.storage.v1beta2.TableSchema.verify(message.tableSchema, long + 1); + if (error) + return "tableSchema." + error; + } + return null; + }; + + /** + * Creates a WriteStream message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.WriteStream + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.WriteStream} WriteStream + */ + WriteStream.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.WriteStream) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.WriteStream(); + if (object.name != null) + message.name = String(object.name); + switch (object.type) { + default: + if (typeof object.type === "number") { + message.type = object.type; + break; + } + break; + case "TYPE_UNSPECIFIED": + case 0: + message.type = 0; + break; + case "COMMITTED": + case 1: + message.type = 1; + break; + case "PENDING": + case 2: + message.type = 2; + break; + case "BUFFERED": + case 3: + message.type = 3; + break; + } + if (object.createTime != null) { + if (typeof object.createTime !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.WriteStream.createTime: object expected"); + message.createTime = $root.google.protobuf.Timestamp.fromObject(object.createTime, long + 1); + } + if (object.commitTime != null) { + if (typeof object.commitTime !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.WriteStream.commitTime: object expected"); + message.commitTime = $root.google.protobuf.Timestamp.fromObject(object.commitTime, long + 1); + } + if (object.tableSchema != null) { + if (typeof object.tableSchema !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.WriteStream.tableSchema: object expected"); + message.tableSchema = $root.google.cloud.bigquery.storage.v1beta2.TableSchema.fromObject(object.tableSchema, long + 1); + } + return message; + }; + + /** + * Creates a plain object from a WriteStream message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.WriteStream + * @static + * @param {google.cloud.bigquery.storage.v1beta2.WriteStream} message WriteStream + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + WriteStream.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.type = options.enums === String ? "TYPE_UNSPECIFIED" : 0; + object.createTime = null; + object.commitTime = null; + object.tableSchema = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.type != null && message.hasOwnProperty("type")) + object.type = options.enums === String ? $root.google.cloud.bigquery.storage.v1beta2.WriteStream.Type[message.type] === undefined ? message.type : $root.google.cloud.bigquery.storage.v1beta2.WriteStream.Type[message.type] : message.type; + if (message.createTime != null && message.hasOwnProperty("createTime")) + object.createTime = $root.google.protobuf.Timestamp.toObject(message.createTime, options); + if (message.commitTime != null && message.hasOwnProperty("commitTime")) + object.commitTime = $root.google.protobuf.Timestamp.toObject(message.commitTime, options); + if (message.tableSchema != null && message.hasOwnProperty("tableSchema")) + object.tableSchema = $root.google.cloud.bigquery.storage.v1beta2.TableSchema.toObject(message.tableSchema, options); + return object; + }; + + /** + * Converts this WriteStream to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.WriteStream + * @instance + * @returns {Object.} JSON object + */ + WriteStream.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for WriteStream + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.WriteStream + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + WriteStream.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.WriteStream"; + }; + + /** + * Type enum. + * @name google.cloud.bigquery.storage.v1beta2.WriteStream.Type + * @enum {number} + * @property {number} TYPE_UNSPECIFIED=0 TYPE_UNSPECIFIED value + * @property {number} COMMITTED=1 COMMITTED value + * @property {number} PENDING=2 PENDING value + * @property {number} BUFFERED=3 BUFFERED value + */ + WriteStream.Type = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "TYPE_UNSPECIFIED"] = 0; + values[valuesById[1] = "COMMITTED"] = 1; + values[valuesById[2] = "PENDING"] = 2; + values[valuesById[3] = "BUFFERED"] = 3; + return values; + })(); + + return WriteStream; + })(); + + v1beta2.TableSchema = (function() { + + /** + * Properties of a TableSchema. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface ITableSchema + * @property {Array.|null} [fields] TableSchema fields + */ + + /** + * Constructs a new TableSchema. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a TableSchema. + * @implements ITableSchema + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.ITableSchema=} [properties] Properties to set + */ + function TableSchema(properties) { + this.fields = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * TableSchema fields. + * @member {Array.} fields + * @memberof google.cloud.bigquery.storage.v1beta2.TableSchema + * @instance + */ + TableSchema.prototype.fields = $util.emptyArray; + + /** + * Creates a new TableSchema instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.TableSchema + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ITableSchema=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.TableSchema} TableSchema instance + */ + TableSchema.create = function create(properties) { + return new TableSchema(properties); + }; + + /** + * Encodes the specified TableSchema message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.TableSchema.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.TableSchema + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ITableSchema} message TableSchema message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TableSchema.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.fields != null && message.fields.length) + for (var i = 0; i < message.fields.length; ++i) + $root.google.cloud.bigquery.storage.v1beta2.TableFieldSchema.encode(message.fields[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified TableSchema message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.TableSchema.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.TableSchema + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ITableSchema} message TableSchema message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TableSchema.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a TableSchema message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.TableSchema + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.TableSchema} TableSchema + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TableSchema.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.TableSchema(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.fields && message.fields.length)) + message.fields = []; + message.fields.push($root.google.cloud.bigquery.storage.v1beta2.TableFieldSchema.decode(reader, reader.uint32(), undefined, long + 1)); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a TableSchema message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.TableSchema + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.TableSchema} TableSchema + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TableSchema.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a TableSchema message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.TableSchema + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + TableSchema.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.fields != null && message.hasOwnProperty("fields")) { + if (!Array.isArray(message.fields)) + return "fields: array expected"; + for (var i = 0; i < message.fields.length; ++i) { + var error = $root.google.cloud.bigquery.storage.v1beta2.TableFieldSchema.verify(message.fields[i], long + 1); + if (error) + return "fields." + error; + } + } + return null; + }; + + /** + * Creates a TableSchema message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.TableSchema + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.TableSchema} TableSchema + */ + TableSchema.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.TableSchema) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.TableSchema(); + if (object.fields) { + if (!Array.isArray(object.fields)) + throw TypeError(".google.cloud.bigquery.storage.v1beta2.TableSchema.fields: array expected"); + message.fields = []; + for (var i = 0; i < object.fields.length; ++i) { + if (typeof object.fields[i] !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.TableSchema.fields: object expected"); + message.fields[i] = $root.google.cloud.bigquery.storage.v1beta2.TableFieldSchema.fromObject(object.fields[i], long + 1); + } + } + return message; + }; + + /** + * Creates a plain object from a TableSchema message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.TableSchema + * @static + * @param {google.cloud.bigquery.storage.v1beta2.TableSchema} message TableSchema + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TableSchema.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.cloud.bigquery.storage.v1beta2.TableFieldSchema.toObject(message.fields[j], options); + } + return object; + }; + + /** + * Converts this TableSchema to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.TableSchema + * @instance + * @returns {Object.} JSON object + */ + TableSchema.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for TableSchema + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.TableSchema + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TableSchema.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.TableSchema"; + }; + + return TableSchema; + })(); + + v1beta2.TableFieldSchema = (function() { + + /** + * Properties of a TableFieldSchema. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @interface ITableFieldSchema + * @property {string|null} [name] TableFieldSchema name + * @property {google.cloud.bigquery.storage.v1beta2.TableFieldSchema.Type|null} [type] TableFieldSchema type + * @property {google.cloud.bigquery.storage.v1beta2.TableFieldSchema.Mode|null} [mode] TableFieldSchema mode + * @property {Array.|null} [fields] TableFieldSchema fields + * @property {string|null} [description] TableFieldSchema description + */ + + /** + * Constructs a new TableFieldSchema. + * @memberof google.cloud.bigquery.storage.v1beta2 + * @classdesc Represents a TableFieldSchema. + * @implements ITableFieldSchema + * @constructor + * @param {google.cloud.bigquery.storage.v1beta2.ITableFieldSchema=} [properties] Properties to set + */ + function TableFieldSchema(properties) { + this.fields = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null && keys[i] !== "__proto__") + this[keys[i]] = properties[keys[i]]; + } + + /** + * TableFieldSchema name. + * @member {string} name + * @memberof google.cloud.bigquery.storage.v1beta2.TableFieldSchema + * @instance + */ + TableFieldSchema.prototype.name = ""; + + /** + * TableFieldSchema type. + * @member {google.cloud.bigquery.storage.v1beta2.TableFieldSchema.Type} type + * @memberof google.cloud.bigquery.storage.v1beta2.TableFieldSchema + * @instance + */ + TableFieldSchema.prototype.type = 0; + + /** + * TableFieldSchema mode. + * @member {google.cloud.bigquery.storage.v1beta2.TableFieldSchema.Mode} mode + * @memberof google.cloud.bigquery.storage.v1beta2.TableFieldSchema + * @instance + */ + TableFieldSchema.prototype.mode = 0; + + /** + * TableFieldSchema fields. + * @member {Array.} fields + * @memberof google.cloud.bigquery.storage.v1beta2.TableFieldSchema + * @instance + */ + TableFieldSchema.prototype.fields = $util.emptyArray; + + /** + * TableFieldSchema description. + * @member {string} description + * @memberof google.cloud.bigquery.storage.v1beta2.TableFieldSchema + * @instance + */ + TableFieldSchema.prototype.description = ""; + + /** + * Creates a new TableFieldSchema instance using the specified properties. + * @function create + * @memberof google.cloud.bigquery.storage.v1beta2.TableFieldSchema + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ITableFieldSchema=} [properties] Properties to set + * @returns {google.cloud.bigquery.storage.v1beta2.TableFieldSchema} TableFieldSchema instance + */ + TableFieldSchema.create = function create(properties) { + return new TableFieldSchema(properties); + }; + + /** + * Encodes the specified TableFieldSchema message. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.TableFieldSchema.verify|verify} messages. + * @function encode + * @memberof google.cloud.bigquery.storage.v1beta2.TableFieldSchema + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ITableFieldSchema} message TableFieldSchema message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TableFieldSchema.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.name != null && Object.hasOwnProperty.call(message, "name")) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.name); + if (message.type != null && Object.hasOwnProperty.call(message, "type")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.type); + if (message.mode != null && Object.hasOwnProperty.call(message, "mode")) + writer.uint32(/* id 3, wireType 0 =*/24).int32(message.mode); + if (message.fields != null && message.fields.length) + for (var i = 0; i < message.fields.length; ++i) + $root.google.cloud.bigquery.storage.v1beta2.TableFieldSchema.encode(message.fields[i], writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.description != null && Object.hasOwnProperty.call(message, "description")) + writer.uint32(/* id 6, wireType 2 =*/50).string(message.description); + return writer; + }; + + /** + * Encodes the specified TableFieldSchema message, length delimited. Does not implicitly {@link google.cloud.bigquery.storage.v1beta2.TableFieldSchema.verify|verify} messages. + * @function encodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.TableFieldSchema + * @static + * @param {google.cloud.bigquery.storage.v1beta2.ITableFieldSchema} message TableFieldSchema message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + TableFieldSchema.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a TableFieldSchema message from the specified reader or buffer. + * @function decode + * @memberof google.cloud.bigquery.storage.v1beta2.TableFieldSchema + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.cloud.bigquery.storage.v1beta2.TableFieldSchema} TableFieldSchema + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TableFieldSchema.decode = function decode(reader, length, error, long) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + if (long === undefined) + long = 0; + if (long > $Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.cloud.bigquery.storage.v1beta2.TableFieldSchema(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.name = reader.string(); + break; + } + case 2: { + message.type = reader.int32(); + break; + } + case 3: { + message.mode = reader.int32(); + break; + } + case 4: { + if (!(message.fields && message.fields.length)) + message.fields = []; + message.fields.push($root.google.cloud.bigquery.storage.v1beta2.TableFieldSchema.decode(reader, reader.uint32(), undefined, long + 1)); + break; + } + case 6: { + message.description = reader.string(); + break; + } + default: + reader.skipType(tag & 7, long); + break; + } + } + return message; + }; + + /** + * Decodes a TableFieldSchema message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.cloud.bigquery.storage.v1beta2.TableFieldSchema + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.cloud.bigquery.storage.v1beta2.TableFieldSchema} TableFieldSchema + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + TableFieldSchema.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a TableFieldSchema message. + * @function verify + * @memberof google.cloud.bigquery.storage.v1beta2.TableFieldSchema + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + TableFieldSchema.verify = function verify(message, long) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + return "maximum nesting depth exceeded"; + if (message.name != null && message.hasOwnProperty("name")) + if (!$util.isString(message.name)) + return "name: string expected"; + if (message.type != null && message.hasOwnProperty("type")) + switch (message.type) { + default: + return "type: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 10: + case 11: + case 12: + case 13: + case 14: + case 15: + break; + } + if (message.mode != null && message.hasOwnProperty("mode")) + switch (message.mode) { + default: + return "mode: enum value expected"; + case 0: + case 1: + case 2: + case 3: + break; + } + if (message.fields != null && message.hasOwnProperty("fields")) { + if (!Array.isArray(message.fields)) + return "fields: array expected"; + for (var i = 0; i < message.fields.length; ++i) { + var error = $root.google.cloud.bigquery.storage.v1beta2.TableFieldSchema.verify(message.fields[i], long + 1); + if (error) + return "fields." + error; + } + } + if (message.description != null && message.hasOwnProperty("description")) + if (!$util.isString(message.description)) + return "description: string expected"; + return null; + }; + + /** + * Creates a TableFieldSchema message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.cloud.bigquery.storage.v1beta2.TableFieldSchema + * @static + * @param {Object.} object Plain object + * @returns {google.cloud.bigquery.storage.v1beta2.TableFieldSchema} TableFieldSchema + */ + TableFieldSchema.fromObject = function fromObject(object, long) { + if (object instanceof $root.google.cloud.bigquery.storage.v1beta2.TableFieldSchema) + return object; + if (long === undefined) + long = 0; + if (long > $util.recursionLimit) + throw Error("maximum nesting depth exceeded"); + var message = new $root.google.cloud.bigquery.storage.v1beta2.TableFieldSchema(); + if (object.name != null) + message.name = String(object.name); + switch (object.type) { + default: + if (typeof object.type === "number") { + message.type = object.type; + break; + } + break; + case "TYPE_UNSPECIFIED": + case 0: + message.type = 0; + break; + case "STRING": + case 1: + message.type = 1; + break; + case "INT64": + case 2: + message.type = 2; + break; + case "DOUBLE": + case 3: + message.type = 3; + break; + case "STRUCT": + case 4: + message.type = 4; + break; + case "BYTES": + case 5: + message.type = 5; + break; + case "BOOL": + case 6: + message.type = 6; + break; + case "TIMESTAMP": + case 7: + message.type = 7; + break; + case "DATE": + case 8: + message.type = 8; + break; + case "TIME": + case 9: + message.type = 9; + break; + case "DATETIME": + case 10: + message.type = 10; + break; + case "GEOGRAPHY": + case 11: + message.type = 11; + break; + case "NUMERIC": + case 12: + message.type = 12; + break; + case "BIGNUMERIC": + case 13: + message.type = 13; + break; + case "INTERVAL": + case 14: + message.type = 14; + break; + case "JSON": + case 15: + message.type = 15; + break; + } + switch (object.mode) { + default: + if (typeof object.mode === "number") { + message.mode = object.mode; + break; + } + break; + case "MODE_UNSPECIFIED": + case 0: + message.mode = 0; + break; + case "NULLABLE": + case 1: + message.mode = 1; + break; + case "REQUIRED": + case 2: + message.mode = 2; + break; + case "REPEATED": + case 3: + message.mode = 3; + break; + } + if (object.fields) { + if (!Array.isArray(object.fields)) + throw TypeError(".google.cloud.bigquery.storage.v1beta2.TableFieldSchema.fields: array expected"); + message.fields = []; + for (var i = 0; i < object.fields.length; ++i) { + if (typeof object.fields[i] !== "object") + throw TypeError(".google.cloud.bigquery.storage.v1beta2.TableFieldSchema.fields: object expected"); + message.fields[i] = $root.google.cloud.bigquery.storage.v1beta2.TableFieldSchema.fromObject(object.fields[i], long + 1); + } + } + if (object.description != null) + message.description = String(object.description); + return message; + }; + + /** + * Creates a plain object from a TableFieldSchema message. Also converts values to other types if specified. + * @function toObject + * @memberof google.cloud.bigquery.storage.v1beta2.TableFieldSchema + * @static + * @param {google.cloud.bigquery.storage.v1beta2.TableFieldSchema} message TableFieldSchema + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TableFieldSchema.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.fields = []; + if (options.defaults) { + object.name = ""; + object.type = options.enums === String ? "TYPE_UNSPECIFIED" : 0; + object.mode = options.enums === String ? "MODE_UNSPECIFIED" : 0; + object.description = ""; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.type != null && message.hasOwnProperty("type")) + object.type = options.enums === String ? $root.google.cloud.bigquery.storage.v1beta2.TableFieldSchema.Type[message.type] === undefined ? message.type : $root.google.cloud.bigquery.storage.v1beta2.TableFieldSchema.Type[message.type] : message.type; + if (message.mode != null && message.hasOwnProperty("mode")) + object.mode = options.enums === String ? $root.google.cloud.bigquery.storage.v1beta2.TableFieldSchema.Mode[message.mode] === undefined ? message.mode : $root.google.cloud.bigquery.storage.v1beta2.TableFieldSchema.Mode[message.mode] : message.mode; + if (message.fields && message.fields.length) { + object.fields = []; + for (var j = 0; j < message.fields.length; ++j) + object.fields[j] = $root.google.cloud.bigquery.storage.v1beta2.TableFieldSchema.toObject(message.fields[j], options); + } + if (message.description != null && message.hasOwnProperty("description")) + object.description = message.description; + return object; + }; + + /** + * Converts this TableFieldSchema to JSON. + * @function toJSON + * @memberof google.cloud.bigquery.storage.v1beta2.TableFieldSchema + * @instance + * @returns {Object.} JSON object + */ + TableFieldSchema.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for TableFieldSchema + * @function getTypeUrl + * @memberof google.cloud.bigquery.storage.v1beta2.TableFieldSchema + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TableFieldSchema.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.cloud.bigquery.storage.v1beta2.TableFieldSchema"; + }; + + /** + * Type enum. + * @name google.cloud.bigquery.storage.v1beta2.TableFieldSchema.Type + * @enum {number} + * @property {number} TYPE_UNSPECIFIED=0 TYPE_UNSPECIFIED value + * @property {number} STRING=1 STRING value + * @property {number} INT64=2 INT64 value + * @property {number} DOUBLE=3 DOUBLE value + * @property {number} STRUCT=4 STRUCT value + * @property {number} BYTES=5 BYTES value + * @property {number} BOOL=6 BOOL value + * @property {number} TIMESTAMP=7 TIMESTAMP value + * @property {number} DATE=8 DATE value + * @property {number} TIME=9 TIME value + * @property {number} DATETIME=10 DATETIME value + * @property {number} GEOGRAPHY=11 GEOGRAPHY value + * @property {number} NUMERIC=12 NUMERIC value + * @property {number} BIGNUMERIC=13 BIGNUMERIC value + * @property {number} INTERVAL=14 INTERVAL value + * @property {number} JSON=15 JSON value + */ + TableFieldSchema.Type = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "TYPE_UNSPECIFIED"] = 0; + values[valuesById[1] = "STRING"] = 1; + values[valuesById[2] = "INT64"] = 2; + values[valuesById[3] = "DOUBLE"] = 3; + values[valuesById[4] = "STRUCT"] = 4; + values[valuesById[5] = "BYTES"] = 5; + values[valuesById[6] = "BOOL"] = 6; + values[valuesById[7] = "TIMESTAMP"] = 7; + values[valuesById[8] = "DATE"] = 8; + values[valuesById[9] = "TIME"] = 9; + values[valuesById[10] = "DATETIME"] = 10; + values[valuesById[11] = "GEOGRAPHY"] = 11; + values[valuesById[12] = "NUMERIC"] = 12; + values[valuesById[13] = "BIGNUMERIC"] = 13; + values[valuesById[14] = "INTERVAL"] = 14; + values[valuesById[15] = "JSON"] = 15; + return values; + })(); + + /** + * Mode enum. + * @name google.cloud.bigquery.storage.v1beta2.TableFieldSchema.Mode + * @enum {number} + * @property {number} MODE_UNSPECIFIED=0 MODE_UNSPECIFIED value + * @property {number} NULLABLE=1 NULLABLE value + * @property {number} REQUIRED=2 REQUIRED value + * @property {number} REPEATED=3 REPEATED value + */ + TableFieldSchema.Mode = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "MODE_UNSPECIFIED"] = 0; + values[valuesById[1] = "NULLABLE"] = 1; + values[valuesById[2] = "REQUIRED"] = 2; + values[valuesById[3] = "REPEATED"] = 3; + return values; + })(); + + return TableFieldSchema; + })(); + + return v1beta2; + })(); + return storage; })(); diff --git a/handwritten/bigquery-storage/protos/protos.json b/handwritten/bigquery-storage/protos/protos.json index 3cf9dc5a2ae2..3d53db5b99e8 100644 --- a/handwritten/bigquery-storage/protos/protos.json +++ b/handwritten/bigquery-storage/protos/protos.json @@ -2730,6 +2730,927 @@ } } } + }, + "v1beta2": { + "options": { + "go_package": "cloud.google.com/go/bigquery/storage/apiv1beta2/storagepb;storagepb", + "java_multiple_files": true, + "java_outer_classname": "TableProto", + "java_package": "com.google.cloud.bigquery.storage.v1beta2", + "(google.api.resource_definition).type": "bigquery.googleapis.com/Table", + "(google.api.resource_definition).pattern": "projects/{project}/datasets/{dataset}/tables/{table}" + }, + "nested": { + "ArrowSchema": { + "fields": { + "serializedSchema": { + "type": "bytes", + "id": 1 + } + } + }, + "ArrowRecordBatch": { + "fields": { + "serializedRecordBatch": { + "type": "bytes", + "id": 1 + } + } + }, + "ArrowSerializationOptions": { + "fields": { + "format": { + "type": "Format", + "id": 1 + } + }, + "nested": { + "Format": { + "values": { + "FORMAT_UNSPECIFIED": 0, + "ARROW_0_14": 1, + "ARROW_0_15": 2 + } + } + } + }, + "AvroSchema": { + "fields": { + "schema": { + "type": "string", + "id": 1 + } + } + }, + "AvroRows": { + "fields": { + "serializedBinaryRows": { + "type": "bytes", + "id": 1 + } + } + }, + "ProtoSchema": { + "fields": { + "protoDescriptor": { + "type": "google.protobuf.DescriptorProto", + "id": 1 + } + } + }, + "ProtoRows": { + "fields": { + "serializedRows": { + "rule": "repeated", + "type": "bytes", + "id": 1 + } + } + }, + "BigQueryRead": { + "options": { + "(google.api.default_host)": "bigquerystorage.googleapis.com", + "(google.api.oauth_scopes)": "https://www.googleapis.com/auth/bigquery,https://www.googleapis.com/auth/cloud-platform" + }, + "methods": { + "CreateReadSession": { + "requestType": "CreateReadSessionRequest", + "responseType": "ReadSession", + "options": { + "(google.api.http).post": "/v1beta2/{read_session.table=projects/*/datasets/*/tables/*}", + "(google.api.http).body": "*", + "(google.api.method_signature)": "parent,read_session,max_stream_count" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1beta2/{read_session.table=projects/*/datasets/*/tables/*}", + "body": "*" + } + }, + { + "(google.api.method_signature)": "parent,read_session,max_stream_count" + } + ] + }, + "ReadRows": { + "requestType": "ReadRowsRequest", + "responseType": "ReadRowsResponse", + "responseStream": true, + "options": { + "(google.api.http).get": "/v1beta2/{read_stream=projects/*/locations/*/sessions/*/streams/*}", + "(google.api.method_signature)": "read_stream,offset" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1beta2/{read_stream=projects/*/locations/*/sessions/*/streams/*}" + } + }, + { + "(google.api.method_signature)": "read_stream,offset" + } + ] + }, + "SplitReadStream": { + "requestType": "SplitReadStreamRequest", + "responseType": "SplitReadStreamResponse", + "options": { + "(google.api.http).get": "/v1beta2/{name=projects/*/locations/*/sessions/*/streams/*}" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1beta2/{name=projects/*/locations/*/sessions/*/streams/*}" + } + } + ] + } + } + }, + "BigQueryWrite": { + "options": { + "deprecated": true, + "(google.api.default_host)": "bigquerystorage.googleapis.com", + "(google.api.oauth_scopes)": "https://www.googleapis.com/auth/bigquery,https://www.googleapis.com/auth/bigquery.insertdata,https://www.googleapis.com/auth/cloud-platform" + }, + "methods": { + "CreateWriteStream": { + "requestType": "CreateWriteStreamRequest", + "responseType": "WriteStream", + "options": { + "deprecated": true, + "(google.api.http).post": "/v1beta2/{parent=projects/*/datasets/*/tables/*}", + "(google.api.http).body": "write_stream", + "(google.api.method_signature)": "parent,write_stream" + }, + "parsedOptions": [ + { + "deprecated": true + }, + { + "(google.api.http)": { + "post": "/v1beta2/{parent=projects/*/datasets/*/tables/*}", + "body": "write_stream" + } + }, + { + "(google.api.method_signature)": "parent,write_stream" + } + ] + }, + "AppendRows": { + "requestType": "AppendRowsRequest", + "requestStream": true, + "responseType": "AppendRowsResponse", + "responseStream": true, + "options": { + "deprecated": true, + "(google.api.http).post": "/v1beta2/{write_stream=projects/*/datasets/*/tables/*/streams/*}", + "(google.api.http).body": "*", + "(google.api.method_signature)": "write_stream" + }, + "parsedOptions": [ + { + "deprecated": true + }, + { + "(google.api.http)": { + "post": "/v1beta2/{write_stream=projects/*/datasets/*/tables/*/streams/*}", + "body": "*" + } + }, + { + "(google.api.method_signature)": "write_stream" + } + ] + }, + "GetWriteStream": { + "requestType": "GetWriteStreamRequest", + "responseType": "WriteStream", + "options": { + "deprecated": true, + "(google.api.http).post": "/v1beta2/{name=projects/*/datasets/*/tables/*/streams/*}", + "(google.api.http).body": "*", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "deprecated": true + }, + { + "(google.api.http)": { + "post": "/v1beta2/{name=projects/*/datasets/*/tables/*/streams/*}", + "body": "*" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "FinalizeWriteStream": { + "requestType": "FinalizeWriteStreamRequest", + "responseType": "FinalizeWriteStreamResponse", + "options": { + "deprecated": true, + "(google.api.http).post": "/v1beta2/{name=projects/*/datasets/*/tables/*/streams/*}", + "(google.api.http).body": "*", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "deprecated": true + }, + { + "(google.api.http)": { + "post": "/v1beta2/{name=projects/*/datasets/*/tables/*/streams/*}", + "body": "*" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "BatchCommitWriteStreams": { + "requestType": "BatchCommitWriteStreamsRequest", + "responseType": "BatchCommitWriteStreamsResponse", + "options": { + "deprecated": true, + "(google.api.http).get": "/v1beta2/{parent=projects/*/datasets/*/tables/*}", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "deprecated": true + }, + { + "(google.api.http)": { + "get": "/v1beta2/{parent=projects/*/datasets/*/tables/*}" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "FlushRows": { + "requestType": "FlushRowsRequest", + "responseType": "FlushRowsResponse", + "options": { + "deprecated": true, + "(google.api.http).post": "/v1beta2/{write_stream=projects/*/datasets/*/tables/*/streams/*}", + "(google.api.http).body": "*", + "(google.api.method_signature)": "write_stream" + }, + "parsedOptions": [ + { + "deprecated": true + }, + { + "(google.api.http)": { + "post": "/v1beta2/{write_stream=projects/*/datasets/*/tables/*/streams/*}", + "body": "*" + } + }, + { + "(google.api.method_signature)": "write_stream" + } + ] + } + } + }, + "CreateReadSessionRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "cloudresourcemanager.googleapis.com/Project" + } + }, + "readSession": { + "type": "ReadSession", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "maxStreamCount": { + "type": "int32", + "id": 3 + } + } + }, + "ReadRowsRequest": { + "fields": { + "readStream": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "bigquerystorage.googleapis.com/ReadStream" + } + }, + "offset": { + "type": "int64", + "id": 2 + } + } + }, + "ThrottleState": { + "fields": { + "throttlePercent": { + "type": "int32", + "id": 1 + } + } + }, + "StreamStats": { + "fields": { + "progress": { + "type": "Progress", + "id": 2 + } + }, + "nested": { + "Progress": { + "fields": { + "atResponseStart": { + "type": "double", + "id": 1 + }, + "atResponseEnd": { + "type": "double", + "id": 2 + } + } + } + } + }, + "ReadRowsResponse": { + "oneofs": { + "rows": { + "oneof": [ + "avroRows", + "arrowRecordBatch" + ] + }, + "schema": { + "oneof": [ + "avroSchema", + "arrowSchema" + ] + } + }, + "fields": { + "avroRows": { + "type": "AvroRows", + "id": 3 + }, + "arrowRecordBatch": { + "type": "ArrowRecordBatch", + "id": 4 + }, + "rowCount": { + "type": "int64", + "id": 6 + }, + "stats": { + "type": "StreamStats", + "id": 2 + }, + "throttleState": { + "type": "ThrottleState", + "id": 5 + }, + "avroSchema": { + "type": "AvroSchema", + "id": 7, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "arrowSchema": { + "type": "ArrowSchema", + "id": 8, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + } + } + }, + "SplitReadStreamRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "bigquerystorage.googleapis.com/ReadStream" + } + }, + "fraction": { + "type": "double", + "id": 2 + } + } + }, + "SplitReadStreamResponse": { + "fields": { + "primaryStream": { + "type": "ReadStream", + "id": 1 + }, + "remainderStream": { + "type": "ReadStream", + "id": 2 + } + } + }, + "CreateWriteStreamRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "bigquery.googleapis.com/Table" + } + }, + "writeStream": { + "type": "WriteStream", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "AppendRowsRequest": { + "oneofs": { + "rows": { + "oneof": [ + "protoRows" + ] + } + }, + "fields": { + "writeStream": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "bigquerystorage.googleapis.com/WriteStream" + } + }, + "offset": { + "type": "google.protobuf.Int64Value", + "id": 2 + }, + "protoRows": { + "type": "ProtoData", + "id": 4 + }, + "traceId": { + "type": "string", + "id": 6 + } + }, + "nested": { + "ProtoData": { + "fields": { + "writerSchema": { + "type": "ProtoSchema", + "id": 1 + }, + "rows": { + "type": "ProtoRows", + "id": 2 + } + } + } + } + }, + "AppendRowsResponse": { + "oneofs": { + "response": { + "oneof": [ + "appendResult", + "error" + ] + } + }, + "fields": { + "appendResult": { + "type": "AppendResult", + "id": 1 + }, + "error": { + "type": "google.rpc.Status", + "id": 2 + }, + "updatedSchema": { + "type": "TableSchema", + "id": 3 + } + }, + "nested": { + "AppendResult": { + "fields": { + "offset": { + "type": "google.protobuf.Int64Value", + "id": 1 + } + } + } + } + }, + "GetWriteStreamRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "bigquerystorage.googleapis.com/WriteStream" + } + } + } + }, + "BatchCommitWriteStreamsRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "writeStreams": { + "rule": "repeated", + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "BatchCommitWriteStreamsResponse": { + "fields": { + "commitTime": { + "type": "google.protobuf.Timestamp", + "id": 1 + }, + "streamErrors": { + "rule": "repeated", + "type": "StorageError", + "id": 2 + } + } + }, + "FinalizeWriteStreamRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "bigquerystorage.googleapis.com/WriteStream" + } + } + } + }, + "FinalizeWriteStreamResponse": { + "fields": { + "rowCount": { + "type": "int64", + "id": 1 + } + } + }, + "FlushRowsRequest": { + "fields": { + "writeStream": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "bigquerystorage.googleapis.com/WriteStream" + } + }, + "offset": { + "type": "google.protobuf.Int64Value", + "id": 2 + } + } + }, + "FlushRowsResponse": { + "fields": { + "offset": { + "type": "int64", + "id": 1 + } + } + }, + "StorageError": { + "fields": { + "code": { + "type": "StorageErrorCode", + "id": 1 + }, + "entity": { + "type": "string", + "id": 2 + }, + "errorMessage": { + "type": "string", + "id": 3 + } + }, + "nested": { + "StorageErrorCode": { + "values": { + "STORAGE_ERROR_CODE_UNSPECIFIED": 0, + "TABLE_NOT_FOUND": 1, + "STREAM_ALREADY_COMMITTED": 2, + "STREAM_NOT_FOUND": 3, + "INVALID_STREAM_TYPE": 4, + "INVALID_STREAM_STATE": 5, + "STREAM_FINALIZED": 6 + } + } + } + }, + "DataFormat": { + "values": { + "DATA_FORMAT_UNSPECIFIED": 0, + "AVRO": 1, + "ARROW": 2 + } + }, + "ReadSession": { + "options": { + "(google.api.resource).type": "bigquerystorage.googleapis.com/ReadSession", + "(google.api.resource).pattern": "projects/{project}/locations/{location}/sessions/{session}" + }, + "oneofs": { + "schema": { + "oneof": [ + "avroSchema", + "arrowSchema" + ] + } + }, + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "expireTime": { + "type": "google.protobuf.Timestamp", + "id": 2, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "dataFormat": { + "type": "DataFormat", + "id": 3, + "options": { + "(google.api.field_behavior)": "IMMUTABLE" + } + }, + "avroSchema": { + "type": "AvroSchema", + "id": 4, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "arrowSchema": { + "type": "ArrowSchema", + "id": 5, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "table": { + "type": "string", + "id": 6, + "options": { + "(google.api.field_behavior)": "IMMUTABLE", + "(google.api.resource_reference).type": "bigquery.googleapis.com/Table" + } + }, + "tableModifiers": { + "type": "TableModifiers", + "id": 7, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "readOptions": { + "type": "TableReadOptions", + "id": 8, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "streams": { + "rule": "repeated", + "type": "ReadStream", + "id": 10, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + } + }, + "nested": { + "TableModifiers": { + "fields": { + "snapshotTime": { + "type": "google.protobuf.Timestamp", + "id": 1 + } + } + }, + "TableReadOptions": { + "fields": { + "selectedFields": { + "rule": "repeated", + "type": "string", + "id": 1 + }, + "rowRestriction": { + "type": "string", + "id": 2 + }, + "arrowSerializationOptions": { + "type": "ArrowSerializationOptions", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + } + } + }, + "ReadStream": { + "options": { + "(google.api.resource).type": "bigquerystorage.googleapis.com/ReadStream", + "(google.api.resource).pattern": "projects/{project}/locations/{location}/sessions/{session}/streams/{stream}" + }, + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + } + } + }, + "WriteStream": { + "options": { + "(google.api.resource).type": "bigquerystorage.googleapis.com/WriteStream", + "(google.api.resource).pattern": "projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}" + }, + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "type": { + "type": "Type", + "id": 2, + "options": { + "(google.api.field_behavior)": "IMMUTABLE" + } + }, + "createTime": { + "type": "google.protobuf.Timestamp", + "id": 3, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "commitTime": { + "type": "google.protobuf.Timestamp", + "id": 4, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "tableSchema": { + "type": "TableSchema", + "id": 5, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + } + }, + "nested": { + "Type": { + "values": { + "TYPE_UNSPECIFIED": 0, + "COMMITTED": 1, + "PENDING": 2, + "BUFFERED": 3 + } + } + } + }, + "TableSchema": { + "fields": { + "fields": { + "rule": "repeated", + "type": "TableFieldSchema", + "id": 1 + } + } + }, + "TableFieldSchema": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "type": { + "type": "Type", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "mode": { + "type": "Mode", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "fields": { + "rule": "repeated", + "type": "TableFieldSchema", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "description": { + "type": "string", + "id": 6, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + }, + "nested": { + "Type": { + "values": { + "TYPE_UNSPECIFIED": 0, + "STRING": 1, + "INT64": 2, + "DOUBLE": 3, + "STRUCT": 4, + "BYTES": 5, + "BOOL": 6, + "TIMESTAMP": 7, + "DATE": 8, + "TIME": 9, + "DATETIME": 10, + "GEOGRAPHY": 11, + "NUMERIC": 12, + "BIGNUMERIC": 13, + "INTERVAL": 14, + "JSON": 15 + } + }, + "Mode": { + "values": { + "MODE_UNSPECIFIED": 0, + "NULLABLE": 1, + "REQUIRED": 2, + "REPEATED": 3 + } + } + } + } + } } } } diff --git a/handwritten/bigquery-storage/samples/README.md b/handwritten/bigquery-storage/samples/README.md index 6568c068d303..054cb5ffd232 100644 --- a/handwritten/bigquery-storage/samples/README.md +++ b/handwritten/bigquery-storage/samples/README.md @@ -36,6 +36,15 @@ * [Big_query_storage.finalize_stream](#big_query_storage.finalize_stream) * [Big_query_storage.read_rows](#big_query_storage.read_rows) * [Big_query_storage.split_read_stream](#big_query_storage.split_read_stream) + * [Big_query_read.create_read_session](#big_query_read.create_read_session) + * [Big_query_read.read_rows](#big_query_read.read_rows) + * [Big_query_read.split_read_stream](#big_query_read.split_read_stream) + * [Big_query_write.append_rows](#big_query_write.append_rows) + * [Big_query_write.batch_commit_write_streams](#big_query_write.batch_commit_write_streams) + * [Big_query_write.create_write_stream](#big_query_write.create_write_stream) + * [Big_query_write.finalize_write_stream](#big_query_write.finalize_write_stream) + * [Big_query_write.flush_rows](#big_query_write.flush_rows) + * [Big_query_write.get_write_stream](#big_query_write.get_write_stream) ## Before you begin @@ -455,6 +464,159 @@ __Usage:__ `node handwritten/bigquery-storage/samples/generated/v1beta1/big_query_storage.split_read_stream.js` +----- + + + + +### Big_query_read.create_read_session + +View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_read.create_read_session.js). + +[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=handwritten/bigquery-storage/samples/generated/v1beta2/big_query_read.create_read_session.js,samples/README.md) + +__Usage:__ + + +`node handwritten/bigquery-storage/samples/generated/v1beta2/big_query_read.create_read_session.js` + + +----- + + + + +### Big_query_read.read_rows + +View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_read.read_rows.js). + +[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=handwritten/bigquery-storage/samples/generated/v1beta2/big_query_read.read_rows.js,samples/README.md) + +__Usage:__ + + +`node handwritten/bigquery-storage/samples/generated/v1beta2/big_query_read.read_rows.js` + + +----- + + + + +### Big_query_read.split_read_stream + +View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_read.split_read_stream.js). + +[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=handwritten/bigquery-storage/samples/generated/v1beta2/big_query_read.split_read_stream.js,samples/README.md) + +__Usage:__ + + +`node handwritten/bigquery-storage/samples/generated/v1beta2/big_query_read.split_read_stream.js` + + +----- + + + + +### Big_query_write.append_rows + +View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.append_rows.js). + +[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.append_rows.js,samples/README.md) + +__Usage:__ + + +`node handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.append_rows.js` + + +----- + + + + +### Big_query_write.batch_commit_write_streams + +View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.batch_commit_write_streams.js). + +[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.batch_commit_write_streams.js,samples/README.md) + +__Usage:__ + + +`node handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.batch_commit_write_streams.js` + + +----- + + + + +### Big_query_write.create_write_stream + +View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.create_write_stream.js). + +[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.create_write_stream.js,samples/README.md) + +__Usage:__ + + +`node handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.create_write_stream.js` + + +----- + + + + +### Big_query_write.finalize_write_stream + +View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.finalize_write_stream.js). + +[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.finalize_write_stream.js,samples/README.md) + +__Usage:__ + + +`node handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.finalize_write_stream.js` + + +----- + + + + +### Big_query_write.flush_rows + +View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.flush_rows.js). + +[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.flush_rows.js,samples/README.md) + +__Usage:__ + + +`node handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.flush_rows.js` + + +----- + + + + +### Big_query_write.get_write_stream + +View the [source code](https://github.com/googleapis/google-cloud-node/blob/main/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.get_write_stream.js). + +[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.get_write_stream.js,samples/README.md) + +__Usage:__ + + +`node handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.get_write_stream.js` + + diff --git a/handwritten/bigquery-storage/samples/generated/v1/big_query_read.create_read_session.js b/handwritten/bigquery-storage/samples/generated/v1/big_query_read.create_read_session.js index d6f53319cfd6..6b77630dc878 100644 --- a/handwritten/bigquery-storage/samples/generated/v1/big_query_read.create_read_session.js +++ b/handwritten/bigquery-storage/samples/generated/v1/big_query_read.create_read_session.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/bigquery-storage/samples/generated/v1/big_query_read.read_rows.js b/handwritten/bigquery-storage/samples/generated/v1/big_query_read.read_rows.js index 90f0b63cda71..9fd06b134f93 100644 --- a/handwritten/bigquery-storage/samples/generated/v1/big_query_read.read_rows.js +++ b/handwritten/bigquery-storage/samples/generated/v1/big_query_read.read_rows.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/bigquery-storage/samples/generated/v1/big_query_read.split_read_stream.js b/handwritten/bigquery-storage/samples/generated/v1/big_query_read.split_read_stream.js index 2ec67f39f570..3fade2a91fdf 100644 --- a/handwritten/bigquery-storage/samples/generated/v1/big_query_read.split_read_stream.js +++ b/handwritten/bigquery-storage/samples/generated/v1/big_query_read.split_read_stream.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/bigquery-storage/samples/generated/v1/big_query_write.append_rows.js b/handwritten/bigquery-storage/samples/generated/v1/big_query_write.append_rows.js index 240d6e2a6285..f4cd68adfb81 100644 --- a/handwritten/bigquery-storage/samples/generated/v1/big_query_write.append_rows.js +++ b/handwritten/bigquery-storage/samples/generated/v1/big_query_write.append_rows.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -62,8 +62,7 @@ function main(writeStream) { */ // const protoRows = {} /** - * Rows in arrow format. This is an experimental feature only selected for - * allowlisted customers. + * Rows in arrow format. */ // const arrowRows = {} /** @@ -91,8 +90,8 @@ function main(writeStream) { /** * Optional. Default missing value interpretation for all columns in the * table. When a value is specified on an `AppendRowsRequest`, it is applied - * to all requests on the connection from that point forward, until a - * subsequent `AppendRowsRequest` sets it to a different value. + * to all requests from that point forward, until a subsequent + * `AppendRowsRequest` sets it to a different value. * `missing_value_interpretation` can override * `default_missing_value_interpretation`. For example, if you want to write * `NULL` instead of using default values for some columns, you can set diff --git a/handwritten/bigquery-storage/samples/generated/v1/big_query_write.batch_commit_write_streams.js b/handwritten/bigquery-storage/samples/generated/v1/big_query_write.batch_commit_write_streams.js index 72d3877721ec..a12e8a444344 100644 --- a/handwritten/bigquery-storage/samples/generated/v1/big_query_write.batch_commit_write_streams.js +++ b/handwritten/bigquery-storage/samples/generated/v1/big_query_write.batch_commit_write_streams.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/bigquery-storage/samples/generated/v1/big_query_write.create_write_stream.js b/handwritten/bigquery-storage/samples/generated/v1/big_query_write.create_write_stream.js index 022ca1217a4f..89d46f575081 100644 --- a/handwritten/bigquery-storage/samples/generated/v1/big_query_write.create_write_stream.js +++ b/handwritten/bigquery-storage/samples/generated/v1/big_query_write.create_write_stream.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/bigquery-storage/samples/generated/v1/big_query_write.finalize_write_stream.js b/handwritten/bigquery-storage/samples/generated/v1/big_query_write.finalize_write_stream.js index f20f6f0a7318..01e7737068c3 100644 --- a/handwritten/bigquery-storage/samples/generated/v1/big_query_write.finalize_write_stream.js +++ b/handwritten/bigquery-storage/samples/generated/v1/big_query_write.finalize_write_stream.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/bigquery-storage/samples/generated/v1/big_query_write.flush_rows.js b/handwritten/bigquery-storage/samples/generated/v1/big_query_write.flush_rows.js index 8434830cd8c2..90babd9f6563 100644 --- a/handwritten/bigquery-storage/samples/generated/v1/big_query_write.flush_rows.js +++ b/handwritten/bigquery-storage/samples/generated/v1/big_query_write.flush_rows.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/bigquery-storage/samples/generated/v1/big_query_write.get_write_stream.js b/handwritten/bigquery-storage/samples/generated/v1/big_query_write.get_write_stream.js index 94785274b882..83e6d0849ca7 100644 --- a/handwritten/bigquery-storage/samples/generated/v1/big_query_write.get_write_stream.js +++ b/handwritten/bigquery-storage/samples/generated/v1/big_query_write.get_write_stream.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/bigquery-storage/samples/generated/v1/snippet_metadata_google.cloud.bigquery.storage.v1.json b/handwritten/bigquery-storage/samples/generated/v1/snippet_metadata_google.cloud.bigquery.storage.v1.json index 0f17af129f2d..76642dc35926 100644 --- a/handwritten/bigquery-storage/samples/generated/v1/snippet_metadata_google.cloud.bigquery.storage.v1.json +++ b/handwritten/bigquery-storage/samples/generated/v1/snippet_metadata_google.cloud.bigquery.storage.v1.json @@ -1,435 +1,435 @@ { - "clientLibrary": { - "name": "nodejs-storage", - "version": "5.1.0", - "language": "TYPESCRIPT", - "apis": [ - { - "id": "google.cloud.bigquery.storage.v1", - "version": "v1" - } - ] - }, - "snippets": [ + "clientLibrary": { + "name": "nodejs-storage", + "version": "0.1.0", + "language": "TYPESCRIPT", + "apis": [ + { + "id": "google.cloud.bigquery.storage.v1", + "version": "v1" + } + ] + }, + "snippets": [ + { + "regionTag": "bigquerystorage_v1_generated_BigQueryRead_CreateReadSession_async", + "title": "BigQueryRead createReadSession Sample", + "origin": "API_DEFINITION", + "description": " Creates a new read session. A read session divides the contents of a BigQuery table into one or more streams, which can then be used to read data from the table. The read session also specifies properties of the data to be read, such as a list of columns or a push-down filter describing the rows to be returned. A particular row can be read by at most one stream. When the caller has reached the end of each stream in the session, then all the data in the table has been read. Data is assigned to each stream such that roughly the same number of rows can be read from each stream. Because the server-side unit for assigning data is collections of rows, the API does not guarantee that each stream will return the same number or rows. Additionally, the limits are enforced based on the number of pre-filtered rows, so some filters can lead to lopsided assignments. Read sessions automatically expire 6 hours after they are created and do not require manual clean-up by the caller.", + "canonical": true, + "file": "big_query_read.create_read_session.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1_generated_BigQueryRead_CreateReadSession_async", - "title": "BigQueryRead createReadSession Sample", - "origin": "API_DEFINITION", - "description": " Creates a new read session. A read session divides the contents of a BigQuery table into one or more streams, which can then be used to read data from the table. The read session also specifies properties of the data to be read, such as a list of columns or a push-down filter describing the rows to be returned. A particular row can be read by at most one stream. When the caller has reached the end of each stream in the session, then all the data in the table has been read. Data is assigned to each stream such that roughly the same number of rows can be read from each stream. Because the server-side unit for assigning data is collections of rows, the API does not guarantee that each stream will return the same number or rows. Additionally, the limits are enforced based on the number of pre-filtered rows, so some filters can lead to lopsided assignments. Read sessions automatically expire 6 hours after they are created and do not require manual clean-up by the caller.", - "canonical": true, - "file": "big_query_read.create_read_session.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 81, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "CreateReadSession", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryRead.CreateReadSession", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "read_session", - "type": ".google.cloud.bigquery.storage.v1.ReadSession" - }, - { - "name": "max_stream_count", - "type": "TYPE_INT32" - }, - { - "name": "preferred_min_stream_count", - "type": "TYPE_INT32" - } - ], - "resultType": ".google.cloud.bigquery.storage.v1.ReadSession", - "client": { - "shortName": "BigQueryReadClient", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryReadClient" - }, - "method": { - "shortName": "CreateReadSession", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryRead.CreateReadSession", - "service": { - "shortName": "BigQueryRead", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryRead" - } - } - } + "start": 25, + "end": 81, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "CreateReadSession", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryRead.CreateReadSession", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "read_session", + "type": ".google.cloud.bigquery.storage.v1.ReadSession" + }, + { + "name": "max_stream_count", + "type": "TYPE_INT32" + }, + { + "name": "preferred_min_stream_count", + "type": "TYPE_INT32" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1.ReadSession", + "client": { + "shortName": "BigQueryReadClient", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryReadClient" }, + "method": { + "shortName": "CreateReadSession", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryRead.CreateReadSession", + "service": { + "shortName": "BigQueryRead", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryRead" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1_generated_BigQueryRead_ReadRows_async", + "title": "BigQueryRead readRows Sample", + "origin": "API_DEFINITION", + "description": " Reads rows from the stream in the format prescribed by the ReadSession. Each response contains one or more table rows, up to a maximum of 128 MB per response; read requests which attempt to read individual rows larger than 128 MB will fail. Each request also returns a set of stream statistics reflecting the current state of the stream.", + "canonical": true, + "file": "big_query_read.read_rows.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1_generated_BigQueryRead_ReadRows_async", - "title": "BigQueryRead readRows Sample", - "origin": "API_DEFINITION", - "description": " Reads rows from the stream in the format prescribed by the ReadSession. Each response contains one or more table rows, up to a maximum of 100 MiB per response; read requests which attempt to read individual rows larger than 100 MiB will fail. Each request also returns a set of stream statistics reflecting the current state of the stream.", - "canonical": true, - "file": "big_query_read.read_rows.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 61, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "ReadRows", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryRead.ReadRows", - "async": true, - "parameters": [ - { - "name": "read_stream", - "type": "TYPE_STRING" - }, - { - "name": "offset", - "type": "TYPE_INT64" - } - ], - "resultType": ".google.cloud.bigquery.storage.v1.ReadRowsResponse", - "client": { - "shortName": "BigQueryReadClient", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryReadClient" - }, - "method": { - "shortName": "ReadRows", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryRead.ReadRows", - "service": { - "shortName": "BigQueryRead", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryRead" - } - } - } + "start": 25, + "end": 61, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "ReadRows", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryRead.ReadRows", + "async": true, + "parameters": [ + { + "name": "read_stream", + "type": "TYPE_STRING" + }, + { + "name": "offset", + "type": "TYPE_INT64" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1.ReadRowsResponse", + "client": { + "shortName": "BigQueryReadClient", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryReadClient" }, + "method": { + "shortName": "ReadRows", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryRead.ReadRows", + "service": { + "shortName": "BigQueryRead", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryRead" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1_generated_BigQueryRead_SplitReadStream_async", + "title": "BigQueryRead splitReadStream Sample", + "origin": "API_DEFINITION", + "description": " Splits a given `ReadStream` into two `ReadStream` objects. These `ReadStream` objects are referred to as the primary and the residual streams of the split. The original `ReadStream` can still be read from in the same manner as before. Both of the returned `ReadStream` objects can also be read from, and the rows returned by both child streams will be the same as the rows read from the original stream. Moreover, the two child streams will be allocated back-to-back in the original `ReadStream`. Concretely, it is guaranteed that for streams original, primary, and residual, that original[0-j] = primary[0-j] and original[j-n] = residual[0-m] once the streams have been read to completion.", + "canonical": true, + "file": "big_query_read.split_read_stream.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1_generated_BigQueryRead_SplitReadStream_async", - "title": "BigQueryRead splitReadStream Sample", - "origin": "API_DEFINITION", - "description": " Splits a given `ReadStream` into two `ReadStream` objects. These `ReadStream` objects are referred to as the primary and the residual streams of the split. The original `ReadStream` can still be read from in the same manner as before. Both of the returned `ReadStream` objects can also be read from, and the rows returned by both child streams will be the same as the rows read from the original stream. Moreover, the two child streams will be allocated back-to-back in the original `ReadStream`. Concretely, it is guaranteed that for streams original, primary, and residual, that original[0-j] = primary[0-j] and original[j-n] = residual[0-m] once the streams have been read to completion.", - "canonical": true, - "file": "big_query_read.split_read_stream.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 63, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "SplitReadStream", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryRead.SplitReadStream", - "async": true, - "parameters": [ - { - "name": "name", - "type": "TYPE_STRING" - }, - { - "name": "fraction", - "type": "TYPE_DOUBLE" - } - ], - "resultType": ".google.cloud.bigquery.storage.v1.SplitReadStreamResponse", - "client": { - "shortName": "BigQueryReadClient", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryReadClient" - }, - "method": { - "shortName": "SplitReadStream", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryRead.SplitReadStream", - "service": { - "shortName": "BigQueryRead", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryRead" - } - } - } + "start": 25, + "end": 63, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "SplitReadStream", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryRead.SplitReadStream", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + }, + { + "name": "fraction", + "type": "TYPE_DOUBLE" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1.SplitReadStreamResponse", + "client": { + "shortName": "BigQueryReadClient", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryReadClient" }, + "method": { + "shortName": "SplitReadStream", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryRead.SplitReadStream", + "service": { + "shortName": "BigQueryRead", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryRead" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1_generated_BigQueryWrite_CreateWriteStream_async", + "title": "BigQueryRead createWriteStream Sample", + "origin": "API_DEFINITION", + "description": " Creates a write stream to the given table. Additionally, every table has a special stream named '_default' to which data can be written. This stream doesn't need to be created using CreateWriteStream. It is a stream that can be used simultaneously by any number of clients. Data written to this stream is considered committed as soon as an acknowledgement is received.", + "canonical": true, + "file": "big_query_write.create_write_stream.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1_generated_BigQueryWrite_CreateWriteStream_async", - "title": "BigQueryRead createWriteStream Sample", - "origin": "API_DEFINITION", - "description": " Creates a write stream to the given table. Additionally, every table has a special stream named '_default' to which data can be written. This stream doesn't need to be created using CreateWriteStream. It is a stream that can be used simultaneously by any number of clients. Data written to this stream is considered committed as soon as an acknowledgement is received.", - "canonical": true, - "file": "big_query_write.create_write_stream.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 59, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "CreateWriteStream", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.CreateWriteStream", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "write_stream", - "type": ".google.cloud.bigquery.storage.v1.WriteStream" - } - ], - "resultType": ".google.cloud.bigquery.storage.v1.WriteStream", - "client": { - "shortName": "BigQueryWriteClient", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWriteClient" - }, - "method": { - "shortName": "CreateWriteStream", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.CreateWriteStream", - "service": { - "shortName": "BigQueryWrite", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite" - } - } - } + "start": 25, + "end": 59, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "CreateWriteStream", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.CreateWriteStream", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "write_stream", + "type": ".google.cloud.bigquery.storage.v1.WriteStream" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1.WriteStream", + "client": { + "shortName": "BigQueryWriteClient", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWriteClient" }, + "method": { + "shortName": "CreateWriteStream", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.CreateWriteStream", + "service": { + "shortName": "BigQueryWrite", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1_generated_BigQueryWrite_AppendRows_async", + "title": "BigQueryRead appendRows Sample", + "origin": "API_DEFINITION", + "description": " Appends data to the given stream. If `offset` is specified, the `offset` is checked against the end of stream. The server returns `OUT_OF_RANGE` in `AppendRowsResponse` if an attempt is made to append to an offset beyond the current end of the stream or `ALREADY_EXISTS` if user provides an `offset` that has already been written to. User can retry with adjusted offset within the same RPC connection. If `offset` is not specified, append happens at the end of the stream. The response contains an optional offset at which the append happened. No offset information will be returned for appends to a default stream. Responses are received in the same order in which requests are sent. There will be one response for each successful inserted request. Responses may optionally embed error information if the originating AppendRequest was not successfully processed. The specifics of when successfully appended data is made visible to the table are governed by the type of stream: * For COMMITTED streams (which includes the default stream), data is visible immediately upon successful append. * For BUFFERED streams, data is made visible via a subsequent `FlushRows` rpc which advances a cursor to a newer offset in the stream. * For PENDING streams, data is not made visible until the stream itself is finalized (via the `FinalizeWriteStream` rpc), and the stream is explicitly committed via the `BatchCommitWriteStreams` rpc.", + "canonical": true, + "file": "big_query_write.append_rows.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1_generated_BigQueryWrite_AppendRows_async", - "title": "BigQueryRead appendRows Sample", - "origin": "API_DEFINITION", - "description": " Appends data to the given stream. If `offset` is specified, the `offset` is checked against the end of stream. The server returns `OUT_OF_RANGE` in `AppendRowsResponse` if an attempt is made to append to an offset beyond the current end of the stream or `ALREADY_EXISTS` if user provides an `offset` that has already been written to. User can retry with adjusted offset within the same RPC connection. If `offset` is not specified, append happens at the end of the stream. The response contains an optional offset at which the append happened. No offset information will be returned for appends to a default stream. Responses are received in the same order in which requests are sent. There will be one response for each successful inserted request. Responses may optionally embed error information if the originating AppendRequest was not successfully processed. The specifics of when successfully appended data is made visible to the table are governed by the type of stream: * For COMMITTED streams (which includes the default stream), data is visible immediately upon successful append. * For BUFFERED streams, data is made visible via a subsequent `FlushRows` rpc which advances a cursor to a newer offset in the stream. * For PENDING streams, data is not made visible until the stream itself is finalized (via the `FinalizeWriteStream` rpc), and the stream is explicitly committed via the `BatchCommitWriteStreams` rpc.", - "canonical": true, - "file": "big_query_write.append_rows.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 125, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "AppendRows", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.AppendRows", - "async": true, - "parameters": [ - { - "name": "write_stream", - "type": "TYPE_STRING" - }, - { - "name": "offset", - "type": ".google.protobuf.Int64Value" - }, - { - "name": "proto_rows", - "type": ".google.cloud.bigquery.storage.v1.AppendRowsRequest.ProtoData" - }, - { - "name": "arrow_rows", - "type": ".google.cloud.bigquery.storage.v1.AppendRowsRequest.ArrowData" - }, - { - "name": "trace_id", - "type": "TYPE_STRING" - }, - { - "name": "missing_value_interpretations", - "type": "TYPE_MESSAGE[]" - }, - { - "name": "default_missing_value_interpretation", - "type": ".google.cloud.bigquery.storage.v1.AppendRowsRequest.MissingValueInterpretation" - } - ], - "resultType": ".google.cloud.bigquery.storage.v1.AppendRowsResponse", - "client": { - "shortName": "BigQueryWriteClient", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWriteClient" - }, - "method": { - "shortName": "AppendRows", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.AppendRows", - "service": { - "shortName": "BigQueryWrite", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite" - } - } - } + "start": 25, + "end": 124, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "AppendRows", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.AppendRows", + "async": true, + "parameters": [ + { + "name": "write_stream", + "type": "TYPE_STRING" + }, + { + "name": "offset", + "type": ".google.protobuf.Int64Value" + }, + { + "name": "proto_rows", + "type": ".google.cloud.bigquery.storage.v1.AppendRowsRequest.ProtoData" + }, + { + "name": "arrow_rows", + "type": ".google.cloud.bigquery.storage.v1.AppendRowsRequest.ArrowData" + }, + { + "name": "trace_id", + "type": "TYPE_STRING" + }, + { + "name": "missing_value_interpretations", + "type": "TYPE_MESSAGE[]" + }, + { + "name": "default_missing_value_interpretation", + "type": ".google.cloud.bigquery.storage.v1.AppendRowsRequest.MissingValueInterpretation" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1.AppendRowsResponse", + "client": { + "shortName": "BigQueryWriteClient", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWriteClient" }, + "method": { + "shortName": "AppendRows", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.AppendRows", + "service": { + "shortName": "BigQueryWrite", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1_generated_BigQueryWrite_GetWriteStream_async", + "title": "BigQueryRead getWriteStream Sample", + "origin": "API_DEFINITION", + "description": " Gets information about a write stream.", + "canonical": true, + "file": "big_query_write.get_write_stream.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1_generated_BigQueryWrite_GetWriteStream_async", - "title": "BigQueryRead getWriteStream Sample", - "origin": "API_DEFINITION", - "description": " Gets information about a write stream.", - "canonical": true, - "file": "big_query_write.get_write_stream.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 59, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "GetWriteStream", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.GetWriteStream", - "async": true, - "parameters": [ - { - "name": "name", - "type": "TYPE_STRING" - }, - { - "name": "view", - "type": ".google.cloud.bigquery.storage.v1.WriteStreamView" - } - ], - "resultType": ".google.cloud.bigquery.storage.v1.WriteStream", - "client": { - "shortName": "BigQueryWriteClient", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWriteClient" - }, - "method": { - "shortName": "GetWriteStream", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.GetWriteStream", - "service": { - "shortName": "BigQueryWrite", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite" - } - } - } + "start": 25, + "end": 59, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "GetWriteStream", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.GetWriteStream", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + }, + { + "name": "view", + "type": ".google.cloud.bigquery.storage.v1.WriteStreamView" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1.WriteStream", + "client": { + "shortName": "BigQueryWriteClient", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWriteClient" }, + "method": { + "shortName": "GetWriteStream", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.GetWriteStream", + "service": { + "shortName": "BigQueryWrite", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1_generated_BigQueryWrite_FinalizeWriteStream_async", + "title": "BigQueryRead finalizeWriteStream Sample", + "origin": "API_DEFINITION", + "description": " Finalize a write stream so that no new data can be appended to the stream. Finalize is not supported on the '_default' stream.", + "canonical": true, + "file": "big_query_write.finalize_write_stream.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1_generated_BigQueryWrite_FinalizeWriteStream_async", - "title": "BigQueryRead finalizeWriteStream Sample", - "origin": "API_DEFINITION", - "description": " Finalize a write stream so that no new data can be appended to the stream. Finalize is not supported on the '_default' stream.", - "canonical": true, - "file": "big_query_write.finalize_write_stream.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 54, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "FinalizeWriteStream", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.FinalizeWriteStream", - "async": true, - "parameters": [ - { - "name": "name", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.cloud.bigquery.storage.v1.FinalizeWriteStreamResponse", - "client": { - "shortName": "BigQueryWriteClient", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWriteClient" - }, - "method": { - "shortName": "FinalizeWriteStream", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.FinalizeWriteStream", - "service": { - "shortName": "BigQueryWrite", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite" - } - } - } + "start": 25, + "end": 54, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "FinalizeWriteStream", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.FinalizeWriteStream", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1.FinalizeWriteStreamResponse", + "client": { + "shortName": "BigQueryWriteClient", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWriteClient" }, + "method": { + "shortName": "FinalizeWriteStream", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.FinalizeWriteStream", + "service": { + "shortName": "BigQueryWrite", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1_generated_BigQueryWrite_BatchCommitWriteStreams_async", + "title": "BigQueryRead batchCommitWriteStreams Sample", + "origin": "API_DEFINITION", + "description": " Atomically commits a group of `PENDING` streams that belong to the same `parent` table. Streams must be finalized before commit and cannot be committed multiple times. Once a stream is committed, data in the stream becomes available for read operations.", + "canonical": true, + "file": "big_query_write.batch_commit_write_streams.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1_generated_BigQueryWrite_BatchCommitWriteStreams_async", - "title": "BigQueryRead batchCommitWriteStreams Sample", - "origin": "API_DEFINITION", - "description": " Atomically commits a group of `PENDING` streams that belong to the same `parent` table. Streams must be finalized before commit and cannot be committed multiple times. Once a stream is committed, data in the stream becomes available for read operations.", - "canonical": true, - "file": "big_query_write.batch_commit_write_streams.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 59, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "BatchCommitWriteStreams", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.BatchCommitWriteStreams", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "write_streams", - "type": "TYPE_STRING[]" - } - ], - "resultType": ".google.cloud.bigquery.storage.v1.BatchCommitWriteStreamsResponse", - "client": { - "shortName": "BigQueryWriteClient", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWriteClient" - }, - "method": { - "shortName": "BatchCommitWriteStreams", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.BatchCommitWriteStreams", - "service": { - "shortName": "BigQueryWrite", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite" - } - } - } + "start": 25, + "end": 59, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "BatchCommitWriteStreams", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.BatchCommitWriteStreams", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "write_streams", + "type": "TYPE_STRING[]" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1.BatchCommitWriteStreamsResponse", + "client": { + "shortName": "BigQueryWriteClient", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWriteClient" }, + "method": { + "shortName": "BatchCommitWriteStreams", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.BatchCommitWriteStreams", + "service": { + "shortName": "BigQueryWrite", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1_generated_BigQueryWrite_FlushRows_async", + "title": "BigQueryRead flushRows Sample", + "origin": "API_DEFINITION", + "description": " Flushes rows to a BUFFERED stream. If users are appending rows to BUFFERED stream, flush operation is required in order for the rows to become available for reading. A Flush operation flushes up to any previously flushed offset in a BUFFERED stream, to the offset specified in the request. Flush is not supported on the _default stream, since it is not BUFFERED.", + "canonical": true, + "file": "big_query_write.flush_rows.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1_generated_BigQueryWrite_FlushRows_async", - "title": "BigQueryRead flushRows Sample", - "origin": "API_DEFINITION", - "description": " Flushes rows to a BUFFERED stream. If users are appending rows to BUFFERED stream, flush operation is required in order for the rows to become available for reading. A Flush operation flushes up to any previously flushed offset in a BUFFERED stream, to the offset specified in the request. Flush is not supported on the _default stream, since it is not BUFFERED.", - "canonical": true, - "file": "big_query_write.flush_rows.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 58, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "FlushRows", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.FlushRows", - "async": true, - "parameters": [ - { - "name": "write_stream", - "type": "TYPE_STRING" - }, - { - "name": "offset", - "type": ".google.protobuf.Int64Value" - } - ], - "resultType": ".google.cloud.bigquery.storage.v1.FlushRowsResponse", - "client": { - "shortName": "BigQueryWriteClient", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWriteClient" - }, - "method": { - "shortName": "FlushRows", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.FlushRows", - "service": { - "shortName": "BigQueryWrite", - "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite" - } - } - } + "start": 25, + "end": 58, + "type": "FULL" } - ] -} \ No newline at end of file + ], + "clientMethod": { + "shortName": "FlushRows", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.FlushRows", + "async": true, + "parameters": [ + { + "name": "write_stream", + "type": "TYPE_STRING" + }, + { + "name": "offset", + "type": ".google.protobuf.Int64Value" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1.FlushRowsResponse", + "client": { + "shortName": "BigQueryWriteClient", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWriteClient" + }, + "method": { + "shortName": "FlushRows", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite.FlushRows", + "service": { + "shortName": "BigQueryWrite", + "fullName": "google.cloud.bigquery.storage.v1.BigQueryWrite" + } + } + } + } + ] +} diff --git a/handwritten/bigquery-storage/samples/generated/v1alpha/metastore_partition_service.batch_create_metastore_partitions.js b/handwritten/bigquery-storage/samples/generated/v1alpha/metastore_partition_service.batch_create_metastore_partitions.js index f9552ee4a0cd..912f110b99d1 100644 --- a/handwritten/bigquery-storage/samples/generated/v1alpha/metastore_partition_service.batch_create_metastore_partitions.js +++ b/handwritten/bigquery-storage/samples/generated/v1alpha/metastore_partition_service.batch_create_metastore_partitions.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/bigquery-storage/samples/generated/v1alpha/metastore_partition_service.batch_delete_metastore_partitions.js b/handwritten/bigquery-storage/samples/generated/v1alpha/metastore_partition_service.batch_delete_metastore_partitions.js index 10d3f93907a6..89d8e0efb0d2 100644 --- a/handwritten/bigquery-storage/samples/generated/v1alpha/metastore_partition_service.batch_delete_metastore_partitions.js +++ b/handwritten/bigquery-storage/samples/generated/v1alpha/metastore_partition_service.batch_delete_metastore_partitions.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/bigquery-storage/samples/generated/v1alpha/metastore_partition_service.batch_update_metastore_partitions.js b/handwritten/bigquery-storage/samples/generated/v1alpha/metastore_partition_service.batch_update_metastore_partitions.js index 0d662372fb4b..d330a5dcb0bd 100644 --- a/handwritten/bigquery-storage/samples/generated/v1alpha/metastore_partition_service.batch_update_metastore_partitions.js +++ b/handwritten/bigquery-storage/samples/generated/v1alpha/metastore_partition_service.batch_update_metastore_partitions.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/bigquery-storage/samples/generated/v1alpha/metastore_partition_service.list_metastore_partitions.js b/handwritten/bigquery-storage/samples/generated/v1alpha/metastore_partition_service.list_metastore_partitions.js index 7b4faf856fd4..d076f31e69f7 100644 --- a/handwritten/bigquery-storage/samples/generated/v1alpha/metastore_partition_service.list_metastore_partitions.js +++ b/handwritten/bigquery-storage/samples/generated/v1alpha/metastore_partition_service.list_metastore_partitions.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/bigquery-storage/samples/generated/v1alpha/metastore_partition_service.stream_metastore_partitions.js b/handwritten/bigquery-storage/samples/generated/v1alpha/metastore_partition_service.stream_metastore_partitions.js index 233f9675c138..49ad7f13cc66 100644 --- a/handwritten/bigquery-storage/samples/generated/v1alpha/metastore_partition_service.stream_metastore_partitions.js +++ b/handwritten/bigquery-storage/samples/generated/v1alpha/metastore_partition_service.stream_metastore_partitions.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/bigquery-storage/samples/generated/v1alpha/snippet_metadata_google.cloud.bigquery.storage.v1alpha.json b/handwritten/bigquery-storage/samples/generated/v1alpha/snippet_metadata_google.cloud.bigquery.storage.v1alpha.json index 3fedb87b58a9..7ba7beeb6de5 100644 --- a/handwritten/bigquery-storage/samples/generated/v1alpha/snippet_metadata_google.cloud.bigquery.storage.v1alpha.json +++ b/handwritten/bigquery-storage/samples/generated/v1alpha/snippet_metadata_google.cloud.bigquery.storage.v1alpha.json @@ -1,259 +1,259 @@ { - "clientLibrary": { - "name": "nodejs-storage", - "version": "5.1.0", - "language": "TYPESCRIPT", - "apis": [ - { - "id": "google.cloud.bigquery.storage.v1alpha", - "version": "v1alpha" - } - ] - }, - "snippets": [ + "clientLibrary": { + "name": "nodejs-storage", + "version": "0.1.0", + "language": "TYPESCRIPT", + "apis": [ + { + "id": "google.cloud.bigquery.storage.v1alpha", + "version": "v1alpha" + } + ] + }, + "snippets": [ + { + "regionTag": "bigquerystorage_v1alpha_generated_MetastorePartitionService_BatchCreateMetastorePartitions_async", + "title": "MetastorePartitionService batchCreateMetastorePartitions Sample", + "origin": "API_DEFINITION", + "description": " Adds metastore partitions to a table.", + "canonical": true, + "file": "metastore_partition_service.batch_create_metastore_partitions.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1alpha_generated_MetastorePartitionService_BatchCreateMetastorePartitions_async", - "title": "MetastorePartitionService batchCreateMetastorePartitions Sample", - "origin": "API_DEFINITION", - "description": " Adds metastore partitions to a table.", - "canonical": true, - "file": "metastore_partition_service.batch_create_metastore_partitions.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 76, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "BatchCreateMetastorePartitions", - "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService.BatchCreateMetastorePartitions", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "requests", - "type": "TYPE_MESSAGE[]" - }, - { - "name": "skip_existing_partitions", - "type": "TYPE_BOOL" - }, - { - "name": "trace_id", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.cloud.bigquery.storage.v1alpha.BatchCreateMetastorePartitionsResponse", - "client": { - "shortName": "MetastorePartitionServiceClient", - "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionServiceClient" - }, - "method": { - "shortName": "BatchCreateMetastorePartitions", - "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService.BatchCreateMetastorePartitions", - "service": { - "shortName": "MetastorePartitionService", - "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService" - } - } - } + "start": 25, + "end": 76, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "BatchCreateMetastorePartitions", + "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService.BatchCreateMetastorePartitions", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "requests", + "type": "TYPE_MESSAGE[]" + }, + { + "name": "skip_existing_partitions", + "type": "TYPE_BOOL" + }, + { + "name": "trace_id", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1alpha.BatchCreateMetastorePartitionsResponse", + "client": { + "shortName": "MetastorePartitionServiceClient", + "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionServiceClient" }, + "method": { + "shortName": "BatchCreateMetastorePartitions", + "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService.BatchCreateMetastorePartitions", + "service": { + "shortName": "MetastorePartitionService", + "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1alpha_generated_MetastorePartitionService_BatchDeleteMetastorePartitions_async", + "title": "MetastorePartitionService batchDeleteMetastorePartitions Sample", + "origin": "API_DEFINITION", + "description": " Deletes metastore partitions from a table.", + "canonical": true, + "file": "metastore_partition_service.batch_delete_metastore_partitions.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1alpha_generated_MetastorePartitionService_BatchDeleteMetastorePartitions_async", - "title": "MetastorePartitionService batchDeleteMetastorePartitions Sample", - "origin": "API_DEFINITION", - "description": " Deletes metastore partitions from a table.", - "canonical": true, - "file": "metastore_partition_service.batch_delete_metastore_partitions.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 69, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "BatchDeleteMetastorePartitions", - "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService.BatchDeleteMetastorePartitions", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "partition_values", - "type": "TYPE_MESSAGE[]" - }, - { - "name": "trace_id", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.protobuf.Empty", - "client": { - "shortName": "MetastorePartitionServiceClient", - "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionServiceClient" - }, - "method": { - "shortName": "BatchDeleteMetastorePartitions", - "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService.BatchDeleteMetastorePartitions", - "service": { - "shortName": "MetastorePartitionService", - "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService" - } - } - } + "start": 25, + "end": 69, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "BatchDeleteMetastorePartitions", + "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService.BatchDeleteMetastorePartitions", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "partition_values", + "type": "TYPE_MESSAGE[]" + }, + { + "name": "trace_id", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.protobuf.Empty", + "client": { + "shortName": "MetastorePartitionServiceClient", + "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionServiceClient" }, + "method": { + "shortName": "BatchDeleteMetastorePartitions", + "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService.BatchDeleteMetastorePartitions", + "service": { + "shortName": "MetastorePartitionService", + "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1alpha_generated_MetastorePartitionService_BatchUpdateMetastorePartitions_async", + "title": "MetastorePartitionService batchUpdateMetastorePartitions Sample", + "origin": "API_DEFINITION", + "description": " Updates metastore partitions in a table.", + "canonical": true, + "file": "metastore_partition_service.batch_update_metastore_partitions.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1alpha_generated_MetastorePartitionService_BatchUpdateMetastorePartitions_async", - "title": "MetastorePartitionService batchUpdateMetastorePartitions Sample", - "origin": "API_DEFINITION", - "description": " Updates metastore partitions in a table.", - "canonical": true, - "file": "metastore_partition_service.batch_update_metastore_partitions.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 68, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "BatchUpdateMetastorePartitions", - "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService.BatchUpdateMetastorePartitions", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "requests", - "type": "TYPE_MESSAGE[]" - }, - { - "name": "trace_id", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.cloud.bigquery.storage.v1alpha.BatchUpdateMetastorePartitionsResponse", - "client": { - "shortName": "MetastorePartitionServiceClient", - "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionServiceClient" - }, - "method": { - "shortName": "BatchUpdateMetastorePartitions", - "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService.BatchUpdateMetastorePartitions", - "service": { - "shortName": "MetastorePartitionService", - "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService" - } - } - } + "start": 25, + "end": 68, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "BatchUpdateMetastorePartitions", + "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService.BatchUpdateMetastorePartitions", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "requests", + "type": "TYPE_MESSAGE[]" + }, + { + "name": "trace_id", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1alpha.BatchUpdateMetastorePartitionsResponse", + "client": { + "shortName": "MetastorePartitionServiceClient", + "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionServiceClient" }, + "method": { + "shortName": "BatchUpdateMetastorePartitions", + "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService.BatchUpdateMetastorePartitions", + "service": { + "shortName": "MetastorePartitionService", + "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1alpha_generated_MetastorePartitionService_ListMetastorePartitions_async", + "title": "MetastorePartitionService listMetastorePartitions Sample", + "origin": "API_DEFINITION", + "description": " Gets metastore partitions from a table.", + "canonical": true, + "file": "metastore_partition_service.list_metastore_partitions.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1alpha_generated_MetastorePartitionService_ListMetastorePartitions_async", - "title": "MetastorePartitionService listMetastorePartitions Sample", - "origin": "API_DEFINITION", - "description": " Gets metastore partitions from a table.", - "canonical": true, - "file": "metastore_partition_service.list_metastore_partitions.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 75, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "ListMetastorePartitions", - "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService.ListMetastorePartitions", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "filter", - "type": "TYPE_STRING" - }, - { - "name": "trace_id", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.cloud.bigquery.storage.v1alpha.ListMetastorePartitionsResponse", - "client": { - "shortName": "MetastorePartitionServiceClient", - "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionServiceClient" - }, - "method": { - "shortName": "ListMetastorePartitions", - "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService.ListMetastorePartitions", - "service": { - "shortName": "MetastorePartitionService", - "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService" - } - } - } + "start": 25, + "end": 75, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "ListMetastorePartitions", + "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService.ListMetastorePartitions", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "filter", + "type": "TYPE_STRING" + }, + { + "name": "trace_id", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1alpha.ListMetastorePartitionsResponse", + "client": { + "shortName": "MetastorePartitionServiceClient", + "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionServiceClient" }, + "method": { + "shortName": "ListMetastorePartitions", + "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService.ListMetastorePartitions", + "service": { + "shortName": "MetastorePartitionService", + "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1alpha_generated_MetastorePartitionService_StreamMetastorePartitions_async", + "title": "MetastorePartitionService streamMetastorePartitions Sample", + "origin": "API_DEFINITION", + "description": " This is a bi-di streaming rpc method that allows the client to send a stream of partitions and commit all of them atomically at the end. If the commit is successful, the server will return a response and close the stream. If the commit fails (due to duplicate partitions or other reason), the server will close the stream with an error. This method is only available via the gRPC API (not REST).", + "canonical": true, + "file": "metastore_partition_service.stream_metastore_partitions.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1alpha_generated_MetastorePartitionService_StreamMetastorePartitions_async", - "title": "MetastorePartitionService streamMetastorePartitions Sample", - "origin": "API_DEFINITION", - "description": " This is a bi-di streaming rpc method that allows the client to send a stream of partitions and commit all of them atomically at the end. If the commit is successful, the server will return a response and close the stream. If the commit fails (due to duplicate partitions or other reason), the server will close the stream with an error. This method is only available via the gRPC API (not REST).", - "canonical": true, - "file": "metastore_partition_service.stream_metastore_partitions.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 74, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "StreamMetastorePartitions", - "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService.StreamMetastorePartitions", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "metastore_partitions", - "type": "TYPE_MESSAGE[]" - }, - { - "name": "skip_existing_partitions", - "type": "TYPE_BOOL" - } - ], - "resultType": ".google.cloud.bigquery.storage.v1alpha.StreamMetastorePartitionsResponse", - "client": { - "shortName": "MetastorePartitionServiceClient", - "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionServiceClient" - }, - "method": { - "shortName": "StreamMetastorePartitions", - "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService.StreamMetastorePartitions", - "service": { - "shortName": "MetastorePartitionService", - "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService" - } - } - } + "start": 25, + "end": 74, + "type": "FULL" } - ] -} \ No newline at end of file + ], + "clientMethod": { + "shortName": "StreamMetastorePartitions", + "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService.StreamMetastorePartitions", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "metastore_partitions", + "type": "TYPE_MESSAGE[]" + }, + { + "name": "skip_existing_partitions", + "type": "TYPE_BOOL" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1alpha.StreamMetastorePartitionsResponse", + "client": { + "shortName": "MetastorePartitionServiceClient", + "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionServiceClient" + }, + "method": { + "shortName": "StreamMetastorePartitions", + "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService.StreamMetastorePartitions", + "service": { + "shortName": "MetastorePartitionService", + "fullName": "google.cloud.bigquery.storage.v1alpha.MetastorePartitionService" + } + } + } + } + ] +} diff --git a/handwritten/bigquery-storage/samples/generated/v1beta/metastore_partition_service.batch_create_metastore_partitions.js b/handwritten/bigquery-storage/samples/generated/v1beta/metastore_partition_service.batch_create_metastore_partitions.js index ce5d32f25151..e3360292d0f6 100644 --- a/handwritten/bigquery-storage/samples/generated/v1beta/metastore_partition_service.batch_create_metastore_partitions.js +++ b/handwritten/bigquery-storage/samples/generated/v1beta/metastore_partition_service.batch_create_metastore_partitions.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/bigquery-storage/samples/generated/v1beta/metastore_partition_service.batch_delete_metastore_partitions.js b/handwritten/bigquery-storage/samples/generated/v1beta/metastore_partition_service.batch_delete_metastore_partitions.js index f289e265b937..77c7e30cac8c 100644 --- a/handwritten/bigquery-storage/samples/generated/v1beta/metastore_partition_service.batch_delete_metastore_partitions.js +++ b/handwritten/bigquery-storage/samples/generated/v1beta/metastore_partition_service.batch_delete_metastore_partitions.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/bigquery-storage/samples/generated/v1beta/metastore_partition_service.batch_update_metastore_partitions.js b/handwritten/bigquery-storage/samples/generated/v1beta/metastore_partition_service.batch_update_metastore_partitions.js index 4ef034bffbfd..86cb412b34fa 100644 --- a/handwritten/bigquery-storage/samples/generated/v1beta/metastore_partition_service.batch_update_metastore_partitions.js +++ b/handwritten/bigquery-storage/samples/generated/v1beta/metastore_partition_service.batch_update_metastore_partitions.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/bigquery-storage/samples/generated/v1beta/metastore_partition_service.list_metastore_partitions.js b/handwritten/bigquery-storage/samples/generated/v1beta/metastore_partition_service.list_metastore_partitions.js index 188046ccc072..7c2ed318f048 100644 --- a/handwritten/bigquery-storage/samples/generated/v1beta/metastore_partition_service.list_metastore_partitions.js +++ b/handwritten/bigquery-storage/samples/generated/v1beta/metastore_partition_service.list_metastore_partitions.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/bigquery-storage/samples/generated/v1beta/metastore_partition_service.stream_metastore_partitions.js b/handwritten/bigquery-storage/samples/generated/v1beta/metastore_partition_service.stream_metastore_partitions.js index a773fb970542..74d9060c4c03 100644 --- a/handwritten/bigquery-storage/samples/generated/v1beta/metastore_partition_service.stream_metastore_partitions.js +++ b/handwritten/bigquery-storage/samples/generated/v1beta/metastore_partition_service.stream_metastore_partitions.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/bigquery-storage/samples/generated/v1beta/snippet_metadata_google.cloud.bigquery.storage.v1beta.json b/handwritten/bigquery-storage/samples/generated/v1beta/snippet_metadata_google.cloud.bigquery.storage.v1beta.json index 12b215c9741a..934ce0384000 100644 --- a/handwritten/bigquery-storage/samples/generated/v1beta/snippet_metadata_google.cloud.bigquery.storage.v1beta.json +++ b/handwritten/bigquery-storage/samples/generated/v1beta/snippet_metadata_google.cloud.bigquery.storage.v1beta.json @@ -1,259 +1,259 @@ { - "clientLibrary": { - "name": "nodejs-storage", - "version": "5.1.0", - "language": "TYPESCRIPT", - "apis": [ - { - "id": "google.cloud.bigquery.storage.v1beta", - "version": "v1beta" - } - ] - }, - "snippets": [ + "clientLibrary": { + "name": "nodejs-storage", + "version": "0.1.0", + "language": "TYPESCRIPT", + "apis": [ + { + "id": "google.cloud.bigquery.storage.v1beta", + "version": "v1beta" + } + ] + }, + "snippets": [ + { + "regionTag": "bigquerystorage_v1beta_generated_MetastorePartitionService_BatchCreateMetastorePartitions_async", + "title": "MetastorePartitionService batchCreateMetastorePartitions Sample", + "origin": "API_DEFINITION", + "description": " Adds metastore partitions to a table.", + "canonical": true, + "file": "metastore_partition_service.batch_create_metastore_partitions.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1beta_generated_MetastorePartitionService_BatchCreateMetastorePartitions_async", - "title": "MetastorePartitionService batchCreateMetastorePartitions Sample", - "origin": "API_DEFINITION", - "description": " Adds metastore partitions to a table.", - "canonical": true, - "file": "metastore_partition_service.batch_create_metastore_partitions.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 76, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "BatchCreateMetastorePartitions", - "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService.BatchCreateMetastorePartitions", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "requests", - "type": "TYPE_MESSAGE[]" - }, - { - "name": "skip_existing_partitions", - "type": "TYPE_BOOL" - }, - { - "name": "trace_id", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.cloud.bigquery.storage.v1beta.BatchCreateMetastorePartitionsResponse", - "client": { - "shortName": "MetastorePartitionServiceClient", - "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionServiceClient" - }, - "method": { - "shortName": "BatchCreateMetastorePartitions", - "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService.BatchCreateMetastorePartitions", - "service": { - "shortName": "MetastorePartitionService", - "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService" - } - } - } + "start": 25, + "end": 76, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "BatchCreateMetastorePartitions", + "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService.BatchCreateMetastorePartitions", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "requests", + "type": "TYPE_MESSAGE[]" + }, + { + "name": "skip_existing_partitions", + "type": "TYPE_BOOL" + }, + { + "name": "trace_id", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1beta.BatchCreateMetastorePartitionsResponse", + "client": { + "shortName": "MetastorePartitionServiceClient", + "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionServiceClient" }, + "method": { + "shortName": "BatchCreateMetastorePartitions", + "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService.BatchCreateMetastorePartitions", + "service": { + "shortName": "MetastorePartitionService", + "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1beta_generated_MetastorePartitionService_BatchDeleteMetastorePartitions_async", + "title": "MetastorePartitionService batchDeleteMetastorePartitions Sample", + "origin": "API_DEFINITION", + "description": " Deletes metastore partitions from a table.", + "canonical": true, + "file": "metastore_partition_service.batch_delete_metastore_partitions.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1beta_generated_MetastorePartitionService_BatchDeleteMetastorePartitions_async", - "title": "MetastorePartitionService batchDeleteMetastorePartitions Sample", - "origin": "API_DEFINITION", - "description": " Deletes metastore partitions from a table.", - "canonical": true, - "file": "metastore_partition_service.batch_delete_metastore_partitions.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 69, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "BatchDeleteMetastorePartitions", - "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService.BatchDeleteMetastorePartitions", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "partition_values", - "type": "TYPE_MESSAGE[]" - }, - { - "name": "trace_id", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.protobuf.Empty", - "client": { - "shortName": "MetastorePartitionServiceClient", - "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionServiceClient" - }, - "method": { - "shortName": "BatchDeleteMetastorePartitions", - "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService.BatchDeleteMetastorePartitions", - "service": { - "shortName": "MetastorePartitionService", - "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService" - } - } - } + "start": 25, + "end": 69, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "BatchDeleteMetastorePartitions", + "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService.BatchDeleteMetastorePartitions", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "partition_values", + "type": "TYPE_MESSAGE[]" + }, + { + "name": "trace_id", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.protobuf.Empty", + "client": { + "shortName": "MetastorePartitionServiceClient", + "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionServiceClient" }, + "method": { + "shortName": "BatchDeleteMetastorePartitions", + "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService.BatchDeleteMetastorePartitions", + "service": { + "shortName": "MetastorePartitionService", + "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1beta_generated_MetastorePartitionService_BatchUpdateMetastorePartitions_async", + "title": "MetastorePartitionService batchUpdateMetastorePartitions Sample", + "origin": "API_DEFINITION", + "description": " Updates metastore partitions in a table.", + "canonical": true, + "file": "metastore_partition_service.batch_update_metastore_partitions.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1beta_generated_MetastorePartitionService_BatchUpdateMetastorePartitions_async", - "title": "MetastorePartitionService batchUpdateMetastorePartitions Sample", - "origin": "API_DEFINITION", - "description": " Updates metastore partitions in a table.", - "canonical": true, - "file": "metastore_partition_service.batch_update_metastore_partitions.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 68, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "BatchUpdateMetastorePartitions", - "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService.BatchUpdateMetastorePartitions", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "requests", - "type": "TYPE_MESSAGE[]" - }, - { - "name": "trace_id", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.cloud.bigquery.storage.v1beta.BatchUpdateMetastorePartitionsResponse", - "client": { - "shortName": "MetastorePartitionServiceClient", - "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionServiceClient" - }, - "method": { - "shortName": "BatchUpdateMetastorePartitions", - "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService.BatchUpdateMetastorePartitions", - "service": { - "shortName": "MetastorePartitionService", - "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService" - } - } - } + "start": 25, + "end": 68, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "BatchUpdateMetastorePartitions", + "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService.BatchUpdateMetastorePartitions", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "requests", + "type": "TYPE_MESSAGE[]" + }, + { + "name": "trace_id", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1beta.BatchUpdateMetastorePartitionsResponse", + "client": { + "shortName": "MetastorePartitionServiceClient", + "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionServiceClient" }, + "method": { + "shortName": "BatchUpdateMetastorePartitions", + "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService.BatchUpdateMetastorePartitions", + "service": { + "shortName": "MetastorePartitionService", + "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1beta_generated_MetastorePartitionService_ListMetastorePartitions_async", + "title": "MetastorePartitionService listMetastorePartitions Sample", + "origin": "API_DEFINITION", + "description": " Gets metastore partitions from a table.", + "canonical": true, + "file": "metastore_partition_service.list_metastore_partitions.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1beta_generated_MetastorePartitionService_ListMetastorePartitions_async", - "title": "MetastorePartitionService listMetastorePartitions Sample", - "origin": "API_DEFINITION", - "description": " Gets metastore partitions from a table.", - "canonical": true, - "file": "metastore_partition_service.list_metastore_partitions.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 76, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "ListMetastorePartitions", - "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService.ListMetastorePartitions", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "filter", - "type": "TYPE_STRING" - }, - { - "name": "trace_id", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.cloud.bigquery.storage.v1beta.ListMetastorePartitionsResponse", - "client": { - "shortName": "MetastorePartitionServiceClient", - "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionServiceClient" - }, - "method": { - "shortName": "ListMetastorePartitions", - "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService.ListMetastorePartitions", - "service": { - "shortName": "MetastorePartitionService", - "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService" - } - } - } + "start": 25, + "end": 76, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "ListMetastorePartitions", + "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService.ListMetastorePartitions", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "filter", + "type": "TYPE_STRING" + }, + { + "name": "trace_id", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1beta.ListMetastorePartitionsResponse", + "client": { + "shortName": "MetastorePartitionServiceClient", + "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionServiceClient" }, + "method": { + "shortName": "ListMetastorePartitions", + "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService.ListMetastorePartitions", + "service": { + "shortName": "MetastorePartitionService", + "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1beta_generated_MetastorePartitionService_StreamMetastorePartitions_async", + "title": "MetastorePartitionService streamMetastorePartitions Sample", + "origin": "API_DEFINITION", + "description": " This is a bi-di streaming rpc method that allows the client to send a stream of partitions and commit all of them atomically at the end. If the commit is successful, the server will return a response and close the stream. If the commit fails (due to duplicate partitions or other reason), the server will close the stream with an error. This method is only available via the gRPC API (not REST).", + "canonical": true, + "file": "metastore_partition_service.stream_metastore_partitions.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1beta_generated_MetastorePartitionService_StreamMetastorePartitions_async", - "title": "MetastorePartitionService streamMetastorePartitions Sample", - "origin": "API_DEFINITION", - "description": " This is a bi-di streaming rpc method that allows the client to send a stream of partitions and commit all of them atomically at the end. If the commit is successful, the server will return a response and close the stream. If the commit fails (due to duplicate partitions or other reason), the server will close the stream with an error. This method is only available via the gRPC API (not REST).", - "canonical": true, - "file": "metastore_partition_service.stream_metastore_partitions.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 74, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "StreamMetastorePartitions", - "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService.StreamMetastorePartitions", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "metastore_partitions", - "type": "TYPE_MESSAGE[]" - }, - { - "name": "skip_existing_partitions", - "type": "TYPE_BOOL" - } - ], - "resultType": ".google.cloud.bigquery.storage.v1beta.StreamMetastorePartitionsResponse", - "client": { - "shortName": "MetastorePartitionServiceClient", - "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionServiceClient" - }, - "method": { - "shortName": "StreamMetastorePartitions", - "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService.StreamMetastorePartitions", - "service": { - "shortName": "MetastorePartitionService", - "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService" - } - } - } + "start": 25, + "end": 74, + "type": "FULL" } - ] -} \ No newline at end of file + ], + "clientMethod": { + "shortName": "StreamMetastorePartitions", + "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService.StreamMetastorePartitions", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "metastore_partitions", + "type": "TYPE_MESSAGE[]" + }, + { + "name": "skip_existing_partitions", + "type": "TYPE_BOOL" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1beta.StreamMetastorePartitionsResponse", + "client": { + "shortName": "MetastorePartitionServiceClient", + "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionServiceClient" + }, + "method": { + "shortName": "StreamMetastorePartitions", + "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService.StreamMetastorePartitions", + "service": { + "shortName": "MetastorePartitionService", + "fullName": "google.cloud.bigquery.storage.v1beta.MetastorePartitionService" + } + } + } + } + ] +} diff --git a/handwritten/bigquery-storage/samples/generated/v1beta1/big_query_storage.batch_create_read_session_streams.js b/handwritten/bigquery-storage/samples/generated/v1beta1/big_query_storage.batch_create_read_session_streams.js index ab34427123c0..b02f97001fc4 100644 --- a/handwritten/bigquery-storage/samples/generated/v1beta1/big_query_storage.batch_create_read_session_streams.js +++ b/handwritten/bigquery-storage/samples/generated/v1beta1/big_query_storage.batch_create_read_session_streams.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/bigquery-storage/samples/generated/v1beta1/big_query_storage.create_read_session.js b/handwritten/bigquery-storage/samples/generated/v1beta1/big_query_storage.create_read_session.js index 7b75eb954cdb..68c773ef506e 100644 --- a/handwritten/bigquery-storage/samples/generated/v1beta1/big_query_storage.create_read_session.js +++ b/handwritten/bigquery-storage/samples/generated/v1beta1/big_query_storage.create_read_session.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/bigquery-storage/samples/generated/v1beta1/big_query_storage.finalize_stream.js b/handwritten/bigquery-storage/samples/generated/v1beta1/big_query_storage.finalize_stream.js index 9f23c6a54dbf..9d2a5912080f 100644 --- a/handwritten/bigquery-storage/samples/generated/v1beta1/big_query_storage.finalize_stream.js +++ b/handwritten/bigquery-storage/samples/generated/v1beta1/big_query_storage.finalize_stream.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/bigquery-storage/samples/generated/v1beta1/big_query_storage.read_rows.js b/handwritten/bigquery-storage/samples/generated/v1beta1/big_query_storage.read_rows.js index 8dc6da158b4f..6b8aec2af86d 100644 --- a/handwritten/bigquery-storage/samples/generated/v1beta1/big_query_storage.read_rows.js +++ b/handwritten/bigquery-storage/samples/generated/v1beta1/big_query_storage.read_rows.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/bigquery-storage/samples/generated/v1beta1/big_query_storage.split_read_stream.js b/handwritten/bigquery-storage/samples/generated/v1beta1/big_query_storage.split_read_stream.js index e3fad01c93db..6a77bbf294a5 100644 --- a/handwritten/bigquery-storage/samples/generated/v1beta1/big_query_storage.split_read_stream.js +++ b/handwritten/bigquery-storage/samples/generated/v1beta1/big_query_storage.split_read_stream.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/bigquery-storage/samples/generated/v1beta1/snippet_metadata_google.cloud.bigquery.storage.v1beta1.json b/handwritten/bigquery-storage/samples/generated/v1beta1/snippet_metadata_google.cloud.bigquery.storage.v1beta1.json index 8ced04685a1d..39cb1d2c8692 100644 --- a/handwritten/bigquery-storage/samples/generated/v1beta1/snippet_metadata_google.cloud.bigquery.storage.v1beta1.json +++ b/handwritten/bigquery-storage/samples/generated/v1beta1/snippet_metadata_google.cloud.bigquery.storage.v1beta1.json @@ -1,247 +1,247 @@ { - "clientLibrary": { - "name": "nodejs-storage", - "version": "5.1.0", - "language": "TYPESCRIPT", - "apis": [ - { - "id": "google.cloud.bigquery.storage.v1beta1", - "version": "v1beta1" - } - ] - }, - "snippets": [ + "clientLibrary": { + "name": "nodejs-storage", + "version": "0.1.0", + "language": "TYPESCRIPT", + "apis": [ + { + "id": "google.cloud.bigquery.storage.v1beta1", + "version": "v1beta1" + } + ] + }, + "snippets": [ + { + "regionTag": "bigquerystorage_v1beta1_generated_BigQueryStorage_CreateReadSession_async", + "title": "BigQueryStorage createReadSession Sample", + "origin": "API_DEFINITION", + "description": " Creates a new read session. A read session divides the contents of a BigQuery table into one or more streams, which can then be used to read data from the table. The read session also specifies properties of the data to be read, such as a list of columns or a push-down filter describing the rows to be returned. A particular row can be read by at most one stream. When the caller has reached the end of each stream in the session, then all the data in the table has been read. Read sessions automatically expire 6 hours after they are created and do not require manual clean-up by the caller.", + "canonical": true, + "file": "big_query_storage.create_read_session.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1beta1_generated_BigQueryStorage_CreateReadSession_async", - "title": "BigQueryStorage createReadSession Sample", - "origin": "API_DEFINITION", - "description": " Creates a new read session. A read session divides the contents of a BigQuery table into one or more streams, which can then be used to read data from the table. The read session also specifies properties of the data to be read, such as a list of columns or a push-down filter describing the rows to be returned. A particular row can be read by at most one stream. When the caller has reached the end of each stream in the session, then all the data in the table has been read. Read sessions automatically expire 6 hours after they are created and do not require manual clean-up by the caller.", - "canonical": true, - "file": "big_query_storage.create_read_session.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 87, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "CreateReadSession", - "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage.CreateReadSession", - "async": true, - "parameters": [ - { - "name": "table_reference", - "type": ".google.cloud.bigquery.storage.v1beta1.TableReference" - }, - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "table_modifiers", - "type": ".google.cloud.bigquery.storage.v1beta1.TableModifiers" - }, - { - "name": "requested_streams", - "type": "TYPE_INT32" - }, - { - "name": "read_options", - "type": ".google.cloud.bigquery.storage.v1beta1.TableReadOptions" - }, - { - "name": "format", - "type": ".google.cloud.bigquery.storage.v1beta1.DataFormat" - }, - { - "name": "sharding_strategy", - "type": ".google.cloud.bigquery.storage.v1beta1.ShardingStrategy" - } - ], - "resultType": ".google.cloud.bigquery.storage.v1beta1.ReadSession", - "client": { - "shortName": "BigQueryStorageClient", - "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorageClient" - }, - "method": { - "shortName": "CreateReadSession", - "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage.CreateReadSession", - "service": { - "shortName": "BigQueryStorage", - "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage" - } - } - } + "start": 25, + "end": 87, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "CreateReadSession", + "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage.CreateReadSession", + "async": true, + "parameters": [ + { + "name": "table_reference", + "type": ".google.cloud.bigquery.storage.v1beta1.TableReference" + }, + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "table_modifiers", + "type": ".google.cloud.bigquery.storage.v1beta1.TableModifiers" + }, + { + "name": "requested_streams", + "type": "TYPE_INT32" + }, + { + "name": "read_options", + "type": ".google.cloud.bigquery.storage.v1beta1.TableReadOptions" + }, + { + "name": "format", + "type": ".google.cloud.bigquery.storage.v1beta1.DataFormat" + }, + { + "name": "sharding_strategy", + "type": ".google.cloud.bigquery.storage.v1beta1.ShardingStrategy" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1beta1.ReadSession", + "client": { + "shortName": "BigQueryStorageClient", + "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorageClient" }, + "method": { + "shortName": "CreateReadSession", + "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage.CreateReadSession", + "service": { + "shortName": "BigQueryStorage", + "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1beta1_generated_BigQueryStorage_ReadRows_async", + "title": "BigQueryStorage readRows Sample", + "origin": "API_DEFINITION", + "description": " Reads rows from the table in the format prescribed by the read session. Each response contains one or more table rows, up to a maximum of 10 MiB per response; read requests which attempt to read individual rows larger than this will fail. Each request also returns a set of stream statistics reflecting the estimated total number of rows in the read stream. This number is computed based on the total table size and the number of active streams in the read session, and may change as other streams continue to read data.", + "canonical": true, + "file": "big_query_storage.read_rows.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1beta1_generated_BigQueryStorage_ReadRows_async", - "title": "BigQueryStorage readRows Sample", - "origin": "API_DEFINITION", - "description": " Reads rows from the table in the format prescribed by the read session. Each response contains one or more table rows, up to a maximum of 10 MiB per response; read requests which attempt to read individual rows larger than this will fail. Each request also returns a set of stream statistics reflecting the estimated total number of rows in the read stream. This number is computed based on the total table size and the number of active streams in the read session, and may change as other streams continue to read data.", - "canonical": true, - "file": "big_query_storage.read_rows.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 57, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "ReadRows", - "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage.ReadRows", - "async": true, - "parameters": [ - { - "name": "read_position", - "type": ".google.cloud.bigquery.storage.v1beta1.StreamPosition" - } - ], - "resultType": ".google.cloud.bigquery.storage.v1beta1.ReadRowsResponse", - "client": { - "shortName": "BigQueryStorageClient", - "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorageClient" - }, - "method": { - "shortName": "ReadRows", - "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage.ReadRows", - "service": { - "shortName": "BigQueryStorage", - "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage" - } - } - } + "start": 25, + "end": 57, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "ReadRows", + "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage.ReadRows", + "async": true, + "parameters": [ + { + "name": "read_position", + "type": ".google.cloud.bigquery.storage.v1beta1.StreamPosition" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1beta1.ReadRowsResponse", + "client": { + "shortName": "BigQueryStorageClient", + "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorageClient" }, + "method": { + "shortName": "ReadRows", + "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage.ReadRows", + "service": { + "shortName": "BigQueryStorage", + "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1beta1_generated_BigQueryStorage_BatchCreateReadSessionStreams_async", + "title": "BigQueryStorage batchCreateReadSessionStreams Sample", + "origin": "API_DEFINITION", + "description": " Creates additional streams for a ReadSession. This API can be used to dynamically adjust the parallelism of a batch processing task upwards by adding additional workers.", + "canonical": true, + "file": "big_query_storage.batch_create_read_session_streams.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1beta1_generated_BigQueryStorage_BatchCreateReadSessionStreams_async", - "title": "BigQueryStorage batchCreateReadSessionStreams Sample", - "origin": "API_DEFINITION", - "description": " Creates additional streams for a ReadSession. This API can be used to dynamically adjust the parallelism of a batch processing task upwards by adding additional workers.", - "canonical": true, - "file": "big_query_storage.batch_create_read_session_streams.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 61, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "BatchCreateReadSessionStreams", - "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage.BatchCreateReadSessionStreams", - "async": true, - "parameters": [ - { - "name": "session", - "type": ".google.cloud.bigquery.storage.v1beta1.ReadSession" - }, - { - "name": "requested_streams", - "type": "TYPE_INT32" - } - ], - "resultType": ".google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsResponse", - "client": { - "shortName": "BigQueryStorageClient", - "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorageClient" - }, - "method": { - "shortName": "BatchCreateReadSessionStreams", - "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage.BatchCreateReadSessionStreams", - "service": { - "shortName": "BigQueryStorage", - "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage" - } - } - } + "start": 25, + "end": 61, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "BatchCreateReadSessionStreams", + "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage.BatchCreateReadSessionStreams", + "async": true, + "parameters": [ + { + "name": "session", + "type": ".google.cloud.bigquery.storage.v1beta1.ReadSession" + }, + { + "name": "requested_streams", + "type": "TYPE_INT32" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1beta1.BatchCreateReadSessionStreamsResponse", + "client": { + "shortName": "BigQueryStorageClient", + "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorageClient" }, + "method": { + "shortName": "BatchCreateReadSessionStreams", + "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage.BatchCreateReadSessionStreams", + "service": { + "shortName": "BigQueryStorage", + "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1beta1_generated_BigQueryStorage_FinalizeStream_async", + "title": "BigQueryStorage finalizeStream Sample", + "origin": "API_DEFINITION", + "description": " Causes a single stream in a ReadSession to gracefully stop. This API can be used to dynamically adjust the parallelism of a batch processing task downwards without losing data. This API does not delete the stream -- it remains visible in the ReadSession, and any data processed by the stream is not released to other streams. However, no additional data will be assigned to the stream once this call completes. Callers must continue reading data on the stream until the end of the stream is reached so that data which has already been assigned to the stream will be processed. This method will return an error if there are no other live streams in the Session, or if SplitReadStream() has been called on the given Stream.", + "canonical": true, + "file": "big_query_storage.finalize_stream.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1beta1_generated_BigQueryStorage_FinalizeStream_async", - "title": "BigQueryStorage finalizeStream Sample", - "origin": "API_DEFINITION", - "description": " Causes a single stream in a ReadSession to gracefully stop. This API can be used to dynamically adjust the parallelism of a batch processing task downwards without losing data. This API does not delete the stream -- it remains visible in the ReadSession, and any data processed by the stream is not released to other streams. However, no additional data will be assigned to the stream once this call completes. Callers must continue reading data on the stream until the end of the stream is reached so that data which has already been assigned to the stream will be processed. This method will return an error if there are no other live streams in the Session, or if SplitReadStream() has been called on the given Stream.", - "canonical": true, - "file": "big_query_storage.finalize_stream.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 53, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "FinalizeStream", - "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage.FinalizeStream", - "async": true, - "parameters": [ - { - "name": "stream", - "type": ".google.cloud.bigquery.storage.v1beta1.Stream" - } - ], - "resultType": ".google.protobuf.Empty", - "client": { - "shortName": "BigQueryStorageClient", - "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorageClient" - }, - "method": { - "shortName": "FinalizeStream", - "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage.FinalizeStream", - "service": { - "shortName": "BigQueryStorage", - "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage" - } - } - } + "start": 25, + "end": 53, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "FinalizeStream", + "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage.FinalizeStream", + "async": true, + "parameters": [ + { + "name": "stream", + "type": ".google.cloud.bigquery.storage.v1beta1.Stream" + } + ], + "resultType": ".google.protobuf.Empty", + "client": { + "shortName": "BigQueryStorageClient", + "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorageClient" }, + "method": { + "shortName": "FinalizeStream", + "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage.FinalizeStream", + "service": { + "shortName": "BigQueryStorage", + "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1beta1_generated_BigQueryStorage_SplitReadStream_async", + "title": "BigQueryStorage splitReadStream Sample", + "origin": "API_DEFINITION", + "description": " Splits a given read stream into two Streams. These streams are referred to as the primary and the residual of the split. The original stream can still be read from in the same manner as before. Both of the returned streams can also be read from, and the total rows return by both child streams will be the same as the rows read from the original stream. Moreover, the two child streams will be allocated back to back in the original Stream. Concretely, it is guaranteed that for streams Original, Primary, and Residual, that Original[0-j] = Primary[0-j] and Original[j-n] = Residual[0-m] once the streams have been read to completion. This method is guaranteed to be idempotent.", + "canonical": true, + "file": "big_query_storage.split_read_stream.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "bigquerystorage_v1beta1_generated_BigQueryStorage_SplitReadStream_async", - "title": "BigQueryStorage splitReadStream Sample", - "origin": "API_DEFINITION", - "description": " Splits a given read stream into two Streams. These streams are referred to as the primary and the residual of the split. The original stream can still be read from in the same manner as before. Both of the returned streams can also be read from, and the total rows return by both child streams will be the same as the rows read from the original stream. Moreover, the two child streams will be allocated back to back in the original Stream. Concretely, it is guaranteed that for streams Original, Primary, and Residual, that Original[0-j] = Primary[0-j] and Original[j-n] = Residual[0-m] once the streams have been read to completion. This method is guaranteed to be idempotent.", - "canonical": true, - "file": "big_query_storage.split_read_stream.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 63, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "SplitReadStream", - "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage.SplitReadStream", - "async": true, - "parameters": [ - { - "name": "original_stream", - "type": ".google.cloud.bigquery.storage.v1beta1.Stream" - }, - { - "name": "fraction", - "type": "TYPE_FLOAT" - } - ], - "resultType": ".google.cloud.bigquery.storage.v1beta1.SplitReadStreamResponse", - "client": { - "shortName": "BigQueryStorageClient", - "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorageClient" - }, - "method": { - "shortName": "SplitReadStream", - "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage.SplitReadStream", - "service": { - "shortName": "BigQueryStorage", - "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage" - } - } - } + "start": 25, + "end": 63, + "type": "FULL" } - ] -} \ No newline at end of file + ], + "clientMethod": { + "shortName": "SplitReadStream", + "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage.SplitReadStream", + "async": true, + "parameters": [ + { + "name": "original_stream", + "type": ".google.cloud.bigquery.storage.v1beta1.Stream" + }, + { + "name": "fraction", + "type": "TYPE_FLOAT" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1beta1.SplitReadStreamResponse", + "client": { + "shortName": "BigQueryStorageClient", + "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorageClient" + }, + "method": { + "shortName": "SplitReadStream", + "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage.SplitReadStream", + "service": { + "shortName": "BigQueryStorage", + "fullName": "google.cloud.bigquery.storage.v1beta1.BigQueryStorage" + } + } + } + } + ] +} diff --git a/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_read.create_read_session.js b/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_read.create_read_session.js new file mode 100644 index 000000000000..bbf8b2a7ab25 --- /dev/null +++ b/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_read.create_read_session.js @@ -0,0 +1,77 @@ +// Copyright 2026 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 +// +// https://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 file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(parent, readSession) { + // [START bigquerystorage_v1beta2_generated_BigQueryRead_CreateReadSession_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. The request project that owns the session, in the form of + * `projects/{project_id}`. + */ + // const parent = 'abc123' + /** + * Required. Session to be created. + */ + // const readSession = {} + /** + * Max initial number of streams. If unset or zero, the server will + * provide a value of streams so as to produce reasonable throughput. Must be + * non-negative. The number of streams may be lower than the requested number, + * depending on the amount parallelism that is reasonable for the table. Error + * will be returned if the max count is greater than the current system + * max limit of 1,000. + * Streams must be read starting from offset 0. + */ + // const maxStreamCount = 1234 + + // Imports the Storage library + const {BigQueryReadClient} = require('storage').v1beta2; + + // Instantiates a client + const storageClient = new BigQueryReadClient(); + + async function callCreateReadSession() { + // Construct request + const request = { + parent, + readSession, + }; + + // Run request + const response = await storageClient.createReadSession(request); + console.log(response); + } + + callCreateReadSession(); + // [END bigquerystorage_v1beta2_generated_BigQueryRead_CreateReadSession_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_read.read_rows.js b/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_read.read_rows.js new file mode 100644 index 000000000000..51de056a3787 --- /dev/null +++ b/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_read.read_rows.js @@ -0,0 +1,69 @@ +// Copyright 2026 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 +// +// https://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 file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(readStream) { + // [START bigquerystorage_v1beta2_generated_BigQueryRead_ReadRows_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. Stream to read rows from. + */ + // const readStream = 'abc123' + /** + * The offset requested must be less than the last row read from Read. + * Requesting a larger offset is undefined. If not specified, start reading + * from offset zero. + */ + // const offset = 1234 + + // Imports the Storage library + const {BigQueryReadClient} = require('storage').v1beta2; + + // Instantiates a client + const storageClient = new BigQueryReadClient(); + + async function callReadRows() { + // Construct request + const request = { + readStream, + }; + + // Run request + const stream = await storageClient.readRows(request); + stream.on('data', (response) => { console.log(response) }); + stream.on('error', (err) => { throw(err) }); + stream.on('end', () => { /* API call completed */ }); + } + + callReadRows(); + // [END bigquerystorage_v1beta2_generated_BigQueryRead_ReadRows_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_read.split_read_stream.js b/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_read.split_read_stream.js new file mode 100644 index 000000000000..409453802a79 --- /dev/null +++ b/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_read.split_read_stream.js @@ -0,0 +1,71 @@ +// Copyright 2026 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 +// +// https://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 file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(name) { + // [START bigquerystorage_v1beta2_generated_BigQueryRead_SplitReadStream_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. Name of the stream to split. + */ + // const name = 'abc123' + /** + * A value in the range (0.0, 1.0) that specifies the fractional point at + * which the original stream should be split. The actual split point is + * evaluated on pre-filtered rows, so if a filter is provided, then there is + * no guarantee that the division of the rows between the new child streams + * will be proportional to this fractional value. Additionally, because the + * server-side unit for assigning data is collections of rows, this fraction + * will always map to a data storage boundary on the server side. + */ + // const fraction = 1234 + + // Imports the Storage library + const {BigQueryReadClient} = require('storage').v1beta2; + + // Instantiates a client + const storageClient = new BigQueryReadClient(); + + async function callSplitReadStream() { + // Construct request + const request = { + name, + }; + + // Run request + const response = await storageClient.splitReadStream(request); + console.log(response); + } + + callSplitReadStream(); + // [END bigquerystorage_v1beta2_generated_BigQueryRead_SplitReadStream_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.append_rows.js b/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.append_rows.js new file mode 100644 index 000000000000..800d70bb3399 --- /dev/null +++ b/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.append_rows.js @@ -0,0 +1,85 @@ +// Copyright 2026 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 +// +// https://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 file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(writeStream) { + // [START bigquerystorage_v1beta2_generated_BigQueryWrite_AppendRows_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. The stream that is the target of the append operation. This value + * must be specified for the initial request. If subsequent requests specify + * the stream name, it must equal to the value provided in the first request. + * To write to the _default stream, populate this field with a string in the + * format `projects/{project}/datasets/{dataset}/tables/{table}/_default`. + */ + // const writeStream = 'abc123' + /** + * If present, the write is only performed if the next append offset is same + * as the provided value. If not present, the write is performed at the + * current end of stream. Specifying a value for this field is not allowed + * when calling AppendRows for the '_default' stream. + */ + // const offset = {} + /** + * Rows in proto format. + */ + // const protoRows = {} + /** + * Id set by client to annotate its identity. Only initial request setting is + * respected. + */ + // const traceId = 'abc123' + + // Imports the Storage library + const {BigQueryWriteClient} = require('storage').v1beta2; + + // Instantiates a client + const storageClient = new BigQueryWriteClient(); + + async function callAppendRows() { + // Construct request + const request = { + writeStream, + }; + + // Run request + const stream = await storageClient.appendRows(); + stream.on('data', (response) => { console.log(response) }); + stream.on('error', (err) => { throw(err) }); + stream.on('end', () => { /* API call completed */ }); + stream.write(request); + stream.end(); + } + + callAppendRows(); + // [END bigquerystorage_v1beta2_generated_BigQueryWrite_AppendRows_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.batch_commit_write_streams.js b/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.batch_commit_write_streams.js new file mode 100644 index 000000000000..ac93d4d78f41 --- /dev/null +++ b/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.batch_commit_write_streams.js @@ -0,0 +1,67 @@ +// Copyright 2026 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 +// +// https://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 file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(parent, writeStreams) { + // [START bigquerystorage_v1beta2_generated_BigQueryWrite_BatchCommitWriteStreams_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. Parent table that all the streams should belong to, in the form + * of `projects/{project}/datasets/{dataset}/tables/{table}`. + */ + // const parent = 'abc123' + /** + * Required. The group of streams that will be committed atomically. + */ + // const writeStreams = ['abc','def'] + + // Imports the Storage library + const {BigQueryWriteClient} = require('storage').v1beta2; + + // Instantiates a client + const storageClient = new BigQueryWriteClient(); + + async function callBatchCommitWriteStreams() { + // Construct request + const request = { + parent, + writeStreams, + }; + + // Run request + const response = await storageClient.batchCommitWriteStreams(request); + console.log(response); + } + + callBatchCommitWriteStreams(); + // [END bigquerystorage_v1beta2_generated_BigQueryWrite_BatchCommitWriteStreams_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.create_write_stream.js b/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.create_write_stream.js new file mode 100644 index 000000000000..0c97464b5fd4 --- /dev/null +++ b/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.create_write_stream.js @@ -0,0 +1,67 @@ +// Copyright 2026 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 +// +// https://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 file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(parent, writeStream) { + // [START bigquerystorage_v1beta2_generated_BigQueryWrite_CreateWriteStream_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. Reference to the table to which the stream belongs, in the format + * of `projects/{project}/datasets/{dataset}/tables/{table}`. + */ + // const parent = 'abc123' + /** + * Required. Stream to be created. + */ + // const writeStream = {} + + // Imports the Storage library + const {BigQueryWriteClient} = require('storage').v1beta2; + + // Instantiates a client + const storageClient = new BigQueryWriteClient(); + + async function callCreateWriteStream() { + // Construct request + const request = { + parent, + writeStream, + }; + + // Run request + const response = await storageClient.createWriteStream(request); + console.log(response); + } + + callCreateWriteStream(); + // [END bigquerystorage_v1beta2_generated_BigQueryWrite_CreateWriteStream_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.finalize_write_stream.js b/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.finalize_write_stream.js new file mode 100644 index 000000000000..ccc8e99f9248 --- /dev/null +++ b/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.finalize_write_stream.js @@ -0,0 +1,62 @@ +// Copyright 2026 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 +// +// https://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 file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(name) { + // [START bigquerystorage_v1beta2_generated_BigQueryWrite_FinalizeWriteStream_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. Name of the stream to finalize, in the form of + * `projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}`. + */ + // const name = 'abc123' + + // Imports the Storage library + const {BigQueryWriteClient} = require('storage').v1beta2; + + // Instantiates a client + const storageClient = new BigQueryWriteClient(); + + async function callFinalizeWriteStream() { + // Construct request + const request = { + name, + }; + + // Run request + const response = await storageClient.finalizeWriteStream(request); + console.log(response); + } + + callFinalizeWriteStream(); + // [END bigquerystorage_v1beta2_generated_BigQueryWrite_FinalizeWriteStream_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.flush_rows.js b/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.flush_rows.js new file mode 100644 index 000000000000..859953c76b01 --- /dev/null +++ b/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.flush_rows.js @@ -0,0 +1,66 @@ +// Copyright 2026 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 +// +// https://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 file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(writeStream) { + // [START bigquerystorage_v1beta2_generated_BigQueryWrite_FlushRows_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. The stream that is the target of the flush operation. + */ + // const writeStream = 'abc123' + /** + * Ending offset of the flush operation. Rows before this offset(including + * this offset) will be flushed. + */ + // const offset = {} + + // Imports the Storage library + const {BigQueryWriteClient} = require('storage').v1beta2; + + // Instantiates a client + const storageClient = new BigQueryWriteClient(); + + async function callFlushRows() { + // Construct request + const request = { + writeStream, + }; + + // Run request + const response = await storageClient.flushRows(request); + console.log(response); + } + + callFlushRows(); + // [END bigquerystorage_v1beta2_generated_BigQueryWrite_FlushRows_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.get_write_stream.js b/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.get_write_stream.js new file mode 100644 index 000000000000..a4f5f67f1302 --- /dev/null +++ b/handwritten/bigquery-storage/samples/generated/v1beta2/big_query_write.get_write_stream.js @@ -0,0 +1,62 @@ +// Copyright 2026 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 +// +// https://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 file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + + + +'use strict'; + +function main(name) { + // [START bigquerystorage_v1beta2_generated_BigQueryWrite_GetWriteStream_async] + /** + * This snippet has been automatically generated and should be regarded as a code template only. + * It will require modifications to work. + * It may require correct/in-range values for request initialization. + * TODO(developer): Uncomment these variables before running the sample. + */ + /** + * Required. Name of the stream to get, in the form of + * `projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}`. + */ + // const name = 'abc123' + + // Imports the Storage library + const {BigQueryWriteClient} = require('storage').v1beta2; + + // Instantiates a client + const storageClient = new BigQueryWriteClient(); + + async function callGetWriteStream() { + // Construct request + const request = { + name, + }; + + // Run request + const response = await storageClient.getWriteStream(request); + console.log(response); + } + + callGetWriteStream(); + // [END bigquerystorage_v1beta2_generated_BigQueryWrite_GetWriteStream_async] +} + +process.on('unhandledRejection', err => { + console.error(err.message); + process.exitCode = 1; +}); +main(...process.argv.slice(2)); diff --git a/handwritten/bigquery-storage/samples/generated/v1beta2/snippet_metadata_google.cloud.bigquery.storage.v1beta2.json b/handwritten/bigquery-storage/samples/generated/v1beta2/snippet_metadata_google.cloud.bigquery.storage.v1beta2.json new file mode 100644 index 000000000000..949ee0cf2160 --- /dev/null +++ b/handwritten/bigquery-storage/samples/generated/v1beta2/snippet_metadata_google.cloud.bigquery.storage.v1beta2.json @@ -0,0 +1,415 @@ +{ + "clientLibrary": { + "name": "nodejs-storage", + "version": "0.1.0", + "language": "TYPESCRIPT", + "apis": [ + { + "id": "google.cloud.bigquery.storage.v1beta2", + "version": "v1beta2" + } + ] + }, + "snippets": [ + { + "regionTag": "bigquerystorage_v1beta2_generated_BigQueryRead_CreateReadSession_async", + "title": "BigQueryRead createReadSession Sample", + "origin": "API_DEFINITION", + "description": " Creates a new read session. A read session divides the contents of a BigQuery table into one or more streams, which can then be used to read data from the table. The read session also specifies properties of the data to be read, such as a list of columns or a push-down filter describing the rows to be returned. A particular row can be read by at most one stream. When the caller has reached the end of each stream in the session, then all the data in the table has been read. Data is assigned to each stream such that roughly the same number of rows can be read from each stream. Because the server-side unit for assigning data is collections of rows, the API does not guarantee that each stream will return the same number or rows. Additionally, the limits are enforced based on the number of pre-filtered rows, so some filters can lead to lopsided assignments. Read sessions automatically expire 6 hours after they are created and do not require manual clean-up by the caller.", + "canonical": true, + "file": "big_query_read.create_read_session.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 69, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "CreateReadSession", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryRead.CreateReadSession", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "read_session", + "type": ".google.cloud.bigquery.storage.v1beta2.ReadSession" + }, + { + "name": "max_stream_count", + "type": "TYPE_INT32" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1beta2.ReadSession", + "client": { + "shortName": "BigQueryReadClient", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryReadClient" + }, + "method": { + "shortName": "CreateReadSession", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryRead.CreateReadSession", + "service": { + "shortName": "BigQueryRead", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryRead" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1beta2_generated_BigQueryRead_ReadRows_async", + "title": "BigQueryRead readRows Sample", + "origin": "API_DEFINITION", + "description": " Reads rows from the stream in the format prescribed by the ReadSession. Each response contains one or more table rows, up to a maximum of 100 MiB per response; read requests which attempt to read individual rows larger than 100 MiB will fail. Each request also returns a set of stream statistics reflecting the current state of the stream.", + "canonical": true, + "file": "big_query_read.read_rows.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 61, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "ReadRows", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryRead.ReadRows", + "async": true, + "parameters": [ + { + "name": "read_stream", + "type": "TYPE_STRING" + }, + { + "name": "offset", + "type": "TYPE_INT64" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1beta2.ReadRowsResponse", + "client": { + "shortName": "BigQueryReadClient", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryReadClient" + }, + "method": { + "shortName": "ReadRows", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryRead.ReadRows", + "service": { + "shortName": "BigQueryRead", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryRead" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1beta2_generated_BigQueryRead_SplitReadStream_async", + "title": "BigQueryRead splitReadStream Sample", + "origin": "API_DEFINITION", + "description": " Splits a given `ReadStream` into two `ReadStream` objects. These `ReadStream` objects are referred to as the primary and the residual streams of the split. The original `ReadStream` can still be read from in the same manner as before. Both of the returned `ReadStream` objects can also be read from, and the rows returned by both child streams will be the same as the rows read from the original stream. Moreover, the two child streams will be allocated back-to-back in the original `ReadStream`. Concretely, it is guaranteed that for streams original, primary, and residual, that original[0-j] = primary[0-j] and original[j-n] = residual[0-m] once the streams have been read to completion.", + "canonical": true, + "file": "big_query_read.split_read_stream.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 63, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "SplitReadStream", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryRead.SplitReadStream", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + }, + { + "name": "fraction", + "type": "TYPE_DOUBLE" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse", + "client": { + "shortName": "BigQueryReadClient", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryReadClient" + }, + "method": { + "shortName": "SplitReadStream", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryRead.SplitReadStream", + "service": { + "shortName": "BigQueryRead", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryRead" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1beta2_generated_BigQueryWrite_CreateWriteStream_async", + "title": "BigQueryRead createWriteStream Sample", + "origin": "API_DEFINITION", + "description": " Creates a write stream to the given table. Additionally, every table has a special COMMITTED stream named '_default' to which data can be written. This stream doesn't need to be created using CreateWriteStream. It is a stream that can be used simultaneously by any number of clients. Data written to this stream is considered committed as soon as an acknowledgement is received.", + "canonical": true, + "file": "big_query_write.create_write_stream.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 59, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "CreateWriteStream", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWrite.CreateWriteStream", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "write_stream", + "type": ".google.cloud.bigquery.storage.v1beta2.WriteStream" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1beta2.WriteStream", + "client": { + "shortName": "BigQueryWriteClient", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWriteClient" + }, + "method": { + "shortName": "CreateWriteStream", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWrite.CreateWriteStream", + "service": { + "shortName": "BigQueryWrite", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWrite" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1beta2_generated_BigQueryWrite_AppendRows_async", + "title": "BigQueryRead appendRows Sample", + "origin": "API_DEFINITION", + "description": " Appends data to the given stream. If `offset` is specified, the `offset` is checked against the end of stream. The server returns `OUT_OF_RANGE` in `AppendRowsResponse` if an attempt is made to append to an offset beyond the current end of the stream or `ALREADY_EXISTS` if user provids an `offset` that has already been written to. User can retry with adjusted offset within the same RPC stream. If `offset` is not specified, append happens at the end of the stream. The response contains the offset at which the append happened. Responses are received in the same order in which requests are sent. There will be one response for each successful request. If the `offset` is not set in response, it means append didn't happen due to some errors. If one request fails, all the subsequent requests will also fail until a success request is made again. If the stream is of `PENDING` type, data will only be available for read operations after the stream is committed.", + "canonical": true, + "file": "big_query_write.append_rows.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 77, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "AppendRows", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWrite.AppendRows", + "async": true, + "parameters": [ + { + "name": "write_stream", + "type": "TYPE_STRING" + }, + { + "name": "offset", + "type": ".google.protobuf.Int64Value" + }, + { + "name": "proto_rows", + "type": ".google.cloud.bigquery.storage.v1beta2.AppendRowsRequest.ProtoData" + }, + { + "name": "trace_id", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1beta2.AppendRowsResponse", + "client": { + "shortName": "BigQueryWriteClient", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWriteClient" + }, + "method": { + "shortName": "AppendRows", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWrite.AppendRows", + "service": { + "shortName": "BigQueryWrite", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWrite" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1beta2_generated_BigQueryWrite_GetWriteStream_async", + "title": "BigQueryRead getWriteStream Sample", + "origin": "API_DEFINITION", + "description": " Gets a write stream.", + "canonical": true, + "file": "big_query_write.get_write_stream.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 54, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "GetWriteStream", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWrite.GetWriteStream", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1beta2.WriteStream", + "client": { + "shortName": "BigQueryWriteClient", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWriteClient" + }, + "method": { + "shortName": "GetWriteStream", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWrite.GetWriteStream", + "service": { + "shortName": "BigQueryWrite", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWrite" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1beta2_generated_BigQueryWrite_FinalizeWriteStream_async", + "title": "BigQueryRead finalizeWriteStream Sample", + "origin": "API_DEFINITION", + "description": " Finalize a write stream so that no new data can be appended to the stream. Finalize is not supported on the '_default' stream.", + "canonical": true, + "file": "big_query_write.finalize_write_stream.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 54, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "FinalizeWriteStream", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWrite.FinalizeWriteStream", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse", + "client": { + "shortName": "BigQueryWriteClient", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWriteClient" + }, + "method": { + "shortName": "FinalizeWriteStream", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWrite.FinalizeWriteStream", + "service": { + "shortName": "BigQueryWrite", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWrite" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1beta2_generated_BigQueryWrite_BatchCommitWriteStreams_async", + "title": "BigQueryRead batchCommitWriteStreams Sample", + "origin": "API_DEFINITION", + "description": " Atomically commits a group of `PENDING` streams that belong to the same `parent` table. Streams must be finalized before commit and cannot be committed multiple times. Once a stream is committed, data in the stream becomes available for read operations.", + "canonical": true, + "file": "big_query_write.batch_commit_write_streams.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 59, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "BatchCommitWriteStreams", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWrite.BatchCommitWriteStreams", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "write_streams", + "type": "TYPE_STRING[]" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse", + "client": { + "shortName": "BigQueryWriteClient", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWriteClient" + }, + "method": { + "shortName": "BatchCommitWriteStreams", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWrite.BatchCommitWriteStreams", + "service": { + "shortName": "BigQueryWrite", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWrite" + } + } + } + }, + { + "regionTag": "bigquerystorage_v1beta2_generated_BigQueryWrite_FlushRows_async", + "title": "BigQueryRead flushRows Sample", + "origin": "API_DEFINITION", + "description": " Flushes rows to a BUFFERED stream. If users are appending rows to BUFFERED stream, flush operation is required in order for the rows to become available for reading. A Flush operation flushes up to any previously flushed offset in a BUFFERED stream, to the offset specified in the request. Flush is not supported on the _default stream, since it is not BUFFERED.", + "canonical": true, + "file": "big_query_write.flush_rows.js", + "language": "JAVASCRIPT", + "segments": [ + { + "start": 25, + "end": 58, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "FlushRows", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWrite.FlushRows", + "async": true, + "parameters": [ + { + "name": "write_stream", + "type": "TYPE_STRING" + }, + { + "name": "offset", + "type": ".google.protobuf.Int64Value" + } + ], + "resultType": ".google.cloud.bigquery.storage.v1beta2.FlushRowsResponse", + "client": { + "shortName": "BigQueryWriteClient", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWriteClient" + }, + "method": { + "shortName": "FlushRows", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWrite.FlushRows", + "service": { + "shortName": "BigQueryWrite", + "fullName": "google.cloud.bigquery.storage.v1beta2.BigQueryWrite" + } + } + } + } + ] +} diff --git a/handwritten/bigquery-storage/src/v1/big_query_read_client.ts b/handwritten/bigquery-storage/src/v1/big_query_read_client.ts index b34ec292cc94..0c6706f874be 100644 --- a/handwritten/bigquery-storage/src/v1/big_query_read_client.ts +++ b/handwritten/bigquery-storage/src/v1/big_query_read_client.ts @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,10 +24,10 @@ import type { Descriptors, ClientOptions, } from 'google-gax'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -51,7 +51,7 @@ export class BigQueryReadClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('bigquery-storage'); @@ -64,9 +64,9 @@ export class BigQueryReadClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - bigQueryReadStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + bigQueryReadStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of BigQueryReadClient. @@ -142,7 +142,7 @@ export class BigQueryReadClient { const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -231,7 +231,7 @@ export class BigQueryReadClient { 'google.cloud.bigquery.storage.v1.BigQueryRead', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')}, + { 'x-goog-api-client': clientHeader.join(' ') }, ); // Set up a dictionary of "inner API calls"; the core implementation @@ -271,7 +271,7 @@ export class BigQueryReadClient { (this._protos as any).google.cloud.bigquery.storage.v1.BigQueryRead, this._opts, this._providedCustomServicePath, - ) as Promise<{[method: string]: Function}>; + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -282,11 +282,11 @@ export class BigQueryReadClient { ]; for (const methodName of bigQueryReadStubMethods) { const callPromise = this.bigQueryReadStub.then( - stub => + (stub) => (...args: Array<{}>) => { if (this._terminated) { if (methodName in this.descriptors.stream) { - const stream = new PassThrough({objectMode: true}); + const stream = new PassThrough({ objectMode: true }); setImmediate(() => { stream.emit( 'error', @@ -542,7 +542,7 @@ export class BigQueryReadClient { this._gaxModule.routingHeader.fromParams({ 'read_session.table': request.readSession!.table ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('createReadSession request %j', request); @@ -704,7 +704,7 @@ export class BigQueryReadClient { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('splitReadStream request %j', request); @@ -757,9 +757,9 @@ export class BigQueryReadClient { /** * Reads rows from the stream in the format prescribed by the ReadSession. - * Each response contains one or more table rows, up to a maximum of 100 MiB + * Each response contains one or more table rows, up to a maximum of 128 MB * per response; read requests which attempt to read individual rows larger - * than 100 MiB will fail. + * than 128 MB will fail. * * Each request also returns a set of stream statistics reflecting the current * state of the stream. @@ -793,7 +793,7 @@ export class BigQueryReadClient { this._gaxModule.routingHeader.fromParams({ read_stream: request.readStream ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('readRows stream %j', options); @@ -1078,7 +1078,7 @@ export class BigQueryReadClient { */ close(): Promise { if (this.bigQueryReadStub && !this._terminated) { - return this.bigQueryReadStub.then(stub => { + return this.bigQueryReadStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); diff --git a/handwritten/bigquery-storage/src/v1/big_query_write_client.ts b/handwritten/bigquery-storage/src/v1/big_query_write_client.ts index a8db6ca408b2..73c531a999c6 100644 --- a/handwritten/bigquery-storage/src/v1/big_query_write_client.ts +++ b/handwritten/bigquery-storage/src/v1/big_query_write_client.ts @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,10 +24,10 @@ import type { Descriptors, ClientOptions, } from 'google-gax'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -54,7 +54,7 @@ export class BigQueryWriteClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('bigquery-storage'); @@ -67,9 +67,9 @@ export class BigQueryWriteClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - bigQueryWriteStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + bigQueryWriteStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of BigQueryWriteClient. @@ -145,7 +145,7 @@ export class BigQueryWriteClient { const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -234,7 +234,7 @@ export class BigQueryWriteClient { 'google.cloud.bigquery.storage.v1.BigQueryWrite', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')}, + { 'x-goog-api-client': clientHeader.join(' ') }, ); // Set up a dictionary of "inner API calls"; the core implementation @@ -274,7 +274,7 @@ export class BigQueryWriteClient { (this._protos as any).google.cloud.bigquery.storage.v1.BigQueryWrite, this._opts, this._providedCustomServicePath, - ) as Promise<{[method: string]: Function}>; + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -288,11 +288,11 @@ export class BigQueryWriteClient { ]; for (const methodName of bigQueryWriteStubMethods) { const callPromise = this.bigQueryWriteStub.then( - stub => + (stub) => (...args: Array<{}>) => { if (this._terminated) { if (methodName in this.descriptors.stream) { - const stream = new PassThrough({objectMode: true}); + const stream = new PassThrough({ objectMode: true }); setImmediate(() => { stream.emit( 'error', @@ -516,7 +516,7 @@ export class BigQueryWriteClient { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('createWriteStream request %j', request); @@ -663,7 +663,7 @@ export class BigQueryWriteClient { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('getWriteStream request %j', request); @@ -808,7 +808,7 @@ export class BigQueryWriteClient { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('finalizeWriteStream request %j', request); @@ -959,7 +959,7 @@ export class BigQueryWriteClient { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('batchCommitWriteStreams request %j', request); @@ -1106,7 +1106,7 @@ export class BigQueryWriteClient { this._gaxModule.routingHeader.fromParams({ write_stream: request.writeStream ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('flushRows request %j', request); @@ -1199,7 +1199,7 @@ export class BigQueryWriteClient { * region_tag:bigquerystorage_v1_generated_BigQueryWrite_AppendRows_async */ appendRows(options?: CallOptions): gax.CancellableStream { - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('appendRows stream %j', options); @@ -1484,7 +1484,7 @@ export class BigQueryWriteClient { */ close(): Promise { if (this.bigQueryWriteStub && !this._terminated) { - return this.bigQueryWriteStub.then(stub => { + return this.bigQueryWriteStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); diff --git a/handwritten/bigquery-storage/src/v1/index.ts b/handwritten/bigquery-storage/src/v1/index.ts index 4ef2dcd26417..ad672e49aae6 100644 --- a/handwritten/bigquery-storage/src/v1/index.ts +++ b/handwritten/bigquery-storage/src/v1/index.ts @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,5 +16,5 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {BigQueryReadClient} from './big_query_read_client'; -export {BigQueryWriteClient} from './big_query_write_client'; +export { BigQueryReadClient } from './big_query_read_client'; +export { BigQueryWriteClient } from './big_query_write_client'; diff --git a/handwritten/bigquery-storage/src/v1alpha/index.ts b/handwritten/bigquery-storage/src/v1alpha/index.ts index c934f7b77877..df37f43c5abc 100644 --- a/handwritten/bigquery-storage/src/v1alpha/index.ts +++ b/handwritten/bigquery-storage/src/v1alpha/index.ts @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {MetastorePartitionServiceClient} from './metastore_partition_service_client'; +export { MetastorePartitionServiceClient } from './metastore_partition_service_client'; diff --git a/handwritten/bigquery-storage/src/v1alpha/metastore_partition_service_client.ts b/handwritten/bigquery-storage/src/v1alpha/metastore_partition_service_client.ts index ff3134f46498..852858717601 100644 --- a/handwritten/bigquery-storage/src/v1alpha/metastore_partition_service_client.ts +++ b/handwritten/bigquery-storage/src/v1alpha/metastore_partition_service_client.ts @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,10 +24,10 @@ import type { Descriptors, ClientOptions, } from 'google-gax'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -51,7 +51,7 @@ export class MetastorePartitionServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('storage'); @@ -64,9 +64,9 @@ export class MetastorePartitionServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - metastorePartitionServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + metastorePartitionServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of MetastorePartitionServiceClient. @@ -143,7 +143,7 @@ export class MetastorePartitionServiceClient { const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // Request numeric enum values if REST transport is used. opts.numericEnums = true; @@ -226,7 +226,7 @@ export class MetastorePartitionServiceClient { 'google.cloud.bigquery.storage.v1alpha.MetastorePartitionService', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')}, + { 'x-goog-api-client': clientHeader.join(' ') }, ); // Set up a dictionary of "inner API calls"; the core implementation @@ -267,7 +267,7 @@ export class MetastorePartitionServiceClient { .MetastorePartitionService, this._opts, this._providedCustomServicePath, - ) as Promise<{[method: string]: Function}>; + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -280,11 +280,11 @@ export class MetastorePartitionServiceClient { ]; for (const methodName of metastorePartitionServiceStubMethods) { const callPromise = this.metastorePartitionServiceStub.then( - stub => + (stub) => (...args: Array<{}>) => { if (this._terminated) { if (methodName in this.descriptors.stream) { - const stream = new PassThrough({objectMode: true}); + const stream = new PassThrough({ objectMode: true }); setImmediate(() => { stream.emit( 'error', @@ -515,7 +515,7 @@ export class MetastorePartitionServiceClient { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('batchCreateMetastorePartitions request %j', request); @@ -675,7 +675,7 @@ export class MetastorePartitionServiceClient { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('batchDeleteMetastorePartitions request %j', request); @@ -834,7 +834,7 @@ export class MetastorePartitionServiceClient { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('batchUpdateMetastorePartitions request %j', request); @@ -1002,7 +1002,7 @@ export class MetastorePartitionServiceClient { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('listMetastorePartitions request %j', request); @@ -1073,7 +1073,7 @@ export class MetastorePartitionServiceClient { * region_tag:bigquerystorage_v1alpha_generated_MetastorePartitionService_StreamMetastorePartitions_async */ streamMetastorePartitions(options?: CallOptions): gax.CancellableStream { - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('streamMetastorePartitions stream %j', options); @@ -1212,7 +1212,7 @@ export class MetastorePartitionServiceClient { */ close(): Promise { if (this.metastorePartitionServiceStub && !this._terminated) { - return this.metastorePartitionServiceStub.then(stub => { + return this.metastorePartitionServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); diff --git a/handwritten/bigquery-storage/src/v1beta/index.ts b/handwritten/bigquery-storage/src/v1beta/index.ts index c934f7b77877..df37f43c5abc 100644 --- a/handwritten/bigquery-storage/src/v1beta/index.ts +++ b/handwritten/bigquery-storage/src/v1beta/index.ts @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {MetastorePartitionServiceClient} from './metastore_partition_service_client'; +export { MetastorePartitionServiceClient } from './metastore_partition_service_client'; diff --git a/handwritten/bigquery-storage/src/v1beta/metastore_partition_service_client.ts b/handwritten/bigquery-storage/src/v1beta/metastore_partition_service_client.ts index 2f0a4eb9d290..cf2ddf5aafef 100644 --- a/handwritten/bigquery-storage/src/v1beta/metastore_partition_service_client.ts +++ b/handwritten/bigquery-storage/src/v1beta/metastore_partition_service_client.ts @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,10 +24,10 @@ import type { Descriptors, ClientOptions, } from 'google-gax'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -51,7 +51,7 @@ export class MetastorePartitionServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('storage'); @@ -64,9 +64,9 @@ export class MetastorePartitionServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - metastorePartitionServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + metastorePartitionServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of MetastorePartitionServiceClient. @@ -143,7 +143,7 @@ export class MetastorePartitionServiceClient { const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // Request numeric enum values if REST transport is used. opts.numericEnums = true; @@ -226,7 +226,7 @@ export class MetastorePartitionServiceClient { 'google.cloud.bigquery.storage.v1beta.MetastorePartitionService', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')}, + { 'x-goog-api-client': clientHeader.join(' ') }, ); // Set up a dictionary of "inner API calls"; the core implementation @@ -267,7 +267,7 @@ export class MetastorePartitionServiceClient { .MetastorePartitionService, this._opts, this._providedCustomServicePath, - ) as Promise<{[method: string]: Function}>; + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -280,11 +280,11 @@ export class MetastorePartitionServiceClient { ]; for (const methodName of metastorePartitionServiceStubMethods) { const callPromise = this.metastorePartitionServiceStub.then( - stub => + (stub) => (...args: Array<{}>) => { if (this._terminated) { if (methodName in this.descriptors.stream) { - const stream = new PassThrough({objectMode: true}); + const stream = new PassThrough({ objectMode: true }); setImmediate(() => { stream.emit( 'error', @@ -515,7 +515,7 @@ export class MetastorePartitionServiceClient { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('batchCreateMetastorePartitions request %j', request); @@ -675,7 +675,7 @@ export class MetastorePartitionServiceClient { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('batchDeleteMetastorePartitions request %j', request); @@ -834,7 +834,7 @@ export class MetastorePartitionServiceClient { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('batchUpdateMetastorePartitions request %j', request); @@ -1004,7 +1004,7 @@ export class MetastorePartitionServiceClient { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('listMetastorePartitions request %j', request); @@ -1075,7 +1075,7 @@ export class MetastorePartitionServiceClient { * region_tag:bigquerystorage_v1beta_generated_MetastorePartitionService_StreamMetastorePartitions_async */ streamMetastorePartitions(options?: CallOptions): gax.CancellableStream { - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('streamMetastorePartitions stream %j', options); @@ -1214,7 +1214,7 @@ export class MetastorePartitionServiceClient { */ close(): Promise { if (this.metastorePartitionServiceStub && !this._terminated) { - return this.metastorePartitionServiceStub.then(stub => { + return this.metastorePartitionServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); diff --git a/handwritten/bigquery-storage/src/v1beta1/big_query_storage_client.ts b/handwritten/bigquery-storage/src/v1beta1/big_query_storage_client.ts index 782d60859b07..2f2e4c86ef11 100644 --- a/handwritten/bigquery-storage/src/v1beta1/big_query_storage_client.ts +++ b/handwritten/bigquery-storage/src/v1beta1/big_query_storage_client.ts @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,10 +24,10 @@ import type { Descriptors, ClientOptions, } from 'google-gax'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -56,7 +56,7 @@ export class BigQueryStorageClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('bigquery-storage'); @@ -69,9 +69,9 @@ export class BigQueryStorageClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - bigQueryStorageStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + bigQueryStorageStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of BigQueryStorageClient. @@ -147,7 +147,7 @@ export class BigQueryStorageClient { const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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. if (servicePath !== this._servicePath && !('scopes' in opts)) { @@ -230,7 +230,7 @@ export class BigQueryStorageClient { 'google.cloud.bigquery.storage.v1beta1.BigQueryStorage', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')}, + { 'x-goog-api-client': clientHeader.join(' ') }, ); // Set up a dictionary of "inner API calls"; the core implementation @@ -271,7 +271,7 @@ export class BigQueryStorageClient { .BigQueryStorage, this._opts, this._providedCustomServicePath, - ) as Promise<{[method: string]: Function}>; + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -284,11 +284,11 @@ export class BigQueryStorageClient { ]; for (const methodName of bigQueryStorageStubMethods) { const callPromise = this.bigQueryStorageStub.then( - stub => + (stub) => (...args: Array<{}>) => { if (this._terminated) { if (methodName in this.descriptors.stream) { - const stream = new PassThrough({objectMode: true}); + const stream = new PassThrough({ objectMode: true }); setImmediate(() => { stream.emit( 'error', @@ -539,7 +539,7 @@ export class BigQueryStorageClient { 'table_reference.dataset_id': request.tableReference!.datasetId?.toString() ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('createReadSession request %j', request); @@ -689,7 +689,7 @@ export class BigQueryStorageClient { this._gaxModule.routingHeader.fromParams({ 'session.name': request.session!.name ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('batchCreateReadSessionStreams request %j', request); @@ -845,7 +845,7 @@ export class BigQueryStorageClient { this._gaxModule.routingHeader.fromParams({ 'stream.name': request.stream!.name ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('finalizeStream request %j', request); @@ -1008,7 +1008,7 @@ export class BigQueryStorageClient { this._gaxModule.routingHeader.fromParams({ 'original_stream.name': request.originalStream!.name ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('splitReadStream request %j', request); @@ -1097,7 +1097,7 @@ export class BigQueryStorageClient { this._gaxModule.routingHeader.fromParams({ 'read_position.stream.name': request.readPosition!.stream!.name ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('readRows stream %j', options); @@ -1240,7 +1240,7 @@ export class BigQueryStorageClient { */ close(): Promise { if (this.bigQueryStorageStub && !this._terminated) { - return this.bigQueryStorageStub.then(stub => { + return this.bigQueryStorageStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); diff --git a/handwritten/bigquery-storage/src/v1beta1/index.ts b/handwritten/bigquery-storage/src/v1beta1/index.ts index 157199d4f44d..9a6dba62856b 100644 --- a/handwritten/bigquery-storage/src/v1beta1/index.ts +++ b/handwritten/bigquery-storage/src/v1beta1/index.ts @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {BigQueryStorageClient} from './big_query_storage_client'; +export { BigQueryStorageClient } from './big_query_storage_client'; diff --git a/handwritten/bigquery-storage/src/v1beta2/big_query_read_client.ts b/handwritten/bigquery-storage/src/v1beta2/big_query_read_client.ts new file mode 100644 index 000000000000..bf07163430ca --- /dev/null +++ b/handwritten/bigquery-storage/src/v1beta2/big_query_read_client.ts @@ -0,0 +1,1082 @@ +// Copyright 2026 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 +// +// https://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 file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +/* global window */ +import type * as gax from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; +import { PassThrough } from 'stream'; +import * as protos from '../../protos/protos'; +import jsonProtos = require('../../protos/protos.json'); +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; + +/** + * Client JSON configuration object, loaded from + * `src/v1beta2/big_query_read_client_config.json`. + * This file defines retry strategy and timeouts for all API methods in this library. + */ +import * as gapicConfig from './big_query_read_client_config.json'; +const version = require('../../../package.json').version; + +/** + * BigQuery Read API. + * + * The Read API can be used to read data from BigQuery. + * + * New code should use the v1 Read API going forward, if they don't use Write + * API at the same time. + * @class + * @memberof v1beta2 + */ +export class BigQueryReadClient { + private _terminated = false; + private _opts: ClientOptions; + private _providedCustomServicePath: boolean; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: { [method: string]: gax.CallSettings }; + private _universeDomain: string; + private _servicePath: string; + private _log = logging.log('storage'); + + auth: gax.GoogleAuth; + descriptors: Descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + bigQueryReadStub?: Promise<{ [name: string]: Function }>; + + /** + * Construct an instance of BigQueryReadClient. + * + * @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/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * 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://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. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @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 BigQueryReadClient({fallback: true}, gax); + * ``` + */ + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { + // Ensure that options include all the required fields. + const staticMembers = this.constructor as typeof BigQueryReadClient; + 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'; + this._servicePath = 'bigquerystorage.' + this._universeDomain; + 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'); + 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. + if (servicePath !== this._servicePath && !('scopes' in opts)) { + opts['scopes'] = staticMembers.scopes; + } + + // Load google-gax module synchronously if needed + if (!gaxInstance) { + gaxInstance = require('google-gax') as typeof gax; + } + + // Choose either gRPC or proto-over-HTTP implementation of google-gax. + this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance; + + // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; + + // Save the auth object to the client, for use by other methods. + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; + + // Set useJWTAccessWithScope on the auth object. + this.auth.useJWTAccessWithScope = true; + + // Set defaultServicePath on the auth object. + this.auth.defaultServicePath = this._servicePath; + + // Set the default scopes in auth client if needed. + if (servicePath === this._servicePath) { + this.auth.defaultScopes = staticMembers.scopes; + } + + // Determine the client header string. + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; + if (typeof process === 'object' && 'versions' in process) { + clientHeader.push(`gl-node/${process.versions.node}`); + } else { + clientHeader.push(`gl-web/${this._gaxModule.version}`); + } + if (!opts.fallback) { + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); + } else { + clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); + } + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } + // Load the applicable protos. + this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); + + // This API contains "path templates"; forward-slash-separated + // identifiers to uniquely identify resources within the API. + // Create useful helper objects for these. + this.pathTemplates = { + projectPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}', + ), + readSessionPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/locations/{location}/sessions/{session}', + ), + readStreamPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/locations/{location}/sessions/{session}/streams/{stream}', + ), + tablePathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/datasets/{dataset}/tables/{table}', + ), + writeStreamPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}', + ), + }; + + // Some of the methods on this service provide streaming responses. + // Provide descriptors for these. + this.descriptors.stream = { + readRows: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + }; + + // Put together the default options sent with requests. + this._defaults = this._gaxGrpc.constructSettings( + 'google.cloud.bigquery.storage.v1beta2.BigQueryRead', + 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 + // merely providing the destination and request information. + this.innerApiCalls = {}; + + // Add a warn function to the client constructor so it can be easily tested. + this.warn = this._gaxModule.warn; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.bigQueryReadStub) { + return this.bigQueryReadStub; + } + + // Put together the "service stub" for + // google.cloud.bigquery.storage.v1beta2.BigQueryRead. + this.bigQueryReadStub = this._gaxGrpc.createStub( + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.bigquery.storage.v1beta2.BigQueryRead', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.cloud.bigquery.storage.v1beta2 + .BigQueryRead, + 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 bigQueryReadStubMethods = [ + 'createReadSession', + 'readRows', + 'splitReadStream', + ]; + for (const methodName of bigQueryReadStubMethods) { + const callPromise = this.bigQueryReadStub.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.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { + throw err; + }, + ); + + const descriptor = this.descriptors.stream[methodName] || undefined; + const apiCall = this._gaxModule.createApiCall( + callPromise, + this._defaults[methodName], + descriptor, + this._opts.fallback, + ); + + this.innerApiCalls[methodName] = apiCall; + } + + return this.bigQueryReadStub; + } + + /** + * 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() { + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); + } + return 'bigquerystorage.googleapis.com'; + } + + /** + * 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() { + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); + } + return 'bigquerystorage.googleapis.com'; + } + + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint() { + return this._servicePath; + } + + get universeDomain() { + return this._universeDomain; + } + + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port() { + return 443; + } + + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes() { + return [ + 'https://www.googleapis.com/auth/bigquery', + 'https://www.googleapis.com/auth/cloud-platform', + ]; + } + + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * 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 { + if (callback) { + this.auth.getProjectId(callback); + return; + } + return this.auth.getProjectId(); + } + + // ------------------- + // -- Service calls -- + // ------------------- + /** + * Creates a new read session. A read session divides the contents of a + * BigQuery table into one or more streams, which can then be used to read + * data from the table. The read session also specifies properties of the + * data to be read, such as a list of columns or a push-down filter describing + * the rows to be returned. + * + * A particular row can be read by at most one stream. When the caller has + * reached the end of each stream in the session, then all the data in the + * table has been read. + * + * Data is assigned to each stream such that roughly the same number of + * rows can be read from each stream. Because the server-side unit for + * assigning data is collections of rows, the API does not guarantee that + * each stream will return the same number or rows. Additionally, the + * limits are enforced based on the number of pre-filtered rows, so some + * filters can lead to lopsided assignments. + * + * Read sessions automatically expire 6 hours after they are created and do + * not require manual clean-up by the caller. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The request project that owns the session, in the form of + * `projects/{project_id}`. + * @param {google.cloud.bigquery.storage.v1beta2.ReadSession} request.readSession + * Required. Session to be created. + * @param {number} request.maxStreamCount + * Max initial number of streams. If unset or zero, the server will + * provide a value of streams so as to produce reasonable throughput. Must be + * non-negative. The number of streams may be lower than the requested number, + * depending on the amount parallelism that is reasonable for the table. Error + * will be returned if the max count is greater than the current system + * max limit of 1,000. + * + * Streams must be read starting from offset 0. + * @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.cloud.bigquery.storage.v1beta2.ReadSession|ReadSession}. + * 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/v1beta2/big_query_read.create_read_session.js + * region_tag:bigquerystorage_v1beta2_generated_BigQueryRead_CreateReadSession_async + */ + createReadSession( + request?: protos.google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta2.IReadSession, + ( + | protos.google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest + | undefined + ), + {} | undefined, + ] + >; + createReadSession( + request: protos.google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta2.IReadSession, + | protos.google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + createReadSession( + request: protos.google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta2.IReadSession, + | protos.google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + createReadSession( + request?: protos.google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.cloud.bigquery.storage.v1beta2.IReadSession, + | protos.google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.storage.v1beta2.IReadSession, + | protos.google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta2.IReadSession, + ( + | protos.google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest + | 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({ + 'read_session.table': request.readSession!.table ?? '', + }); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('createReadSession request %j', request); + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.storage.v1beta2.IReadSession, + | protos.google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createReadSession response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .createReadSession(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.storage.v1beta2.IReadSession, + ( + | protos.google.cloud.bigquery.storage.v1beta2.ICreateReadSessionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createReadSession response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Splits a given `ReadStream` into two `ReadStream` objects. These + * `ReadStream` objects are referred to as the primary and the residual + * streams of the split. The original `ReadStream` can still be read from in + * the same manner as before. Both of the returned `ReadStream` objects can + * also be read from, and the rows returned by both child streams will be + * the same as the rows read from the original stream. + * + * Moreover, the two child streams will be allocated back-to-back in the + * original `ReadStream`. Concretely, it is guaranteed that for streams + * original, primary, and residual, that original[0-j] = primary[0-j] and + * original[j-n] = residual[0-m] once the streams have been read to + * completion. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Name of the stream to split. + * @param {number} request.fraction + * A value in the range (0.0, 1.0) that specifies the fractional point at + * which the original stream should be split. The actual split point is + * evaluated on pre-filtered rows, so if a filter is provided, then there is + * no guarantee that the division of the rows between the new child streams + * will be proportional to this fractional value. Additionally, because the + * server-side unit for assigning data is collections of rows, this fraction + * will always map to a data storage boundary on the server side. + * @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.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse|SplitReadStreamResponse}. + * 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/v1beta2/big_query_read.split_read_stream.js + * region_tag:bigquerystorage_v1beta2_generated_BigQueryRead_SplitReadStream_async + */ + splitReadStream( + request?: protos.google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta2.ISplitReadStreamResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest + | undefined + ), + {} | undefined, + ] + >; + splitReadStream( + request: protos.google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta2.ISplitReadStreamResponse, + | protos.google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + splitReadStream( + request: protos.google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta2.ISplitReadStreamResponse, + | protos.google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + splitReadStream( + request?: protos.google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.cloud.bigquery.storage.v1beta2.ISplitReadStreamResponse, + | protos.google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.storage.v1beta2.ISplitReadStreamResponse, + | protos.google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta2.ISplitReadStreamResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest + | 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('splitReadStream request %j', request); + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.storage.v1beta2.ISplitReadStreamResponse, + | protos.google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('splitReadStream response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .splitReadStream(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.storage.v1beta2.ISplitReadStreamResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta2.ISplitReadStreamRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('splitReadStream response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + + /** + * Reads rows from the stream in the format prescribed by the ReadSession. + * Each response contains one or more table rows, up to a maximum of 100 MiB + * per response; read requests which attempt to read individual rows larger + * than 100 MiB will fail. + * + * Each request also returns a set of stream statistics reflecting the current + * state of the stream. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.readStream + * Required. Stream to read rows from. + * @param {number} request.offset + * The offset requested must be less than the last row read from Read. + * Requesting a larger offset is undefined. If not specified, start reading + * from offset zero. + * @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.cloud.bigquery.storage.v1beta2.ReadRowsResponse|ReadRowsResponse} 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/v1beta2/big_query_read.read_rows.js + * region_tag:bigquerystorage_v1beta2_generated_BigQueryRead_ReadRows_async + */ + readRows( + request?: protos.google.cloud.bigquery.storage.v1beta2.IReadRowsRequest, + 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({ + read_stream: request.readStream ?? '', + }); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('readRows stream %j', options); + return this.innerApiCalls.readRows(request, options); + } + + // -------------------- + // -- Path templates -- + // -------------------- + + /** + * Return a fully-qualified project resource name string. + * + * @param {string} project + * @returns {string} Resource name string. + */ + projectPath(project: string) { + return this.pathTemplates.projectPathTemplate.render({ + project: project, + }); + } + + /** + * Parse the project from Project resource. + * + * @param {string} projectName + * A fully-qualified path representing Project resource. + * @returns {string} A string representing the project. + */ + matchProjectFromProjectName(projectName: string) { + return this.pathTemplates.projectPathTemplate.match(projectName).project; + } + + /** + * Return a fully-qualified readSession resource name string. + * + * @param {string} project + * @param {string} location + * @param {string} session + * @returns {string} Resource name string. + */ + readSessionPath(project: string, location: string, session: string) { + return this.pathTemplates.readSessionPathTemplate.render({ + project: project, + location: location, + session: session, + }); + } + + /** + * Parse the project from ReadSession resource. + * + * @param {string} readSessionName + * A fully-qualified path representing ReadSession resource. + * @returns {string} A string representing the project. + */ + matchProjectFromReadSessionName(readSessionName: string) { + return this.pathTemplates.readSessionPathTemplate.match(readSessionName) + .project; + } + + /** + * Parse the location from ReadSession resource. + * + * @param {string} readSessionName + * A fully-qualified path representing ReadSession resource. + * @returns {string} A string representing the location. + */ + matchLocationFromReadSessionName(readSessionName: string) { + return this.pathTemplates.readSessionPathTemplate.match(readSessionName) + .location; + } + + /** + * Parse the session from ReadSession resource. + * + * @param {string} readSessionName + * A fully-qualified path representing ReadSession resource. + * @returns {string} A string representing the session. + */ + matchSessionFromReadSessionName(readSessionName: string) { + return this.pathTemplates.readSessionPathTemplate.match(readSessionName) + .session; + } + + /** + * Return a fully-qualified readStream resource name string. + * + * @param {string} project + * @param {string} location + * @param {string} session + * @param {string} stream + * @returns {string} Resource name string. + */ + readStreamPath( + project: string, + location: string, + session: string, + stream: string, + ) { + return this.pathTemplates.readStreamPathTemplate.render({ + project: project, + location: location, + session: session, + stream: stream, + }); + } + + /** + * Parse the project from ReadStream resource. + * + * @param {string} readStreamName + * A fully-qualified path representing ReadStream resource. + * @returns {string} A string representing the project. + */ + matchProjectFromReadStreamName(readStreamName: string) { + return this.pathTemplates.readStreamPathTemplate.match(readStreamName) + .project; + } + + /** + * Parse the location from ReadStream resource. + * + * @param {string} readStreamName + * A fully-qualified path representing ReadStream resource. + * @returns {string} A string representing the location. + */ + matchLocationFromReadStreamName(readStreamName: string) { + return this.pathTemplates.readStreamPathTemplate.match(readStreamName) + .location; + } + + /** + * Parse the session from ReadStream resource. + * + * @param {string} readStreamName + * A fully-qualified path representing ReadStream resource. + * @returns {string} A string representing the session. + */ + matchSessionFromReadStreamName(readStreamName: string) { + return this.pathTemplates.readStreamPathTemplate.match(readStreamName) + .session; + } + + /** + * Parse the stream from ReadStream resource. + * + * @param {string} readStreamName + * A fully-qualified path representing ReadStream resource. + * @returns {string} A string representing the stream. + */ + matchStreamFromReadStreamName(readStreamName: string) { + return this.pathTemplates.readStreamPathTemplate.match(readStreamName) + .stream; + } + + /** + * Return a fully-qualified table resource name string. + * + * @param {string} project + * @param {string} dataset + * @param {string} table + * @returns {string} Resource name string. + */ + tablePath(project: string, dataset: string, table: string) { + return this.pathTemplates.tablePathTemplate.render({ + project: project, + dataset: dataset, + table: table, + }); + } + + /** + * Parse the project from Table resource. + * + * @param {string} tableName + * A fully-qualified path representing Table resource. + * @returns {string} A string representing the project. + */ + matchProjectFromTableName(tableName: string) { + return this.pathTemplates.tablePathTemplate.match(tableName).project; + } + + /** + * Parse the dataset from Table resource. + * + * @param {string} tableName + * A fully-qualified path representing Table resource. + * @returns {string} A string representing the dataset. + */ + matchDatasetFromTableName(tableName: string) { + return this.pathTemplates.tablePathTemplate.match(tableName).dataset; + } + + /** + * Parse the table from Table resource. + * + * @param {string} tableName + * A fully-qualified path representing Table resource. + * @returns {string} A string representing the table. + */ + matchTableFromTableName(tableName: string) { + return this.pathTemplates.tablePathTemplate.match(tableName).table; + } + + /** + * Return a fully-qualified writeStream resource name string. + * + * @param {string} project + * @param {string} dataset + * @param {string} table + * @param {string} stream + * @returns {string} Resource name string. + */ + writeStreamPath( + project: string, + dataset: string, + table: string, + stream: string, + ) { + return this.pathTemplates.writeStreamPathTemplate.render({ + project: project, + dataset: dataset, + table: table, + stream: stream, + }); + } + + /** + * Parse the project from WriteStream resource. + * + * @param {string} writeStreamName + * A fully-qualified path representing WriteStream resource. + * @returns {string} A string representing the project. + */ + matchProjectFromWriteStreamName(writeStreamName: string) { + return this.pathTemplates.writeStreamPathTemplate.match(writeStreamName) + .project; + } + + /** + * Parse the dataset from WriteStream resource. + * + * @param {string} writeStreamName + * A fully-qualified path representing WriteStream resource. + * @returns {string} A string representing the dataset. + */ + matchDatasetFromWriteStreamName(writeStreamName: string) { + return this.pathTemplates.writeStreamPathTemplate.match(writeStreamName) + .dataset; + } + + /** + * Parse the table from WriteStream resource. + * + * @param {string} writeStreamName + * A fully-qualified path representing WriteStream resource. + * @returns {string} A string representing the table. + */ + matchTableFromWriteStreamName(writeStreamName: string) { + return this.pathTemplates.writeStreamPathTemplate.match(writeStreamName) + .table; + } + + /** + * Parse the stream from WriteStream resource. + * + * @param {string} writeStreamName + * A fully-qualified path representing WriteStream resource. + * @returns {string} A string representing the stream. + */ + matchStreamFromWriteStreamName(writeStreamName: string) { + return this.pathTemplates.writeStreamPathTemplate.match(writeStreamName) + .stream; + } + + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise { + if (this.bigQueryReadStub && !this._terminated) { + return this.bigQueryReadStub.then((stub) => { + this._log.info('ending gRPC channel'); + this._terminated = true; + stub.close(); + }); + } + return Promise.resolve(); + } +} diff --git a/handwritten/bigquery-storage/src/v1beta2/big_query_read_client_config.json b/handwritten/bigquery-storage/src/v1beta2/big_query_read_client_config.json new file mode 100644 index 000000000000..67155e9fa09e --- /dev/null +++ b/handwritten/bigquery-storage/src/v1beta2/big_query_read_client_config.json @@ -0,0 +1,44 @@ +{ + "interfaces": { + "google.cloud.bigquery.storage.v1beta2.BigQueryRead": { + "retry_codes": { + "non_idempotent": [], + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ], + "unavailable": [ + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "CreateReadSession": { + "timeout_millis": 600000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "ReadRows": { + "timeout_millis": 86400000, + "retry_codes_name": "unavailable", + "retry_params_name": "default" + }, + "SplitReadStream": { + "timeout_millis": 600000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/handwritten/bigquery-storage/src/v1beta2/big_query_read_proto_list.json b/handwritten/bigquery-storage/src/v1beta2/big_query_read_proto_list.json new file mode 100644 index 000000000000..3a0940a9eb76 --- /dev/null +++ b/handwritten/bigquery-storage/src/v1beta2/big_query_read_proto_list.json @@ -0,0 +1,8 @@ +[ + "../../protos/google/cloud/bigquery/storage/v1beta2/arrow.proto", + "../../protos/google/cloud/bigquery/storage/v1beta2/avro.proto", + "../../protos/google/cloud/bigquery/storage/v1beta2/protobuf.proto", + "../../protos/google/cloud/bigquery/storage/v1beta2/storage.proto", + "../../protos/google/cloud/bigquery/storage/v1beta2/stream.proto", + "../../protos/google/cloud/bigquery/storage/v1beta2/table.proto" +] diff --git a/handwritten/bigquery-storage/src/v1beta2/big_query_write_client.ts b/handwritten/bigquery-storage/src/v1beta2/big_query_write_client.ts new file mode 100644 index 000000000000..340810142f44 --- /dev/null +++ b/handwritten/bigquery-storage/src/v1beta2/big_query_write_client.ts @@ -0,0 +1,1536 @@ +// Copyright 2026 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 +// +// https://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 file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +/* global window */ +import type * as gax from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; +import { PassThrough } from 'stream'; +import * as protos from '../../protos/protos'; +import jsonProtos = require('../../protos/protos.json'); +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; + +/** + * Client JSON configuration object, loaded from + * `src/v1beta2/big_query_write_client_config.json`. + * This file defines retry strategy and timeouts for all API methods in this library. + */ +import * as gapicConfig from './big_query_write_client_config.json'; +const version = require('../../../package.json').version; + +/** + * BigQuery Write API. + * + * The Write API can be used to write data to BigQuery. + * + * + * The [google.cloud.bigquery.storage.v1 + * API](/bigquery/docs/reference/storage/rpc/google.cloud.bigquery.storage.v1) + * should be used instead of the v1beta2 API for BigQueryWrite operations. + * @class + * @memberof v1beta2 + * @deprecated BigQueryWrite is deprecated and may be removed in a future version. + */ +export class BigQueryWriteClient { + private _terminated = false; + private _opts: ClientOptions; + private _providedCustomServicePath: boolean; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: { [method: string]: gax.CallSettings }; + private _universeDomain: string; + private _servicePath: string; + private _log = logging.log('storage'); + + auth: gax.GoogleAuth; + descriptors: Descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + warn: (code: string, message: string, warnType?: string) => void; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + bigQueryWriteStub?: Promise<{ [name: string]: Function }>; + + /** + * Construct an instance of BigQueryWriteClient. + * + * @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/main/client-libraries.md#creating-the-client-instance). + * The common options are: + * @param {object} [options.credentials] - Credentials object. + * @param {string} [options.credentials.client_email] + * @param {string} [options.credentials.private_key] + * @param {string} [options.email] - Account email address. Required when + * using a .pem or .p12 keyFilename. + * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or + * .p12 key downloaded from the Google Developers Console. If you provide + * a path to a JSON file, the projectId option below is not necessary. + * NOTE: .pem and .p12 require you to specify options.email as well. + * @param {number} [options.port] - The port on which to connect to + * the remote host. + * @param {string} [options.projectId] - The project ID from the Google + * 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://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. + * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. + * Follows the structure of {@link gapicConfig}. + * @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 BigQueryWriteClient({fallback: true}, gax); + * ``` + */ + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback, + ) { + // Ensure that options include all the required fields. + const staticMembers = this.constructor as typeof BigQueryWriteClient; + 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'; + this._servicePath = 'bigquerystorage.' + this._universeDomain; + 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'); + 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. + if (servicePath !== this._servicePath && !('scopes' in opts)) { + opts['scopes'] = staticMembers.scopes; + } + + // Load google-gax module synchronously if needed + if (!gaxInstance) { + gaxInstance = require('google-gax') as typeof gax; + } + + // Choose either gRPC or proto-over-HTTP implementation of google-gax. + this._gaxModule = opts.fallback ? gaxInstance.fallback : gaxInstance; + + // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; + + // Save the auth object to the client, for use by other methods. + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; + + // Set useJWTAccessWithScope on the auth object. + this.auth.useJWTAccessWithScope = true; + + // Set defaultServicePath on the auth object. + this.auth.defaultServicePath = this._servicePath; + + // Set the default scopes in auth client if needed. + if (servicePath === this._servicePath) { + this.auth.defaultScopes = staticMembers.scopes; + } + + // Determine the client header string. + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; + if (typeof process === 'object' && 'versions' in process) { + clientHeader.push(`gl-node/${process.versions.node}`); + } else { + clientHeader.push(`gl-web/${this._gaxModule.version}`); + } + if (!opts.fallback) { + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); + } else { + clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); + } + if (opts.libName && opts.libVersion) { + clientHeader.push(`${opts.libName}/${opts.libVersion}`); + } + // Load the applicable protos. + this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); + + // This API contains "path templates"; forward-slash-separated + // identifiers to uniquely identify resources within the API. + // Create useful helper objects for these. + this.pathTemplates = { + projectPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}', + ), + readSessionPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/locations/{location}/sessions/{session}', + ), + readStreamPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/locations/{location}/sessions/{session}/streams/{stream}', + ), + tablePathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/datasets/{dataset}/tables/{table}', + ), + writeStreamPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}', + ), + }; + + // Some of the methods on this service provide streaming responses. + // Provide descriptors for these. + this.descriptors.stream = { + appendRows: 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.cloud.bigquery.storage.v1beta2.BigQueryWrite', + 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 + // merely providing the destination and request information. + this.innerApiCalls = {}; + + // Add a warn function to the client constructor so it can be easily tested. + this.warn = this._gaxModule.warn; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.bigQueryWriteStub) { + this.warn( + 'DEP$BigQueryWrite', + 'BigQueryWrite is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); + return this.bigQueryWriteStub; + } + + // Put together the "service stub" for + // google.cloud.bigquery.storage.v1beta2.BigQueryWrite. + this.bigQueryWriteStub = this._gaxGrpc.createStub( + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.cloud.bigquery.storage.v1beta2.BigQueryWrite', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.cloud.bigquery.storage.v1beta2 + .BigQueryWrite, + 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 bigQueryWriteStubMethods = [ + 'createWriteStream', + 'appendRows', + 'getWriteStream', + 'finalizeWriteStream', + 'batchCommitWriteStreams', + 'flushRows', + ]; + for (const methodName of bigQueryWriteStubMethods) { + const callPromise = this.bigQueryWriteStub.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.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { + throw err; + }, + ); + + const descriptor = this.descriptors.stream[methodName] || undefined; + const apiCall = this._gaxModule.createApiCall( + callPromise, + this._defaults[methodName], + descriptor, + this._opts.fallback, + ); + + this.innerApiCalls[methodName] = apiCall; + } + this.warn( + 'DEP$BigQueryWrite', + 'BigQueryWrite is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); + + return this.bigQueryWriteStub; + } + + /** + * 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() { + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); + } + return 'bigquerystorage.googleapis.com'; + } + + /** + * 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() { + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning', + ); + } + return 'bigquerystorage.googleapis.com'; + } + + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint() { + return this._servicePath; + } + + get universeDomain() { + return this._universeDomain; + } + + /** + * The port for this API service. + * @returns {number} The default port for this service. + */ + static get port() { + return 443; + } + + /** + * The scopes needed to make gRPC calls for every method defined + * in this service. + * @returns {string[]} List of default scopes. + */ + static get scopes() { + return [ + 'https://www.googleapis.com/auth/bigquery', + 'https://www.googleapis.com/auth/bigquery.insertdata', + 'https://www.googleapis.com/auth/cloud-platform', + ]; + } + + getProjectId(): Promise; + getProjectId(callback: Callback): void; + /** + * 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 { + if (callback) { + this.auth.getProjectId(callback); + return; + } + return this.auth.getProjectId(); + } + + // ------------------- + // -- Service calls -- + // ------------------- + /** + * Creates a write stream to the given table. + * Additionally, every table has a special COMMITTED stream named '_default' + * to which data can be written. This stream doesn't need to be created using + * CreateWriteStream. It is a stream that can be used simultaneously by any + * number of clients. Data written to this stream is considered committed as + * soon as an acknowledgement is received. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Reference to the table to which the stream belongs, in the format + * of `projects/{project}/datasets/{dataset}/tables/{table}`. + * @param {google.cloud.bigquery.storage.v1beta2.WriteStream} request.writeStream + * Required. Stream to be created. + * @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.cloud.bigquery.storage.v1beta2.WriteStream|WriteStream}. + * 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/v1beta2/big_query_write.create_write_stream.js + * region_tag:bigquerystorage_v1beta2_generated_BigQueryWrite_CreateWriteStream_async + * @deprecated CreateWriteStream is deprecated and may be removed in a future version. + */ + createWriteStream( + request?: protos.google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta2.IWriteStream, + ( + | protos.google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest + | undefined + ), + {} | undefined, + ] + >; + createWriteStream( + request: protos.google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta2.IWriteStream, + | protos.google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + createWriteStream( + request: protos.google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta2.IWriteStream, + | protos.google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + createWriteStream( + request?: protos.google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.cloud.bigquery.storage.v1beta2.IWriteStream, + | protos.google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.storage.v1beta2.IWriteStream, + | protos.google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta2.IWriteStream, + ( + | protos.google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest + | 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.warn( + 'DEP$BigQueryWrite-$CreateWriteStream', + 'CreateWriteStream is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); + this._log.info('createWriteStream request %j', request); + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.storage.v1beta2.IWriteStream, + | protos.google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createWriteStream response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .createWriteStream(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.storage.v1beta2.IWriteStream, + ( + | protos.google.cloud.bigquery.storage.v1beta2.ICreateWriteStreamRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createWriteStream response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Gets a write stream. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Name of the stream to get, in the form of + * `projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}`. + * @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.cloud.bigquery.storage.v1beta2.WriteStream|WriteStream}. + * 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/v1beta2/big_query_write.get_write_stream.js + * region_tag:bigquerystorage_v1beta2_generated_BigQueryWrite_GetWriteStream_async + * @deprecated GetWriteStream is deprecated and may be removed in a future version. + */ + getWriteStream( + request?: protos.google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta2.IWriteStream, + ( + | protos.google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest + | undefined + ), + {} | undefined, + ] + >; + getWriteStream( + request: protos.google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta2.IWriteStream, + | protos.google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + getWriteStream( + request: protos.google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta2.IWriteStream, + | protos.google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + getWriteStream( + request?: protos.google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.cloud.bigquery.storage.v1beta2.IWriteStream, + | protos.google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.storage.v1beta2.IWriteStream, + | protos.google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta2.IWriteStream, + ( + | protos.google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest + | 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.warn( + 'DEP$BigQueryWrite-$GetWriteStream', + 'GetWriteStream is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); + this._log.info('getWriteStream request %j', request); + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.storage.v1beta2.IWriteStream, + | protos.google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getWriteStream response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getWriteStream(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.storage.v1beta2.IWriteStream, + ( + | protos.google.cloud.bigquery.storage.v1beta2.IGetWriteStreamRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getWriteStream response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Finalize a write stream so that no new data can be appended to the + * stream. Finalize is not supported on the '_default' stream. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Name of the stream to finalize, in the form of + * `projects/{project}/datasets/{dataset}/tables/{table}/streams/{stream}`. + * @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.cloud.bigquery.storage.v1beta2.FinalizeWriteStreamResponse|FinalizeWriteStreamResponse}. + * 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/v1beta2/big_query_write.finalize_write_stream.js + * region_tag:bigquerystorage_v1beta2_generated_BigQueryWrite_FinalizeWriteStream_async + * @deprecated FinalizeWriteStream is deprecated and may be removed in a future version. + */ + finalizeWriteStream( + request?: protos.google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest + | undefined + ), + {} | undefined, + ] + >; + finalizeWriteStream( + request: protos.google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamResponse, + | protos.google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + finalizeWriteStream( + request: protos.google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamResponse, + | protos.google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + finalizeWriteStream( + request?: protos.google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamResponse, + | protos.google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamResponse, + | protos.google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest + | 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.warn( + 'DEP$BigQueryWrite-$FinalizeWriteStream', + 'FinalizeWriteStream is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); + this._log.info('finalizeWriteStream request %j', request); + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamResponse, + | protos.google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('finalizeWriteStream response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .finalizeWriteStream(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta2.IFinalizeWriteStreamRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('finalizeWriteStream response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Atomically commits a group of `PENDING` streams that belong to the same + * `parent` table. + * Streams must be finalized before commit and cannot be committed multiple + * times. Once a stream is committed, data in the stream becomes available + * for read operations. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Parent table that all the streams should belong to, in the form + * of `projects/{project}/datasets/{dataset}/tables/{table}`. + * @param {string[]} request.writeStreams + * Required. The group of streams that will be committed atomically. + * @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.cloud.bigquery.storage.v1beta2.BatchCommitWriteStreamsResponse|BatchCommitWriteStreamsResponse}. + * 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/v1beta2/big_query_write.batch_commit_write_streams.js + * region_tag:bigquerystorage_v1beta2_generated_BigQueryWrite_BatchCommitWriteStreams_async + * @deprecated BatchCommitWriteStreams is deprecated and may be removed in a future version. + */ + batchCommitWriteStreams( + request?: protos.google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest + | undefined + ), + {} | undefined, + ] + >; + batchCommitWriteStreams( + request: protos.google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsResponse, + | protos.google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + batchCommitWriteStreams( + request: protos.google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsResponse, + | protos.google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + batchCommitWriteStreams( + request?: protos.google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsResponse, + | protos.google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsResponse, + | protos.google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest + | 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.warn( + 'DEP$BigQueryWrite-$BatchCommitWriteStreams', + 'BatchCommitWriteStreams is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); + this._log.info('batchCommitWriteStreams request %j', request); + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsResponse, + | protos.google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('batchCommitWriteStreams response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .batchCommitWriteStreams(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta2.IBatchCommitWriteStreamsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchCommitWriteStreams response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + /** + * Flushes rows to a BUFFERED stream. + * If users are appending rows to BUFFERED stream, flush operation is + * required in order for the rows to become available for reading. A + * Flush operation flushes up to any previously flushed offset in a BUFFERED + * stream, to the offset specified in the request. + * Flush is not supported on the _default stream, since it is not BUFFERED. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.writeStream + * Required. The stream that is the target of the flush operation. + * @param {google.protobuf.Int64Value} request.offset + * Ending offset of the flush operation. Rows before this offset(including + * this offset) will be flushed. + * @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.cloud.bigquery.storage.v1beta2.FlushRowsResponse|FlushRowsResponse}. + * 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/v1beta2/big_query_write.flush_rows.js + * region_tag:bigquerystorage_v1beta2_generated_BigQueryWrite_FlushRows_async + * @deprecated FlushRows is deprecated and may be removed in a future version. + */ + flushRows( + request?: protos.google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta2.IFlushRowsResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest + | undefined + ), + {} | undefined, + ] + >; + flushRows( + request: protos.google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest, + options: CallOptions, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta2.IFlushRowsResponse, + | protos.google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + flushRows( + request: protos.google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest, + callback: Callback< + protos.google.cloud.bigquery.storage.v1beta2.IFlushRowsResponse, + | protos.google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + flushRows( + request?: protos.google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + protos.google.cloud.bigquery.storage.v1beta2.IFlushRowsResponse, + | protos.google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.cloud.bigquery.storage.v1beta2.IFlushRowsResponse, + | protos.google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.cloud.bigquery.storage.v1beta2.IFlushRowsResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest + | 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({ + write_stream: request.writeStream ?? '', + }); + this.initialize().catch((err) => { + throw err; + }); + this.warn( + 'DEP$BigQueryWrite-$FlushRows', + 'FlushRows is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); + this._log.info('flushRows request %j', request); + const wrappedCallback: + | Callback< + protos.google.cloud.bigquery.storage.v1beta2.IFlushRowsResponse, + | protos.google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('flushRows response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .flushRows(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.cloud.bigquery.storage.v1beta2.IFlushRowsResponse, + ( + | protos.google.cloud.bigquery.storage.v1beta2.IFlushRowsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('flushRows response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); + } + + /** + * Appends data to the given stream. + * + * If `offset` is specified, the `offset` is checked against the end of + * stream. The server returns `OUT_OF_RANGE` in `AppendRowsResponse` if an + * attempt is made to append to an offset beyond the current end of the stream + * or `ALREADY_EXISTS` if user provids an `offset` that has already been + * written to. User can retry with adjusted offset within the same RPC + * stream. If `offset` is not specified, append happens at the end of the + * stream. + * + * The response contains the offset at which the append happened. Responses + * are received in the same order in which requests are sent. There will be + * one response for each successful request. If the `offset` is not set in + * response, it means append didn't happen due to some errors. If one request + * fails, all the subsequent requests will also fail until a success request + * is made again. + * + * If the stream is of `PENDING` type, data will only be available for read + * operations after the stream is committed. + * + * @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.cloud.bigquery.storage.v1beta2.AppendRowsRequest|AppendRowsRequest} for write() method, and + * will emit objects representing {@link protos.google.cloud.bigquery.storage.v1beta2.AppendRowsResponse|AppendRowsResponse} 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/v1beta2/big_query_write.append_rows.js + * region_tag:bigquerystorage_v1beta2_generated_BigQueryWrite_AppendRows_async + * @deprecated AppendRows is deprecated and may be removed in a future version. + */ + appendRows(options?: CallOptions): gax.CancellableStream { + this.initialize().catch((err) => { + throw err; + }); + this.warn( + 'DEP$BigQueryWrite-$AppendRows', + 'AppendRows is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); + this._log.info('appendRows stream %j', options); + return this.innerApiCalls.appendRows(null, options); + } + + // -------------------- + // -- Path templates -- + // -------------------- + + /** + * Return a fully-qualified project resource name string. + * + * @param {string} project + * @returns {string} Resource name string. + */ + projectPath(project: string) { + return this.pathTemplates.projectPathTemplate.render({ + project: project, + }); + } + + /** + * Parse the project from Project resource. + * + * @param {string} projectName + * A fully-qualified path representing Project resource. + * @returns {string} A string representing the project. + */ + matchProjectFromProjectName(projectName: string) { + return this.pathTemplates.projectPathTemplate.match(projectName).project; + } + + /** + * Return a fully-qualified readSession resource name string. + * + * @param {string} project + * @param {string} location + * @param {string} session + * @returns {string} Resource name string. + */ + readSessionPath(project: string, location: string, session: string) { + return this.pathTemplates.readSessionPathTemplate.render({ + project: project, + location: location, + session: session, + }); + } + + /** + * Parse the project from ReadSession resource. + * + * @param {string} readSessionName + * A fully-qualified path representing ReadSession resource. + * @returns {string} A string representing the project. + */ + matchProjectFromReadSessionName(readSessionName: string) { + return this.pathTemplates.readSessionPathTemplate.match(readSessionName) + .project; + } + + /** + * Parse the location from ReadSession resource. + * + * @param {string} readSessionName + * A fully-qualified path representing ReadSession resource. + * @returns {string} A string representing the location. + */ + matchLocationFromReadSessionName(readSessionName: string) { + return this.pathTemplates.readSessionPathTemplate.match(readSessionName) + .location; + } + + /** + * Parse the session from ReadSession resource. + * + * @param {string} readSessionName + * A fully-qualified path representing ReadSession resource. + * @returns {string} A string representing the session. + */ + matchSessionFromReadSessionName(readSessionName: string) { + return this.pathTemplates.readSessionPathTemplate.match(readSessionName) + .session; + } + + /** + * Return a fully-qualified readStream resource name string. + * + * @param {string} project + * @param {string} location + * @param {string} session + * @param {string} stream + * @returns {string} Resource name string. + */ + readStreamPath( + project: string, + location: string, + session: string, + stream: string, + ) { + return this.pathTemplates.readStreamPathTemplate.render({ + project: project, + location: location, + session: session, + stream: stream, + }); + } + + /** + * Parse the project from ReadStream resource. + * + * @param {string} readStreamName + * A fully-qualified path representing ReadStream resource. + * @returns {string} A string representing the project. + */ + matchProjectFromReadStreamName(readStreamName: string) { + return this.pathTemplates.readStreamPathTemplate.match(readStreamName) + .project; + } + + /** + * Parse the location from ReadStream resource. + * + * @param {string} readStreamName + * A fully-qualified path representing ReadStream resource. + * @returns {string} A string representing the location. + */ + matchLocationFromReadStreamName(readStreamName: string) { + return this.pathTemplates.readStreamPathTemplate.match(readStreamName) + .location; + } + + /** + * Parse the session from ReadStream resource. + * + * @param {string} readStreamName + * A fully-qualified path representing ReadStream resource. + * @returns {string} A string representing the session. + */ + matchSessionFromReadStreamName(readStreamName: string) { + return this.pathTemplates.readStreamPathTemplate.match(readStreamName) + .session; + } + + /** + * Parse the stream from ReadStream resource. + * + * @param {string} readStreamName + * A fully-qualified path representing ReadStream resource. + * @returns {string} A string representing the stream. + */ + matchStreamFromReadStreamName(readStreamName: string) { + return this.pathTemplates.readStreamPathTemplate.match(readStreamName) + .stream; + } + + /** + * Return a fully-qualified table resource name string. + * + * @param {string} project + * @param {string} dataset + * @param {string} table + * @returns {string} Resource name string. + */ + tablePath(project: string, dataset: string, table: string) { + return this.pathTemplates.tablePathTemplate.render({ + project: project, + dataset: dataset, + table: table, + }); + } + + /** + * Parse the project from Table resource. + * + * @param {string} tableName + * A fully-qualified path representing Table resource. + * @returns {string} A string representing the project. + */ + matchProjectFromTableName(tableName: string) { + return this.pathTemplates.tablePathTemplate.match(tableName).project; + } + + /** + * Parse the dataset from Table resource. + * + * @param {string} tableName + * A fully-qualified path representing Table resource. + * @returns {string} A string representing the dataset. + */ + matchDatasetFromTableName(tableName: string) { + return this.pathTemplates.tablePathTemplate.match(tableName).dataset; + } + + /** + * Parse the table from Table resource. + * + * @param {string} tableName + * A fully-qualified path representing Table resource. + * @returns {string} A string representing the table. + */ + matchTableFromTableName(tableName: string) { + return this.pathTemplates.tablePathTemplate.match(tableName).table; + } + + /** + * Return a fully-qualified writeStream resource name string. + * + * @param {string} project + * @param {string} dataset + * @param {string} table + * @param {string} stream + * @returns {string} Resource name string. + */ + writeStreamPath( + project: string, + dataset: string, + table: string, + stream: string, + ) { + return this.pathTemplates.writeStreamPathTemplate.render({ + project: project, + dataset: dataset, + table: table, + stream: stream, + }); + } + + /** + * Parse the project from WriteStream resource. + * + * @param {string} writeStreamName + * A fully-qualified path representing WriteStream resource. + * @returns {string} A string representing the project. + */ + matchProjectFromWriteStreamName(writeStreamName: string) { + return this.pathTemplates.writeStreamPathTemplate.match(writeStreamName) + .project; + } + + /** + * Parse the dataset from WriteStream resource. + * + * @param {string} writeStreamName + * A fully-qualified path representing WriteStream resource. + * @returns {string} A string representing the dataset. + */ + matchDatasetFromWriteStreamName(writeStreamName: string) { + return this.pathTemplates.writeStreamPathTemplate.match(writeStreamName) + .dataset; + } + + /** + * Parse the table from WriteStream resource. + * + * @param {string} writeStreamName + * A fully-qualified path representing WriteStream resource. + * @returns {string} A string representing the table. + */ + matchTableFromWriteStreamName(writeStreamName: string) { + return this.pathTemplates.writeStreamPathTemplate.match(writeStreamName) + .table; + } + + /** + * Parse the stream from WriteStream resource. + * + * @param {string} writeStreamName + * A fully-qualified path representing WriteStream resource. + * @returns {string} A string representing the stream. + */ + matchStreamFromWriteStreamName(writeStreamName: string) { + return this.pathTemplates.writeStreamPathTemplate.match(writeStreamName) + .stream; + } + + /** + * Terminate the gRPC channel and close the client. + * + * The client will no longer be usable and all future behavior is undefined. + * @returns {Promise} A promise that resolves when the client is closed. + */ + close(): Promise { + if (this.bigQueryWriteStub && !this._terminated) { + return this.bigQueryWriteStub.then((stub) => { + this._log.info('ending gRPC channel'); + this._terminated = true; + stub.close(); + }); + } + return Promise.resolve(); + } +} diff --git a/handwritten/bigquery-storage/src/v1beta2/big_query_write_client_config.json b/handwritten/bigquery-storage/src/v1beta2/big_query_write_client_config.json new file mode 100644 index 000000000000..7f28169e4cf1 --- /dev/null +++ b/handwritten/bigquery-storage/src/v1beta2/big_query_write_client_config.json @@ -0,0 +1,65 @@ +{ + "interfaces": { + "google.cloud.bigquery.storage.v1beta2.BigQueryWrite": { + "retry_codes": { + "non_idempotent": [], + "idempotent": [ + "DEADLINE_EXCEEDED", + "UNAVAILABLE" + ], + "deadline_exceeded_resource_exhausted_unavailable": [ + "DEADLINE_EXCEEDED", + "RESOURCE_EXHAUSTED", + "UNAVAILABLE" + ], + "resource_exhausted_unavailable": [ + "RESOURCE_EXHAUSTED", + "UNAVAILABLE" + ] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "CreateWriteStream": { + "timeout_millis": 600000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_unavailable", + "retry_params_name": "default" + }, + "AppendRows": { + "timeout_millis": 86400000, + "retry_codes_name": "resource_exhausted_unavailable", + "retry_params_name": "default" + }, + "GetWriteStream": { + "timeout_millis": 600000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "FinalizeWriteStream": { + "timeout_millis": 600000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "BatchCommitWriteStreams": { + "timeout_millis": 600000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "FlushRows": { + "timeout_millis": 600000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/handwritten/bigquery-storage/src/v1beta2/big_query_write_proto_list.json b/handwritten/bigquery-storage/src/v1beta2/big_query_write_proto_list.json new file mode 100644 index 000000000000..3a0940a9eb76 --- /dev/null +++ b/handwritten/bigquery-storage/src/v1beta2/big_query_write_proto_list.json @@ -0,0 +1,8 @@ +[ + "../../protos/google/cloud/bigquery/storage/v1beta2/arrow.proto", + "../../protos/google/cloud/bigquery/storage/v1beta2/avro.proto", + "../../protos/google/cloud/bigquery/storage/v1beta2/protobuf.proto", + "../../protos/google/cloud/bigquery/storage/v1beta2/storage.proto", + "../../protos/google/cloud/bigquery/storage/v1beta2/stream.proto", + "../../protos/google/cloud/bigquery/storage/v1beta2/table.proto" +] diff --git a/handwritten/bigquery-storage/src/v1beta2/gapic_metadata.json b/handwritten/bigquery-storage/src/v1beta2/gapic_metadata.json new file mode 100644 index 000000000000..d360825be2d2 --- /dev/null +++ b/handwritten/bigquery-storage/src/v1beta2/gapic_metadata.json @@ -0,0 +1,117 @@ +{ + "schema": "1.0", + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "typescript", + "protoPackage": "google.cloud.bigquery.storage.v1beta2", + "libraryPackage": "storage", + "services": { + "BigQueryRead": { + "clients": { + "grpc": { + "libraryClient": "BigQueryReadClient", + "rpcs": { + "CreateReadSession": { + "methods": [ + "createReadSession" + ] + }, + "SplitReadStream": { + "methods": [ + "splitReadStream" + ] + }, + "ReadRows": { + "methods": [ + "readRows" + ] + } + } + }, + "grpc-fallback": { + "libraryClient": "BigQueryReadClient", + "rpcs": { + "CreateReadSession": { + "methods": [ + "createReadSession" + ] + }, + "SplitReadStream": { + "methods": [ + "splitReadStream" + ] + } + } + } + } + }, + "BigQueryWrite": { + "clients": { + "grpc": { + "libraryClient": "BigQueryWriteClient", + "rpcs": { + "CreateWriteStream": { + "methods": [ + "createWriteStream" + ] + }, + "GetWriteStream": { + "methods": [ + "getWriteStream" + ] + }, + "FinalizeWriteStream": { + "methods": [ + "finalizeWriteStream" + ] + }, + "BatchCommitWriteStreams": { + "methods": [ + "batchCommitWriteStreams" + ] + }, + "FlushRows": { + "methods": [ + "flushRows" + ] + }, + "AppendRows": { + "methods": [ + "appendRows" + ] + } + } + }, + "grpc-fallback": { + "libraryClient": "BigQueryWriteClient", + "rpcs": { + "CreateWriteStream": { + "methods": [ + "createWriteStream" + ] + }, + "GetWriteStream": { + "methods": [ + "getWriteStream" + ] + }, + "FinalizeWriteStream": { + "methods": [ + "finalizeWriteStream" + ] + }, + "BatchCommitWriteStreams": { + "methods": [ + "batchCommitWriteStreams" + ] + }, + "FlushRows": { + "methods": [ + "flushRows" + ] + } + } + } + } + } + } +} diff --git a/handwritten/bigquery-storage/src/v1beta2/index.ts b/handwritten/bigquery-storage/src/v1beta2/index.ts new file mode 100644 index 000000000000..ad672e49aae6 --- /dev/null +++ b/handwritten/bigquery-storage/src/v1beta2/index.ts @@ -0,0 +1,20 @@ +// Copyright 2026 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 +// +// https://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 file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +export { BigQueryReadClient } from './big_query_read_client'; +export { BigQueryWriteClient } from './big_query_write_client'; diff --git a/handwritten/bigquery-storage/system-test/fixtures/sample/src/index.js b/handwritten/bigquery-storage/system-test/fixtures/sample/src/index.js index 4d1e990cb8dc..bf392b491d64 100644 --- a/handwritten/bigquery-storage/system-test/fixtures/sample/src/index.js +++ b/handwritten/bigquery-storage/system-test/fixtures/sample/src/index.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + /* eslint-disable node/no-missing-require, no-unused-vars */ const storage = require('@google-cloud/bigquery-storage'); diff --git a/handwritten/bigquery-storage/system-test/fixtures/sample/src/index.ts b/handwritten/bigquery-storage/system-test/fixtures/sample/src/index.ts index 3c3da47e6951..2f82355fef41 100644 --- a/handwritten/bigquery-storage/system-test/fixtures/sample/src/index.ts +++ b/handwritten/bigquery-storage/system-test/fixtures/sample/src/index.ts @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,7 +16,10 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {BigQueryReadClient, BigQueryWriteClient} from '@google-cloud/bigquery-storage'; +import { + BigQueryReadClient, + BigQueryWriteClient, +} from '@google-cloud/bigquery-storage'; // check that the client class type name can be used function doStuffWithBigQueryReadClient(client: BigQueryReadClient) { diff --git a/handwritten/bigquery-storage/system-test/install.ts b/handwritten/bigquery-storage/system-test/install.ts index 5257a7ba101c..ccf167042d2e 100644 --- a/handwritten/bigquery-storage/system-test/install.ts +++ b/handwritten/bigquery-storage/system-test/install.ts @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,9 +16,9 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { it('TypeScript code', async function () { @@ -41,7 +41,7 @@ describe('📦 pack-n-play test', () => { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - ts: readFileSync( + cjs: readFileSync( './system-test/fixtures/sample/src/index.js', ).toString(), }, diff --git a/handwritten/bigquery-storage/test/gapic_big_query_read_v1.ts b/handwritten/bigquery-storage/test/gapic_big_query_read_v1.ts index 0672ab7ec6f4..e0a3162347a1 100644 --- a/handwritten/bigquery-storage/test/gapic_big_query_read_v1.ts +++ b/handwritten/bigquery-storage/test/gapic_big_query_read_v1.ts @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,13 +19,13 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as bigqueryreadModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects @@ -45,7 +45,7 @@ function getTypeDefaultValue(typeName: string, fields: string[]) { function generateSampleMessage(instance: T) { const filledObject = ( instance.constructor as typeof protobuf.Message - ).toObject(instance as protobuf.Message, {defaults: true}); + ).toObject(instance as protobuf.Message, { defaults: true }); return (instance.constructor as typeof protobuf.Message).fromObject( filledObject, ) as T; @@ -202,7 +202,7 @@ describe('v1.BigQueryReadClient', () => { it('has initialize method and supports deferred initialization', async () => { const client = new bigqueryreadModule.v1.BigQueryReadClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); assert.strictEqual(client.bigQueryReadStub, undefined); @@ -210,12 +210,12 @@ describe('v1.BigQueryReadClient', () => { assert(client.bigQueryReadStub); }); - it('has close method for the initialized client', done => { + it('has close method for the initialized client', (done) => { const client = new bigqueryreadModule.v1.BigQueryReadClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize().catch(err => { + client.initialize().catch((err) => { throw err; }); assert(client.bigQueryReadStub); @@ -224,14 +224,14 @@ describe('v1.BigQueryReadClient', () => { .then(() => { done(); }) - .catch(err => { + .catch((err) => { throw err; }); }); - it('has close method for the non-initialized client', done => { + it('has close method for the non-initialized client', (done) => { const client = new bigqueryreadModule.v1.BigQueryReadClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); assert.strictEqual(client.bigQueryReadStub, undefined); @@ -240,7 +240,7 @@ describe('v1.BigQueryReadClient', () => { .then(() => { done(); }) - .catch(err => { + .catch((err) => { throw err; }); }); @@ -248,7 +248,7 @@ describe('v1.BigQueryReadClient', () => { it('has getProjectId method', async () => { const fakeProjectId = 'fake-project-id'; const client = new bigqueryreadModule.v1.BigQueryReadClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); @@ -260,7 +260,7 @@ describe('v1.BigQueryReadClient', () => { it('has getProjectId method with callback', async () => { const fakeProjectId = 'fake-project-id'; const client = new bigqueryreadModule.v1.BigQueryReadClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); client.auth.getProjectId = sinon @@ -283,7 +283,7 @@ describe('v1.BigQueryReadClient', () => { describe('createReadSession', () => { it('invokes createReadSession without error', async () => { const client = new bigqueryreadModule.v1.BigQueryReadClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -315,7 +315,7 @@ describe('v1.BigQueryReadClient', () => { it('invokes createReadSession without error using callback', async () => { const client = new bigqueryreadModule.v1.BigQueryReadClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -363,7 +363,7 @@ describe('v1.BigQueryReadClient', () => { it('invokes createReadSession with error', async () => { const client = new bigqueryreadModule.v1.BigQueryReadClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -395,7 +395,7 @@ describe('v1.BigQueryReadClient', () => { it('invokes createReadSession with closed client', async () => { const client = new bigqueryreadModule.v1.BigQueryReadClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -409,7 +409,7 @@ describe('v1.BigQueryReadClient', () => { ); request.readSession.table = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => { + client.close().catch((err) => { throw err; }); await assert.rejects(client.createReadSession(request), expectedError); @@ -419,7 +419,7 @@ describe('v1.BigQueryReadClient', () => { describe('splitReadStream', () => { it('invokes splitReadStream without error', async () => { const client = new bigqueryreadModule.v1.BigQueryReadClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -450,7 +450,7 @@ describe('v1.BigQueryReadClient', () => { it('invokes splitReadStream without error using callback', async () => { const client = new bigqueryreadModule.v1.BigQueryReadClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -497,7 +497,7 @@ describe('v1.BigQueryReadClient', () => { it('invokes splitReadStream with error', async () => { const client = new bigqueryreadModule.v1.BigQueryReadClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -528,7 +528,7 @@ describe('v1.BigQueryReadClient', () => { it('invokes splitReadStream with closed client', async () => { const client = new bigqueryreadModule.v1.BigQueryReadClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -541,7 +541,7 @@ describe('v1.BigQueryReadClient', () => { ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => { + client.close().catch((err) => { throw err; }); await assert.rejects(client.splitReadStream(request), expectedError); @@ -551,7 +551,7 @@ describe('v1.BigQueryReadClient', () => { describe('readRows', () => { it('invokes readRows without error', async () => { const client = new bigqueryreadModule.v1.BigQueryReadClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -596,7 +596,7 @@ describe('v1.BigQueryReadClient', () => { it('invokes readRows without error and gaxServerStreamingRetries enabled', async () => { const client = new bigqueryreadModule.v1.BigQueryReadClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', gaxServerStreamingRetries: true, }); @@ -642,7 +642,7 @@ describe('v1.BigQueryReadClient', () => { it('invokes readRows with error', async () => { const client = new bigqueryreadModule.v1.BigQueryReadClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -687,7 +687,7 @@ describe('v1.BigQueryReadClient', () => { it('invokes readRows with closed client', async () => { const client = new bigqueryreadModule.v1.BigQueryReadClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -700,11 +700,11 @@ describe('v1.BigQueryReadClient', () => { ); request.readStream = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => { + client.close().catch((err) => { throw err; }); const stream = client.readRows(request, { - retryRequestOptions: {noResponseRetries: 0}, + retryRequestOptions: { noResponseRetries: 0 }, }); const promise = new Promise((resolve, reject) => { stream.on( @@ -736,7 +736,7 @@ describe('v1.BigQueryReadClient', () => { project: 'projectValue', }; const client = new bigqueryreadModule.v1.BigQueryReadClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -776,7 +776,7 @@ describe('v1.BigQueryReadClient', () => { session: 'sessionValue', }; const client = new bigqueryreadModule.v1.BigQueryReadClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -841,7 +841,7 @@ describe('v1.BigQueryReadClient', () => { stream: 'streamValue', }; const client = new bigqueryreadModule.v1.BigQueryReadClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -916,7 +916,7 @@ describe('v1.BigQueryReadClient', () => { table: 'tableValue', }; const client = new bigqueryreadModule.v1.BigQueryReadClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -981,7 +981,7 @@ describe('v1.BigQueryReadClient', () => { stream: 'streamValue', }; const client = new bigqueryreadModule.v1.BigQueryReadClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); diff --git a/handwritten/bigquery-storage/test/gapic_big_query_read_v1beta2.ts b/handwritten/bigquery-storage/test/gapic_big_query_read_v1beta2.ts new file mode 100644 index 000000000000..3a9df05fe195 --- /dev/null +++ b/handwritten/bigquery-storage/test/gapic_big_query_read_v1beta2.ts @@ -0,0 +1,1051 @@ +// Copyright 2026 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 +// +// https://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 file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +import * as protos from '../protos/protos'; +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; +import * as bigqueryreadModule from '../src'; + +import { PassThrough } from 'stream'; + +import { protobuf } 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/protos.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; +} + +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; +} + +function stubSimpleCall(response?: ResponseType, error?: Error) { + 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 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); +} + +describe('v1beta2.BigQueryReadClient', () => { + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquerystorage.googleapis.com'); + }); + + it('has universeDomain', () => { + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient(); + 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 = + bigqueryreadModule.v1beta2.BigQueryReadClient.servicePath; + assert.strictEqual(servicePath, 'bigquerystorage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + bigqueryreadModule.v1beta2.BigQueryReadClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'bigquerystorage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquerystorage.example.com'); + }); + + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquerystorage.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 bigqueryreadModule.v1beta2.BigQueryReadClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'bigquerystorage.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 bigqueryreadModule.v1beta2.BigQueryReadClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'bigquerystorage.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 bigqueryreadModule.v1beta2.BigQueryReadClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', + }); + }); + }); + + it('has port', () => { + const port = bigqueryreadModule.v1beta2.BigQueryReadClient.port; + assert(port); + assert(typeof port === 'number'); + }); + + it('should create a client with no option', () => { + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + fallback: true, + }); + assert(client); + }); + + it('has initialize method and supports deferred initialization', async () => { + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.bigQueryReadStub, undefined); + await client.initialize(); + assert(client.bigQueryReadStub); + }); + + it('has close method for the initialized client', (done) => { + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.bigQueryReadStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; + }); + }); + + it('has close method for the non-initialized client', (done) => { + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.bigQueryReadStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; + }); + }); + + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + 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 bigqueryreadModule.v1beta2.BigQueryReadClient({ + 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('createReadSession', () => { + it('invokes createReadSession without error', async () => { + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest(), + ); + request.readSession ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest', + ['readSession', 'table'], + ); + request.readSession.table = defaultValue1; + const expectedHeaderRequestParams = `read_session.table=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta2.ReadSession(), + ); + client.innerApiCalls.createReadSession = stubSimpleCall(expectedResponse); + const [response] = await client.createReadSession(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createReadSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createReadSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createReadSession without error using callback', async () => { + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest(), + ); + request.readSession ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest', + ['readSession', 'table'], + ); + request.readSession.table = defaultValue1; + const expectedHeaderRequestParams = `read_session.table=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta2.ReadSession(), + ); + client.innerApiCalls.createReadSession = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createReadSession( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.storage.v1beta2.IReadSession | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createReadSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createReadSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createReadSession with error', async () => { + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest(), + ); + request.readSession ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest', + ['readSession', 'table'], + ); + request.readSession.table = defaultValue1; + const expectedHeaderRequestParams = `read_session.table=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createReadSession = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createReadSession(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createReadSession as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createReadSession as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createReadSession with closed client', async () => { + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest(), + ); + request.readSession ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta2.CreateReadSessionRequest', + ['readSession', 'table'], + ); + request.readSession.table = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createReadSession(request), expectedError); + }); + }); + + describe('splitReadStream', () => { + it('invokes splitReadStream without error', async () => { + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse(), + ); + client.innerApiCalls.splitReadStream = stubSimpleCall(expectedResponse); + const [response] = await client.splitReadStream(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.splitReadStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.splitReadStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes splitReadStream without error using callback', async () => { + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta2.SplitReadStreamResponse(), + ); + client.innerApiCalls.splitReadStream = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.splitReadStream( + request, + ( + err?: Error | null, + result?: protos.google.cloud.bigquery.storage.v1beta2.ISplitReadStreamResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.splitReadStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.splitReadStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes splitReadStream with error', async () => { + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.splitReadStream = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.splitReadStream(request), expectedError); + const actualRequest = ( + client.innerApiCalls.splitReadStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.splitReadStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes splitReadStream with closed client', async () => { + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta2.SplitReadStreamRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.splitReadStream(request), expectedError); + }); + }); + + describe('readRows', () => { + it('invokes readRows without error', async () => { + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta2.ReadRowsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta2.ReadRowsRequest', + ['readStream'], + ); + request.readStream = defaultValue1; + const expectedHeaderRequestParams = `read_stream=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta2.ReadRowsResponse(), + ); + client.innerApiCalls.readRows = stubServerStreamingCall(expectedResponse); + const stream = client.readRows(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.cloud.bigquery.storage.v1beta2.ReadRowsResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.readRows as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.readRows as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes readRows without error and gaxServerStreamingRetries enabled', async () => { + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + gaxServerStreamingRetries: true, + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta2.ReadRowsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta2.ReadRowsRequest', + ['readStream'], + ); + request.readStream = defaultValue1; + const expectedHeaderRequestParams = `read_stream=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta2.ReadRowsResponse(), + ); + client.innerApiCalls.readRows = stubServerStreamingCall(expectedResponse); + const stream = client.readRows(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.cloud.bigquery.storage.v1beta2.ReadRowsResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.readRows as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.readRows as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes readRows with error', async () => { + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta2.ReadRowsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta2.ReadRowsRequest', + ['readStream'], + ); + request.readStream = defaultValue1; + const expectedHeaderRequestParams = `read_stream=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.readRows = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.readRows(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.cloud.bigquery.storage.v1beta2.ReadRowsResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.readRows as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.readRows as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes readRows with closed client', async () => { + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.bigquery.storage.v1beta2.ReadRowsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.cloud.bigquery.storage.v1beta2.ReadRowsRequest', + ['readStream'], + ); + request.readStream = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + const stream = client.readRows(request, { + retryRequestOptions: { noResponseRetries: 0 }, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.cloud.bigquery.storage.v1beta2.ReadRowsResponse, + ) => { + 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 bigqueryreadModule.v1beta2.BigQueryReadClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('Path templates', () => { + describe('project', async () => { + const fakePath = '/rendered/path/project'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + 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('readSession', async () => { + const fakePath = '/rendered/path/readSession'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + session: 'sessionValue', + }; + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.readSessionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.readSessionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('readSessionPath', () => { + const result = client.readSessionPath( + 'projectValue', + 'locationValue', + 'sessionValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.readSessionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromReadSessionName', () => { + const result = client.matchProjectFromReadSessionName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.readSessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromReadSessionName', () => { + const result = client.matchLocationFromReadSessionName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.readSessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSessionFromReadSessionName', () => { + const result = client.matchSessionFromReadSessionName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.readSessionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('readStream', async () => { + const fakePath = '/rendered/path/readStream'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + session: 'sessionValue', + stream: 'streamValue', + }; + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.readStreamPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.readStreamPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('readStreamPath', () => { + const result = client.readStreamPath( + 'projectValue', + 'locationValue', + 'sessionValue', + 'streamValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.readStreamPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromReadStreamName', () => { + const result = client.matchProjectFromReadStreamName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.readStreamPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromReadStreamName', () => { + const result = client.matchLocationFromReadStreamName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.readStreamPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSessionFromReadStreamName', () => { + const result = client.matchSessionFromReadStreamName(fakePath); + assert.strictEqual(result, 'sessionValue'); + assert( + (client.pathTemplates.readStreamPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchStreamFromReadStreamName', () => { + const result = client.matchStreamFromReadStreamName(fakePath); + assert.strictEqual(result, 'streamValue'); + assert( + (client.pathTemplates.readStreamPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('table', async () => { + const fakePath = '/rendered/path/table'; + const expectedParameters = { + project: 'projectValue', + dataset: 'datasetValue', + table: 'tableValue', + }; + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tablePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tablePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tablePath', () => { + const result = client.tablePath( + 'projectValue', + 'datasetValue', + 'tableValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.tablePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromTableName', () => { + const result = client.matchProjectFromTableName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.tablePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDatasetFromTableName', () => { + const result = client.matchDatasetFromTableName(fakePath); + assert.strictEqual(result, 'datasetValue'); + assert( + (client.pathTemplates.tablePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTableFromTableName', () => { + const result = client.matchTableFromTableName(fakePath); + assert.strictEqual(result, 'tableValue'); + assert( + (client.pathTemplates.tablePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('writeStream', async () => { + const fakePath = '/rendered/path/writeStream'; + const expectedParameters = { + project: 'projectValue', + dataset: 'datasetValue', + table: 'tableValue', + stream: 'streamValue', + }; + const client = new bigqueryreadModule.v1beta2.BigQueryReadClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.writeStreamPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.writeStreamPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('writeStreamPath', () => { + const result = client.writeStreamPath( + 'projectValue', + 'datasetValue', + 'tableValue', + 'streamValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.writeStreamPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromWriteStreamName', () => { + const result = client.matchProjectFromWriteStreamName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.writeStreamPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDatasetFromWriteStreamName', () => { + const result = client.matchDatasetFromWriteStreamName(fakePath); + assert.strictEqual(result, 'datasetValue'); + assert( + (client.pathTemplates.writeStreamPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchTableFromWriteStreamName', () => { + const result = client.matchTableFromWriteStreamName(fakePath); + assert.strictEqual(result, 'tableValue'); + assert( + (client.pathTemplates.writeStreamPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchStreamFromWriteStreamName', () => { + const result = client.matchStreamFromWriteStreamName(fakePath); + assert.strictEqual(result, 'streamValue'); + assert( + (client.pathTemplates.writeStreamPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + }); +}); diff --git a/handwritten/bigquery-storage/test/gapic_big_query_storage_v1beta1.ts b/handwritten/bigquery-storage/test/gapic_big_query_storage_v1beta1.ts index 27cdb803d130..8a3938d925ea 100644 --- a/handwritten/bigquery-storage/test/gapic_big_query_storage_v1beta1.ts +++ b/handwritten/bigquery-storage/test/gapic_big_query_storage_v1beta1.ts @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,13 +19,13 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as bigquerystorageModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects @@ -45,7 +45,7 @@ function getTypeDefaultValue(typeName: string, fields: string[]) { function generateSampleMessage(instance: T) { const filledObject = ( instance.constructor as typeof protobuf.Message - ).toObject(instance as protobuf.Message, {defaults: true}); + ).toObject(instance as protobuf.Message, { defaults: true }); return (instance.constructor as typeof protobuf.Message).fromObject( filledObject, ) as T; @@ -204,7 +204,7 @@ describe('v1beta1.BigQueryStorageClient', () => { it('has initialize method and supports deferred initialization', async () => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); assert.strictEqual(client.bigQueryStorageStub, undefined); @@ -212,12 +212,12 @@ describe('v1beta1.BigQueryStorageClient', () => { assert(client.bigQueryStorageStub); }); - it('has close method for the initialized client', done => { + it('has close method for the initialized client', (done) => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize().catch(err => { + client.initialize().catch((err) => { throw err; }); assert(client.bigQueryStorageStub); @@ -226,14 +226,14 @@ describe('v1beta1.BigQueryStorageClient', () => { .then(() => { done(); }) - .catch(err => { + .catch((err) => { throw err; }); }); - it('has close method for the non-initialized client', done => { + it('has close method for the non-initialized client', (done) => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); assert.strictEqual(client.bigQueryStorageStub, undefined); @@ -242,7 +242,7 @@ describe('v1beta1.BigQueryStorageClient', () => { .then(() => { done(); }) - .catch(err => { + .catch((err) => { throw err; }); }); @@ -250,7 +250,7 @@ describe('v1beta1.BigQueryStorageClient', () => { it('has getProjectId method', async () => { const fakeProjectId = 'fake-project-id'; const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); @@ -262,7 +262,7 @@ describe('v1beta1.BigQueryStorageClient', () => { it('has getProjectId method with callback', async () => { const fakeProjectId = 'fake-project-id'; const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); client.auth.getProjectId = sinon @@ -285,7 +285,7 @@ describe('v1beta1.BigQueryStorageClient', () => { describe('createReadSession', () => { it('invokes createReadSession without error', async () => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -323,7 +323,7 @@ describe('v1beta1.BigQueryStorageClient', () => { it('invokes createReadSession without error using callback', async () => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -377,7 +377,7 @@ describe('v1beta1.BigQueryStorageClient', () => { it('invokes createReadSession with error', async () => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -415,7 +415,7 @@ describe('v1beta1.BigQueryStorageClient', () => { it('invokes createReadSession with closed client', async () => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -435,7 +435,7 @@ describe('v1beta1.BigQueryStorageClient', () => { ); request.tableReference.datasetId = defaultValue2; const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => { + client.close().catch((err) => { throw err; }); await assert.rejects(client.createReadSession(request), expectedError); @@ -445,7 +445,7 @@ describe('v1beta1.BigQueryStorageClient', () => { describe('batchCreateReadSessionStreams', () => { it('invokes batchCreateReadSessionStreams without error', async () => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -478,7 +478,7 @@ describe('v1beta1.BigQueryStorageClient', () => { it('invokes batchCreateReadSessionStreams without error using callback', async () => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -526,7 +526,7 @@ describe('v1beta1.BigQueryStorageClient', () => { it('invokes batchCreateReadSessionStreams with error', async () => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -561,7 +561,7 @@ describe('v1beta1.BigQueryStorageClient', () => { it('invokes batchCreateReadSessionStreams with closed client', async () => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -575,7 +575,7 @@ describe('v1beta1.BigQueryStorageClient', () => { ); request.session.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => { + client.close().catch((err) => { throw err; }); await assert.rejects( @@ -588,7 +588,7 @@ describe('v1beta1.BigQueryStorageClient', () => { describe('finalizeStream', () => { it('invokes finalizeStream without error', async () => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -620,7 +620,7 @@ describe('v1beta1.BigQueryStorageClient', () => { it('invokes finalizeStream without error using callback', async () => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -668,7 +668,7 @@ describe('v1beta1.BigQueryStorageClient', () => { it('invokes finalizeStream with error', async () => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -700,7 +700,7 @@ describe('v1beta1.BigQueryStorageClient', () => { it('invokes finalizeStream with closed client', async () => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -714,7 +714,7 @@ describe('v1beta1.BigQueryStorageClient', () => { ); request.stream.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => { + client.close().catch((err) => { throw err; }); await assert.rejects(client.finalizeStream(request), expectedError); @@ -724,7 +724,7 @@ describe('v1beta1.BigQueryStorageClient', () => { describe('splitReadStream', () => { it('invokes splitReadStream without error', async () => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -756,7 +756,7 @@ describe('v1beta1.BigQueryStorageClient', () => { it('invokes splitReadStream without error using callback', async () => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -804,7 +804,7 @@ describe('v1beta1.BigQueryStorageClient', () => { it('invokes splitReadStream with error', async () => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -836,7 +836,7 @@ describe('v1beta1.BigQueryStorageClient', () => { it('invokes splitReadStream with closed client', async () => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -850,7 +850,7 @@ describe('v1beta1.BigQueryStorageClient', () => { ); request.originalStream.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => { + client.close().catch((err) => { throw err; }); await assert.rejects(client.splitReadStream(request), expectedError); @@ -860,7 +860,7 @@ describe('v1beta1.BigQueryStorageClient', () => { describe('readRows', () => { it('invokes readRows without error', async () => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -907,7 +907,7 @@ describe('v1beta1.BigQueryStorageClient', () => { it('invokes readRows without error and gaxServerStreamingRetries enabled', async () => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', gaxServerStreamingRetries: true, }); @@ -955,7 +955,7 @@ describe('v1beta1.BigQueryStorageClient', () => { it('invokes readRows with error', async () => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1002,7 +1002,7 @@ describe('v1beta1.BigQueryStorageClient', () => { it('invokes readRows with closed client', async () => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1017,11 +1017,11 @@ describe('v1beta1.BigQueryStorageClient', () => { ); request.readPosition.stream.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => { + client.close().catch((err) => { throw err; }); const stream = client.readRows(request, { - retryRequestOptions: {noResponseRetries: 0}, + retryRequestOptions: { noResponseRetries: 0 }, }); const promise = new Promise((resolve, reject) => { stream.on( @@ -1053,7 +1053,7 @@ describe('v1beta1.BigQueryStorageClient', () => { project: 'projectValue', }; const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1093,7 +1093,7 @@ describe('v1beta1.BigQueryStorageClient', () => { session: 'sessionValue', }; const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1157,7 +1157,7 @@ describe('v1beta1.BigQueryStorageClient', () => { stream: 'streamValue', }; const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); diff --git a/handwritten/bigquery-storage/test/gapic_big_query_write_v1.ts b/handwritten/bigquery-storage/test/gapic_big_query_write_v1.ts index 7c78a4d3b30b..164b1603e083 100644 --- a/handwritten/bigquery-storage/test/gapic_big_query_write_v1.ts +++ b/handwritten/bigquery-storage/test/gapic_big_query_write_v1.ts @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,13 +19,13 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as bigquerywriteModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects @@ -45,7 +45,7 @@ function getTypeDefaultValue(typeName: string, fields: string[]) { function generateSampleMessage(instance: T) { const filledObject = ( instance.constructor as typeof protobuf.Message - ).toObject(instance as protobuf.Message, {defaults: true}); + ).toObject(instance as protobuf.Message, { defaults: true }); return (instance.constructor as typeof protobuf.Message).fromObject( filledObject, ) as T; @@ -195,7 +195,7 @@ describe('v1.BigQueryWriteClient', () => { it('has initialize method and supports deferred initialization', async () => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); assert.strictEqual(client.bigQueryWriteStub, undefined); @@ -203,12 +203,12 @@ describe('v1.BigQueryWriteClient', () => { assert(client.bigQueryWriteStub); }); - it('has close method for the initialized client', done => { + it('has close method for the initialized client', (done) => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize().catch(err => { + client.initialize().catch((err) => { throw err; }); assert(client.bigQueryWriteStub); @@ -217,14 +217,14 @@ describe('v1.BigQueryWriteClient', () => { .then(() => { done(); }) - .catch(err => { + .catch((err) => { throw err; }); }); - it('has close method for the non-initialized client', done => { + it('has close method for the non-initialized client', (done) => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); assert.strictEqual(client.bigQueryWriteStub, undefined); @@ -233,7 +233,7 @@ describe('v1.BigQueryWriteClient', () => { .then(() => { done(); }) - .catch(err => { + .catch((err) => { throw err; }); }); @@ -241,7 +241,7 @@ describe('v1.BigQueryWriteClient', () => { it('has getProjectId method', async () => { const fakeProjectId = 'fake-project-id'; const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); @@ -253,7 +253,7 @@ describe('v1.BigQueryWriteClient', () => { it('has getProjectId method with callback', async () => { const fakeProjectId = 'fake-project-id'; const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); client.auth.getProjectId = sinon @@ -276,7 +276,7 @@ describe('v1.BigQueryWriteClient', () => { describe('createWriteStream', () => { it('invokes createWriteStream without error', async () => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -307,7 +307,7 @@ describe('v1.BigQueryWriteClient', () => { it('invokes createWriteStream without error using callback', async () => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -354,7 +354,7 @@ describe('v1.BigQueryWriteClient', () => { it('invokes createWriteStream with error', async () => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -385,7 +385,7 @@ describe('v1.BigQueryWriteClient', () => { it('invokes createWriteStream with closed client', async () => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -398,7 +398,7 @@ describe('v1.BigQueryWriteClient', () => { ); request.parent = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => { + client.close().catch((err) => { throw err; }); await assert.rejects(client.createWriteStream(request), expectedError); @@ -408,7 +408,7 @@ describe('v1.BigQueryWriteClient', () => { describe('getWriteStream', () => { it('invokes getWriteStream without error', async () => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -439,7 +439,7 @@ describe('v1.BigQueryWriteClient', () => { it('invokes getWriteStream without error using callback', async () => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -486,7 +486,7 @@ describe('v1.BigQueryWriteClient', () => { it('invokes getWriteStream with error', async () => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -517,7 +517,7 @@ describe('v1.BigQueryWriteClient', () => { it('invokes getWriteStream with closed client', async () => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -530,7 +530,7 @@ describe('v1.BigQueryWriteClient', () => { ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => { + client.close().catch((err) => { throw err; }); await assert.rejects(client.getWriteStream(request), expectedError); @@ -540,7 +540,7 @@ describe('v1.BigQueryWriteClient', () => { describe('finalizeWriteStream', () => { it('invokes finalizeWriteStream without error', async () => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -572,7 +572,7 @@ describe('v1.BigQueryWriteClient', () => { it('invokes finalizeWriteStream without error using callback', async () => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -619,7 +619,7 @@ describe('v1.BigQueryWriteClient', () => { it('invokes finalizeWriteStream with error', async () => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -650,7 +650,7 @@ describe('v1.BigQueryWriteClient', () => { it('invokes finalizeWriteStream with closed client', async () => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -663,7 +663,7 @@ describe('v1.BigQueryWriteClient', () => { ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => { + client.close().catch((err) => { throw err; }); await assert.rejects(client.finalizeWriteStream(request), expectedError); @@ -673,7 +673,7 @@ describe('v1.BigQueryWriteClient', () => { describe('batchCommitWriteStreams', () => { it('invokes batchCommitWriteStreams without error', async () => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -705,7 +705,7 @@ describe('v1.BigQueryWriteClient', () => { it('invokes batchCommitWriteStreams without error using callback', async () => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -752,7 +752,7 @@ describe('v1.BigQueryWriteClient', () => { it('invokes batchCommitWriteStreams with error', async () => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -786,7 +786,7 @@ describe('v1.BigQueryWriteClient', () => { it('invokes batchCommitWriteStreams with closed client', async () => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -799,7 +799,7 @@ describe('v1.BigQueryWriteClient', () => { ); request.parent = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => { + client.close().catch((err) => { throw err; }); await assert.rejects( @@ -812,7 +812,7 @@ describe('v1.BigQueryWriteClient', () => { describe('flushRows', () => { it('invokes flushRows without error', async () => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -843,7 +843,7 @@ describe('v1.BigQueryWriteClient', () => { it('invokes flushRows without error using callback', async () => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -890,7 +890,7 @@ describe('v1.BigQueryWriteClient', () => { it('invokes flushRows with error', async () => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -918,7 +918,7 @@ describe('v1.BigQueryWriteClient', () => { it('invokes flushRows with closed client', async () => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -931,7 +931,7 @@ describe('v1.BigQueryWriteClient', () => { ); request.writeStream = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => { + client.close().catch((err) => { throw err; }); await assert.rejects(client.flushRows(request), expectedError); @@ -941,7 +941,7 @@ describe('v1.BigQueryWriteClient', () => { describe('appendRows', () => { it('invokes appendRows without error', async () => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -985,7 +985,7 @@ describe('v1.BigQueryWriteClient', () => { it('invokes appendRows with error', async () => { const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1034,7 +1034,7 @@ describe('v1.BigQueryWriteClient', () => { project: 'projectValue', }; const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1074,7 +1074,7 @@ describe('v1.BigQueryWriteClient', () => { session: 'sessionValue', }; const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1139,7 +1139,7 @@ describe('v1.BigQueryWriteClient', () => { stream: 'streamValue', }; const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1214,7 +1214,7 @@ describe('v1.BigQueryWriteClient', () => { table: 'tableValue', }; const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1279,7 +1279,7 @@ describe('v1.BigQueryWriteClient', () => { stream: 'streamValue', }; const client = new bigquerywriteModule.v1.BigQueryWriteClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); diff --git a/handwritten/bigquery-storage/test/gapic_metastore_partition_service_v1alpha.ts b/handwritten/bigquery-storage/test/gapic_metastore_partition_service_v1alpha.ts index 5746d5e08b6f..245b16ba78f5 100644 --- a/handwritten/bigquery-storage/test/gapic_metastore_partition_service_v1alpha.ts +++ b/handwritten/bigquery-storage/test/gapic_metastore_partition_service_v1alpha.ts @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,13 +19,13 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as metastorepartitionserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects @@ -45,7 +45,7 @@ function getTypeDefaultValue(typeName: string, fields: string[]) { function generateSampleMessage(instance: T) { const filledObject = ( instance.constructor as typeof protobuf.Message - ).toObject(instance as protobuf.Message, {defaults: true}); + ).toObject(instance as protobuf.Message, { defaults: true }); return (instance.constructor as typeof protobuf.Message).fromObject( filledObject, ) as T; @@ -123,7 +123,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { it('sets apiEndpoint according to universe domain camelCase', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( - {universeDomain: 'example.com'}, + { universeDomain: 'example.com' }, ); const servicePath = client.apiEndpoint; assert.strictEqual(servicePath, 'bigquerystorage.example.com'); @@ -132,7 +132,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { it('sets apiEndpoint according to universe domain snakeCase', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( - {universe_domain: 'example.com'}, + { universe_domain: 'example.com' }, ); const servicePath = client.apiEndpoint; assert.strictEqual(servicePath, 'bigquerystorage.example.com'); @@ -159,7 +159,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( - {universeDomain: 'configured.example.com'}, + { universeDomain: 'configured.example.com' }, ); const servicePath = client.apiEndpoint; assert.strictEqual( @@ -177,7 +177,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { it('does not allow setting both universeDomain and universe_domain', () => { assert.throws(() => { new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( - {universe_domain: 'example.com', universeDomain: 'example.net'}, + { universe_domain: 'example.com', universeDomain: 'example.net' }, ); }); }); @@ -210,7 +210,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -219,15 +219,15 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { assert(client.metastorePartitionServiceStub); }); - it('has close method for the initialized client', done => { + it('has close method for the initialized client', (done) => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); - client.initialize().catch(err => { + client.initialize().catch((err) => { throw err; }); assert(client.metastorePartitionServiceStub); @@ -236,16 +236,16 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { .then(() => { done(); }) - .catch(err => { + .catch((err) => { throw err; }); }); - it('has close method for the non-initialized client', done => { + it('has close method for the non-initialized client', (done) => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -255,7 +255,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { .then(() => { done(); }) - .catch(err => { + .catch((err) => { throw err; }); }); @@ -265,7 +265,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -280,7 +280,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -306,7 +306,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -341,7 +341,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -391,7 +391,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -428,7 +428,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -442,7 +442,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { ); request.parent = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => { + client.close().catch((err) => { throw err; }); await assert.rejects( @@ -457,7 +457,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -492,7 +492,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -542,7 +542,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -579,7 +579,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -593,7 +593,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { ); request.parent = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => { + client.close().catch((err) => { throw err; }); await assert.rejects( @@ -608,7 +608,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -643,7 +643,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -693,7 +693,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -730,7 +730,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -744,7 +744,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { ); request.parent = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => { + client.close().catch((err) => { throw err; }); await assert.rejects( @@ -759,7 +759,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -794,7 +794,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -844,7 +844,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -881,7 +881,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -895,7 +895,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { ); request.parent = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => { + client.close().catch((err) => { throw err; }); await assert.rejects( @@ -910,7 +910,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -958,7 +958,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -1013,7 +1013,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -1091,7 +1091,7 @@ describe('v1alpha.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1alpha.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); diff --git a/handwritten/bigquery-storage/test/gapic_metastore_partition_service_v1beta.ts b/handwritten/bigquery-storage/test/gapic_metastore_partition_service_v1beta.ts index da3e55a9c512..408a160921b4 100644 --- a/handwritten/bigquery-storage/test/gapic_metastore_partition_service_v1beta.ts +++ b/handwritten/bigquery-storage/test/gapic_metastore_partition_service_v1beta.ts @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,13 +19,13 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as metastorepartitionserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects @@ -45,7 +45,7 @@ function getTypeDefaultValue(typeName: string, fields: string[]) { function generateSampleMessage(instance: T) { const filledObject = ( instance.constructor as typeof protobuf.Message - ).toObject(instance as protobuf.Message, {defaults: true}); + ).toObject(instance as protobuf.Message, { defaults: true }); return (instance.constructor as typeof protobuf.Message).fromObject( filledObject, ) as T; @@ -123,7 +123,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { it('sets apiEndpoint according to universe domain camelCase', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( - {universeDomain: 'example.com'}, + { universeDomain: 'example.com' }, ); const servicePath = client.apiEndpoint; assert.strictEqual(servicePath, 'bigquerystorage.example.com'); @@ -132,7 +132,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { it('sets apiEndpoint according to universe domain snakeCase', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( - {universe_domain: 'example.com'}, + { universe_domain: 'example.com' }, ); const servicePath = client.apiEndpoint; assert.strictEqual(servicePath, 'bigquerystorage.example.com'); @@ -159,7 +159,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( - {universeDomain: 'configured.example.com'}, + { universeDomain: 'configured.example.com' }, ); const servicePath = client.apiEndpoint; assert.strictEqual( @@ -177,7 +177,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { it('does not allow setting both universeDomain and universe_domain', () => { assert.throws(() => { new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( - {universe_domain: 'example.com', universeDomain: 'example.net'}, + { universe_domain: 'example.com', universeDomain: 'example.net' }, ); }); }); @@ -210,7 +210,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -219,15 +219,15 @@ describe('v1beta.MetastorePartitionServiceClient', () => { assert(client.metastorePartitionServiceStub); }); - it('has close method for the initialized client', done => { + it('has close method for the initialized client', (done) => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); - client.initialize().catch(err => { + client.initialize().catch((err) => { throw err; }); assert(client.metastorePartitionServiceStub); @@ -236,16 +236,16 @@ describe('v1beta.MetastorePartitionServiceClient', () => { .then(() => { done(); }) - .catch(err => { + .catch((err) => { throw err; }); }); - it('has close method for the non-initialized client', done => { + it('has close method for the non-initialized client', (done) => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -255,7 +255,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { .then(() => { done(); }) - .catch(err => { + .catch((err) => { throw err; }); }); @@ -265,7 +265,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -280,7 +280,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -306,7 +306,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -341,7 +341,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -391,7 +391,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -428,7 +428,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -442,7 +442,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { ); request.parent = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => { + client.close().catch((err) => { throw err; }); await assert.rejects( @@ -457,7 +457,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -492,7 +492,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -542,7 +542,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -579,7 +579,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -593,7 +593,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { ); request.parent = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => { + client.close().catch((err) => { throw err; }); await assert.rejects( @@ -608,7 +608,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -643,7 +643,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -693,7 +693,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -730,7 +730,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -744,7 +744,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { ); request.parent = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => { + client.close().catch((err) => { throw err; }); await assert.rejects( @@ -759,7 +759,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -794,7 +794,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -844,7 +844,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -881,7 +881,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -895,7 +895,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { ); request.parent = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => { + client.close().catch((err) => { throw err; }); await assert.rejects( @@ -910,7 +910,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -958,7 +958,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -1013,7 +1013,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); @@ -1091,7 +1091,7 @@ describe('v1beta.MetastorePartitionServiceClient', () => { const client = new metastorepartitionserviceModule.v1beta.MetastorePartitionServiceClient( { - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }, ); diff --git a/handwritten/bigquery-storage/tsconfig.json b/handwritten/bigquery-storage/tsconfig.json index ee0702dcdefd..ca73e7bfc824 100644 --- a/handwritten/bigquery-storage/tsconfig.json +++ b/handwritten/bigquery-storage/tsconfig.json @@ -14,9 +14,7 @@ "src/**/*.ts", "test/*.ts", "test/**/*.ts", - "test/testdata/message.json", "system-test/*.ts", - "system-test/fixtures/customer_record.json", "src/**/*.json", "samples/**/*.json", "protos/protos.json" diff --git a/handwritten/bigquery-storage/webpack.config.js b/handwritten/bigquery-storage/webpack.config.js index de163617408c..bad73cc0fe26 100644 --- a/handwritten/bigquery-storage/webpack.config.js +++ b/handwritten/bigquery-storage/webpack.config.js @@ -36,27 +36,27 @@ module.exports = { { test: /\.tsx?$/, use: 'ts-loader', - exclude: /node_modules/, + exclude: /node_modules/ }, { test: /node_modules[\\/]@grpc[\\/]grpc-js/, - use: 'null-loader', + use: 'null-loader' }, { test: /node_modules[\\/]grpc/, - use: 'null-loader', + use: 'null-loader' }, { test: /node_modules[\\/]retry-request/, - use: 'null-loader', + use: 'null-loader' }, { test: /node_modules[\\/]https?-proxy-agent/, - use: 'null-loader', + use: 'null-loader' }, { test: /node_modules[\\/]gtoken/, - use: 'null-loader', + use: 'null-loader' }, ], }, diff --git a/handwritten/datastore/.OwlBot.yaml b/handwritten/datastore/.OwlBot.yaml index 7db91a105f96..7ed9b7b5cff3 100644 --- a/handwritten/datastore/.OwlBot.yaml +++ b/handwritten/datastore/.OwlBot.yaml @@ -1,10 +1,10 @@ -# Copyright 2021 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. # You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# 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, @@ -12,15 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. - -deep-remove-regex: - - /owl-bot-staging - deep-copy-regex: - - source: /google/datastore/(v.*)/.*-nodejs - dest: /owl-bot-staging/datastore/$1 - - source: /google/datastore/(admin/v.*)/.*-nodejs - dest: /owl-bot-staging/datastore/$1 - -begin-after-commit-hash: fb91803ccef5d7c695139b22788b309e2197856b + - source: /google/datastore/admin/google-datastore-admin-nodejs + dest: /owl-bot-staging/google-datastore-admin +api-name: admin \ No newline at end of file diff --git a/handwritten/datastore/.jsdoc.js b/handwritten/datastore/.jsdoc.js index 4e00e5b8f282..47c538344e03 100644 --- a/handwritten/datastore/.jsdoc.js +++ b/handwritten/datastore/.jsdoc.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -40,7 +40,7 @@ module.exports = { includePattern: '\\.js$' }, templates: { - copyright: 'Copyright 2025 Google LLC', + copyright: 'Copyright 2026 Google LLC', includeDate: false, sourceFiles: false, systemName: '@google-cloud/datastore', diff --git a/handwritten/datastore/samples/generated/v1/datastore.allocate_ids.js b/handwritten/datastore/samples/generated/v1/datastore.allocate_ids.js index e47fb3a80670..a9d6a4da9b1f 100644 --- a/handwritten/datastore/samples/generated/v1/datastore.allocate_ids.js +++ b/handwritten/datastore/samples/generated/v1/datastore.allocate_ids.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/datastore/samples/generated/v1/datastore.begin_transaction.js b/handwritten/datastore/samples/generated/v1/datastore.begin_transaction.js index 048d1ef5e3a7..8ebff8759bd9 100644 --- a/handwritten/datastore/samples/generated/v1/datastore.begin_transaction.js +++ b/handwritten/datastore/samples/generated/v1/datastore.begin_transaction.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/datastore/samples/generated/v1/datastore.commit.js b/handwritten/datastore/samples/generated/v1/datastore.commit.js index 6adbb99605fd..1e8af82f7b31 100644 --- a/handwritten/datastore/samples/generated/v1/datastore.commit.js +++ b/handwritten/datastore/samples/generated/v1/datastore.commit.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/datastore/samples/generated/v1/datastore.lookup.js b/handwritten/datastore/samples/generated/v1/datastore.lookup.js index 10605896735c..73830172b6e2 100644 --- a/handwritten/datastore/samples/generated/v1/datastore.lookup.js +++ b/handwritten/datastore/samples/generated/v1/datastore.lookup.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/datastore/samples/generated/v1/datastore.reserve_ids.js b/handwritten/datastore/samples/generated/v1/datastore.reserve_ids.js index d6a5b8559648..3a8c0bc36889 100644 --- a/handwritten/datastore/samples/generated/v1/datastore.reserve_ids.js +++ b/handwritten/datastore/samples/generated/v1/datastore.reserve_ids.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/datastore/samples/generated/v1/datastore.rollback.js b/handwritten/datastore/samples/generated/v1/datastore.rollback.js index 27757dcc8282..f76f8f7be802 100644 --- a/handwritten/datastore/samples/generated/v1/datastore.rollback.js +++ b/handwritten/datastore/samples/generated/v1/datastore.rollback.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/datastore/samples/generated/v1/datastore.run_aggregation_query.js b/handwritten/datastore/samples/generated/v1/datastore.run_aggregation_query.js index b5c44b6ef74c..b3d26c8fcc08 100644 --- a/handwritten/datastore/samples/generated/v1/datastore.run_aggregation_query.js +++ b/handwritten/datastore/samples/generated/v1/datastore.run_aggregation_query.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/datastore/samples/generated/v1/datastore.run_query.js b/handwritten/datastore/samples/generated/v1/datastore.run_query.js index 70237069d9c9..87b7f9d16bc2 100644 --- a/handwritten/datastore/samples/generated/v1/datastore.run_query.js +++ b/handwritten/datastore/samples/generated/v1/datastore.run_query.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/datastore/samples/generated/v1/datastore_admin.create_index.js b/handwritten/datastore/samples/generated/v1/datastore_admin.create_index.js index a54d726a8a74..72b80a24bc81 100644 --- a/handwritten/datastore/samples/generated/v1/datastore_admin.create_index.js +++ b/handwritten/datastore/samples/generated/v1/datastore_admin.create_index.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/datastore/samples/generated/v1/datastore_admin.delete_index.js b/handwritten/datastore/samples/generated/v1/datastore_admin.delete_index.js index 8b74e8d5e4dc..e891224de6a9 100644 --- a/handwritten/datastore/samples/generated/v1/datastore_admin.delete_index.js +++ b/handwritten/datastore/samples/generated/v1/datastore_admin.delete_index.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/datastore/samples/generated/v1/datastore_admin.export_entities.js b/handwritten/datastore/samples/generated/v1/datastore_admin.export_entities.js index de3f899694b2..60681aefd50d 100644 --- a/handwritten/datastore/samples/generated/v1/datastore_admin.export_entities.js +++ b/handwritten/datastore/samples/generated/v1/datastore_admin.export_entities.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/datastore/samples/generated/v1/datastore_admin.get_index.js b/handwritten/datastore/samples/generated/v1/datastore_admin.get_index.js index 9c930af60b89..d3b3032284a1 100644 --- a/handwritten/datastore/samples/generated/v1/datastore_admin.get_index.js +++ b/handwritten/datastore/samples/generated/v1/datastore_admin.get_index.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/datastore/samples/generated/v1/datastore_admin.import_entities.js b/handwritten/datastore/samples/generated/v1/datastore_admin.import_entities.js index a17a03e9c2fb..f607e51e5e3b 100644 --- a/handwritten/datastore/samples/generated/v1/datastore_admin.import_entities.js +++ b/handwritten/datastore/samples/generated/v1/datastore_admin.import_entities.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/datastore/samples/generated/v1/datastore_admin.list_indexes.js b/handwritten/datastore/samples/generated/v1/datastore_admin.list_indexes.js index 624f64231486..16c954b3f325 100644 --- a/handwritten/datastore/samples/generated/v1/datastore_admin.list_indexes.js +++ b/handwritten/datastore/samples/generated/v1/datastore_admin.list_indexes.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/handwritten/datastore/src/v1/datastore_admin_client.ts b/handwritten/datastore/src/v1/datastore_admin_client.ts index 1156724c081d..4e22175c3309 100644 --- a/handwritten/datastore/src/v1/datastore_admin_client.ts +++ b/handwritten/datastore/src/v1/datastore_admin_client.ts @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -28,10 +28,10 @@ import type { PaginationCallback, GaxCall, } from 'google-gax'; -import {Transform} from 'stream'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -99,7 +99,7 @@ export class DatastoreAdminClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('datastore-admin'); @@ -112,9 +112,9 @@ export class DatastoreAdminClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; + innerApiCalls: { [name: string]: Function }; operationsClient: gax.OperationsClient; - datastoreAdminStub?: Promise<{[name: string]: Function}>; + datastoreAdminStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of DatastoreAdminClient. @@ -190,7 +190,7 @@ export class DatastoreAdminClient { const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // Request numeric enum values if REST transport is used. opts.numericEnums = true; @@ -257,7 +257,7 @@ export class DatastoreAdminClient { ), }; - const protoFilesRoot = this._gaxModule.protobuf.Root.fromJSON(jsonProtos); + const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); // This API contains "long-running operations", which return a // an Operation object that allows for tracking of the operation, // rather than holding a request open. @@ -342,7 +342,7 @@ export class DatastoreAdminClient { 'google.datastore.admin.v1.DatastoreAdmin', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')}, + { 'x-goog-api-client': clientHeader.join(' ') }, ); // Set up a dictionary of "inner API calls"; the core implementation @@ -382,7 +382,7 @@ export class DatastoreAdminClient { (this._protos as any).google.datastore.admin.v1.DatastoreAdmin, this._opts, this._providedCustomServicePath, - ) as Promise<{[method: string]: Function}>; + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -396,7 +396,7 @@ export class DatastoreAdminClient { ]; for (const methodName of datastoreAdminStubMethods) { const callPromise = this.datastoreAdminStub.then( - stub => + (stub) => (...args: Array<{}>) => { if (this._terminated) { return Promise.reject('The client has already been closed.'); @@ -592,10 +592,10 @@ export class DatastoreAdminClient { options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = this._gaxModule.routingHeader.fromParams({ - project_id: request.projectId ?? '', - index_id: request.indexId ?? '', + project_id: request.projectId?.toString() ?? '', + index_id: request.indexId?.toString() ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('getIndex request %j', request); @@ -622,7 +622,23 @@ export class DatastoreAdminClient { this._log.info('getIndex response %j', response); return [response, options, rawResponse]; }, - ); + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** @@ -752,9 +768,9 @@ export class DatastoreAdminClient { options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = this._gaxModule.routingHeader.fromParams({ - project_id: request.projectId ?? '', + project_id: request.projectId?.toString() ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); const wrappedCallback: @@ -811,7 +827,7 @@ export class DatastoreAdminClient { this._log.info('exportEntities long-running'); const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( - {name}, + { name }, ); const [operation] = await this.operationsClient.getOperation(request); const decodeOperation = new this._gaxModule.Operation( @@ -947,9 +963,9 @@ export class DatastoreAdminClient { options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = this._gaxModule.routingHeader.fromParams({ - project_id: request.projectId ?? '', + project_id: request.projectId?.toString() ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); const wrappedCallback: @@ -1006,7 +1022,7 @@ export class DatastoreAdminClient { this._log.info('importEntities long-running'); const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( - {name}, + { name }, ); const [operation] = await this.operationsClient.getOperation(request); const decodeOperation = new this._gaxModule.Operation( @@ -1132,9 +1148,9 @@ export class DatastoreAdminClient { options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = this._gaxModule.routingHeader.fromParams({ - project_id: request.projectId ?? '', + project_id: request.projectId?.toString() ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); const wrappedCallback: @@ -1191,7 +1207,7 @@ export class DatastoreAdminClient { this._log.info('createIndex long-running'); const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( - {name}, + { name }, ); const [operation] = await this.operationsClient.getOperation(request); const decodeOperation = new this._gaxModule.Operation( @@ -1313,10 +1329,10 @@ export class DatastoreAdminClient { options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = this._gaxModule.routingHeader.fromParams({ - project_id: request.projectId ?? '', - index_id: request.indexId ?? '', + project_id: request.projectId?.toString() ?? '', + index_id: request.indexId?.toString() ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); const wrappedCallback: @@ -1373,7 +1389,7 @@ export class DatastoreAdminClient { this._log.info('deleteIndex long-running'); const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( - {name}, + { name }, ); const [operation] = await this.operationsClient.getOperation(request); const decodeOperation = new this._gaxModule.Operation( @@ -1476,9 +1492,9 @@ export class DatastoreAdminClient { options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = this._gaxModule.routingHeader.fromParams({ - project_id: request.projectId ?? '', + project_id: request.projectId?.toString() ?? '', }); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); const wrappedCallback: @@ -1543,11 +1559,11 @@ export class DatastoreAdminClient { options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = this._gaxModule.routingHeader.fromParams({ - project_id: request.projectId ?? '', + project_id: request.projectId?.toString() ?? '', }); const defaultCallSettings = this._defaults['listIndexes']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('listIndexes stream %j', request); @@ -1594,11 +1610,11 @@ export class DatastoreAdminClient { options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = this._gaxModule.routingHeader.fromParams({ - project_id: request.projectId ?? '', + project_id: request.projectId?.toString() ?? '', }); const defaultCallSettings = this._defaults['listIndexes']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => { + this.initialize().catch((err) => { throw err; }); this._log.info('listIndexes iterate %j', request); @@ -1774,7 +1790,6 @@ export class DatastoreAdminClient { }); return this.operationsClient.cancelOperation(request, options, callback); } - /** * Deletes a long-running operation. This method indicates that the client is * no longer interested in the operation result. It does not cancel the @@ -1840,11 +1855,11 @@ export class DatastoreAdminClient { */ close(): Promise { if (this.datastoreAdminStub && !this._terminated) { - return this.datastoreAdminStub.then(stub => { + return this.datastoreAdminStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); - this.operationsClient.close(); + void this.operationsClient.close(); }); } return Promise.resolve(); diff --git a/handwritten/datastore/src/v1/datastore_client.ts b/handwritten/datastore/src/v1/datastore_client.ts index 1b1158315ea8..e830c956aea5 100644 --- a/handwritten/datastore/src/v1/datastore_client.ts +++ b/handwritten/datastore/src/v1/datastore_client.ts @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -28,7 +28,7 @@ import type { import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -56,7 +56,7 @@ export class DatastoreClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('datastore'); @@ -69,9 +69,9 @@ export class DatastoreClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; + innerApiCalls: { [name: string]: Function }; operationsClient: gax.OperationsClient; - datastoreStub?: Promise<{[name: string]: Function}>; + datastoreStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of DatastoreClient. @@ -147,7 +147,7 @@ export class DatastoreClient { const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // Request numeric enum values if REST transport is used. opts.numericEnums = true; @@ -203,7 +203,7 @@ export class DatastoreClient { // Load the applicable protos. this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); - const protoFilesRoot = this._gaxModule.protobuf.Root.fromJSON(jsonProtos); + const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); // This API contains "long-running operations", which return a // an Operation object that allows for tracking of the operation, // rather than holding a request open. @@ -243,7 +243,7 @@ export class DatastoreClient { 'google.datastore.v1.Datastore', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')}, + { 'x-goog-api-client': clientHeader.join(' ') }, ); // Set up a dictionary of "inner API calls"; the core implementation @@ -283,7 +283,7 @@ export class DatastoreClient { (this._protos as any).google.datastore.v1.Datastore, this._opts, this._providedCustomServicePath, - ) as Promise<{[method: string]: Function}>; + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -299,7 +299,7 @@ export class DatastoreClient { ]; for (const methodName of datastoreStubMethods) { const callPromise = this.datastoreStub.then( - stub => + (stub) => (...args: Array<{}>) => { if (this._terminated) { return Promise.reject('The client has already been closed.'); @@ -504,14 +504,14 @@ export class DatastoreClient { options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - const routingParameter = {}; + let routingParameter = {}; { const fieldValue = request.projectId; if (fieldValue !== undefined && fieldValue !== null) { const match = fieldValue.toString().match(RegExp('(?.*)')); if (match) { const parameterValue = match.groups?.['project_id'] ?? fieldValue; - Object.assign(routingParameter, {project_id: parameterValue}); + Object.assign(routingParameter, { project_id: parameterValue }); } } } @@ -521,13 +521,13 @@ export class DatastoreClient { const match = fieldValue.toString().match(RegExp('(?.*)')); 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 => { + this.initialize().catch((err) => { throw err; }); this._log.info('lookup request %j', request); @@ -554,7 +554,23 @@ export class DatastoreClient { this._log.info('lookup response %j', response); return [response, options, rawResponse]; }, - ); + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Queries for entities. @@ -656,14 +672,14 @@ export class DatastoreClient { options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - const routingParameter = {}; + let routingParameter = {}; { const fieldValue = request.projectId; if (fieldValue !== undefined && fieldValue !== null) { const match = fieldValue.toString().match(RegExp('(?.*)')); if (match) { const parameterValue = match.groups?.['project_id'] ?? fieldValue; - Object.assign(routingParameter, {project_id: parameterValue}); + Object.assign(routingParameter, { project_id: parameterValue }); } } } @@ -673,13 +689,13 @@ export class DatastoreClient { const match = fieldValue.toString().match(RegExp('(?.*)')); 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 => { + this.initialize().catch((err) => { throw err; }); this._log.info('runQuery request %j', request); @@ -706,7 +722,23 @@ export class DatastoreClient { this._log.info('runQuery response %j', response); return [response, options, rawResponse]; }, - ); + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Runs an aggregation query. @@ -804,14 +836,14 @@ export class DatastoreClient { options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - const routingParameter = {}; + let routingParameter = {}; { const fieldValue = request.projectId; if (fieldValue !== undefined && fieldValue !== null) { const match = fieldValue.toString().match(RegExp('(?.*)')); if (match) { const parameterValue = match.groups?.['project_id'] ?? fieldValue; - Object.assign(routingParameter, {project_id: parameterValue}); + Object.assign(routingParameter, { project_id: parameterValue }); } } } @@ -821,13 +853,13 @@ export class DatastoreClient { const match = fieldValue.toString().match(RegExp('(?.*)')); 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 => { + this.initialize().catch((err) => { throw err; }); this._log.info('runAggregationQuery request %j', request); @@ -856,7 +888,23 @@ export class DatastoreClient { this._log.info('runAggregationQuery response %j', response); return [response, options, rawResponse]; }, - ); + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Begins a new transaction. @@ -942,14 +990,14 @@ export class DatastoreClient { options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - const routingParameter = {}; + let routingParameter = {}; { const fieldValue = request.projectId; if (fieldValue !== undefined && fieldValue !== null) { const match = fieldValue.toString().match(RegExp('(?.*)')); if (match) { const parameterValue = match.groups?.['project_id'] ?? fieldValue; - Object.assign(routingParameter, {project_id: parameterValue}); + Object.assign(routingParameter, { project_id: parameterValue }); } } } @@ -959,13 +1007,13 @@ export class DatastoreClient { const match = fieldValue.toString().match(RegExp('(?.*)')); 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 => { + this.initialize().catch((err) => { throw err; }); this._log.info('beginTransaction request %j', request); @@ -994,7 +1042,23 @@ export class DatastoreClient { this._log.info('beginTransaction response %j', response); return [response, options, rawResponse]; }, - ); + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Commits a transaction, optionally creating, deleting or modifying some @@ -1102,14 +1166,14 @@ export class DatastoreClient { options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - const routingParameter = {}; + let routingParameter = {}; { const fieldValue = request.projectId; if (fieldValue !== undefined && fieldValue !== null) { const match = fieldValue.toString().match(RegExp('(?.*)')); if (match) { const parameterValue = match.groups?.['project_id'] ?? fieldValue; - Object.assign(routingParameter, {project_id: parameterValue}); + Object.assign(routingParameter, { project_id: parameterValue }); } } } @@ -1119,13 +1183,13 @@ export class DatastoreClient { const match = fieldValue.toString().match(RegExp('(?.*)')); 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 => { + this.initialize().catch((err) => { throw err; }); this._log.info('commit request %j', request); @@ -1152,7 +1216,23 @@ export class DatastoreClient { this._log.info('commit response %j', response); return [response, options, rawResponse]; }, - ); + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Rolls back a transaction. @@ -1237,14 +1317,14 @@ export class DatastoreClient { options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - const routingParameter = {}; + let routingParameter = {}; { const fieldValue = request.projectId; if (fieldValue !== undefined && fieldValue !== null) { const match = fieldValue.toString().match(RegExp('(?.*)')); if (match) { const parameterValue = match.groups?.['project_id'] ?? fieldValue; - Object.assign(routingParameter, {project_id: parameterValue}); + Object.assign(routingParameter, { project_id: parameterValue }); } } } @@ -1254,13 +1334,13 @@ export class DatastoreClient { const match = fieldValue.toString().match(RegExp('(?.*)')); 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 => { + this.initialize().catch((err) => { throw err; }); this._log.info('rollback request %j', request); @@ -1287,7 +1367,23 @@ export class DatastoreClient { this._log.info('rollback response %j', response); return [response, options, rawResponse]; }, - ); + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Allocates IDs for the given keys, which is useful for referencing an entity @@ -1373,14 +1469,14 @@ export class DatastoreClient { options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - const routingParameter = {}; + let routingParameter = {}; { const fieldValue = request.projectId; if (fieldValue !== undefined && fieldValue !== null) { const match = fieldValue.toString().match(RegExp('(?.*)')); if (match) { const parameterValue = match.groups?.['project_id'] ?? fieldValue; - Object.assign(routingParameter, {project_id: parameterValue}); + Object.assign(routingParameter, { project_id: parameterValue }); } } } @@ -1390,13 +1486,13 @@ export class DatastoreClient { const match = fieldValue.toString().match(RegExp('(?.*)')); 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 => { + this.initialize().catch((err) => { throw err; }); this._log.info('allocateIds request %j', request); @@ -1423,7 +1519,23 @@ export class DatastoreClient { this._log.info('allocateIds response %j', response); return [response, options, rawResponse]; }, - ); + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Prevents the supplied keys' IDs from being auto-allocated by Cloud @@ -1509,14 +1621,14 @@ export class DatastoreClient { options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - const routingParameter = {}; + let routingParameter = {}; { const fieldValue = request.projectId; if (fieldValue !== undefined && fieldValue !== null) { const match = fieldValue.toString().match(RegExp('(?.*)')); if (match) { const parameterValue = match.groups?.['project_id'] ?? fieldValue; - Object.assign(routingParameter, {project_id: parameterValue}); + Object.assign(routingParameter, { project_id: parameterValue }); } } } @@ -1526,13 +1638,13 @@ export class DatastoreClient { const match = fieldValue.toString().match(RegExp('(?.*)')); 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 => { + this.initialize().catch((err) => { throw err; }); this._log.info('reserveIds request %j', request); @@ -1559,7 +1671,23 @@ export class DatastoreClient { this._log.info('reserveIds response %j', response); return [response, options, rawResponse]; }, - ); + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** @@ -1728,7 +1856,6 @@ export class DatastoreClient { }); return this.operationsClient.cancelOperation(request, options, callback); } - /** * Deletes a long-running operation. This method indicates that the client is * no longer interested in the operation result. It does not cancel the @@ -1794,11 +1921,11 @@ export class DatastoreClient { */ close(): Promise { if (this.datastoreStub && !this._terminated) { - return this.datastoreStub.then(stub => { + return this.datastoreStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); - this.operationsClient.close(); + void this.operationsClient.close(); }); } return Promise.resolve(); diff --git a/handwritten/datastore/system-test/fixtures/sample/src/index.js b/handwritten/datastore/system-test/fixtures/sample/src/index.js index 1cb393060623..ee7482f4b6ee 100644 --- a/handwritten/datastore/system-test/fixtures/sample/src/index.js +++ b/handwritten/datastore/system-test/fixtures/sample/src/index.js @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + /* eslint-disable node/no-missing-require, no-unused-vars */ const datastore = require('@google-cloud/datastore'); diff --git a/handwritten/datastore/system-test/fixtures/sample/src/index.ts b/handwritten/datastore/system-test/fixtures/sample/src/index.ts index c0c27e781f15..0a18405b51ed 100644 --- a/handwritten/datastore/system-test/fixtures/sample/src/index.ts +++ b/handwritten/datastore/system-test/fixtures/sample/src/index.ts @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {Datastore} from '@google-cloud/datastore'; +import { Datastore } from '@google-cloud/datastore'; // check that the client class type name can be used function doStuffWithDatastore(client: Datastore) { diff --git a/handwritten/datastore/system-test/install.ts b/handwritten/datastore/system-test/install.ts index 5257a7ba101c..ccf167042d2e 100644 --- a/handwritten/datastore/system-test/install.ts +++ b/handwritten/datastore/system-test/install.ts @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,9 +16,9 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { it('TypeScript code', async function () { @@ -41,7 +41,7 @@ describe('📦 pack-n-play test', () => { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - ts: readFileSync( + cjs: readFileSync( './system-test/fixtures/sample/src/index.js', ).toString(), }, diff --git a/handwritten/datastore/test/gapic_datastore_admin_v1.ts b/handwritten/datastore/test/gapic_datastore_admin_v1.ts index 33169355de8c..55cd3968baad 100644 --- a/handwritten/datastore/test/gapic_datastore_admin_v1.ts +++ b/handwritten/datastore/test/gapic_datastore_admin_v1.ts @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,13 +19,13 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as datastoreadminModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects @@ -45,7 +45,7 @@ function getTypeDefaultValue(typeName: string, fields: string[]) { function generateSampleMessage(instance: T) { const filledObject = ( instance.constructor as typeof protobuf.Message - ).toObject(instance as protobuf.Message, {defaults: true}); + ).toObject(instance as protobuf.Message, { defaults: true }); return (instance.constructor as typeof protobuf.Message).fromObject( filledObject, ) as T; @@ -149,9 +149,9 @@ function stubAsyncIterationCall( return Promise.reject(error); } if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); + return Promise.resolve({ done: true, value: undefined }); } - return Promise.resolve({done: false, value: responses![counter++]}); + return Promise.resolve({ done: false, value: responses![counter++] }); }, }; }, @@ -271,7 +271,7 @@ describe('v1.DatastoreAdminClient', () => { it('has initialize method and supports deferred initialization', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); assert.strictEqual(client.datastoreAdminStub, undefined); @@ -279,35 +279,45 @@ describe('v1.DatastoreAdminClient', () => { assert(client.datastoreAdminStub); }); - it('has close method for the initialized client', done => { + it('has close method for the initialized client', (done) => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize().catch((err: any) => { + client.initialize().catch((err) => { throw err; }); assert(client.datastoreAdminStub); - client.close().then(() => { - done(); - }); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; + }); }); - it('has close method for the non-initialized client', done => { + it('has close method for the non-initialized client', (done) => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); assert.strictEqual(client.datastoreAdminStub, undefined); - client.close().then(() => { - done(); - }); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; + }); }); it('has getProjectId method', async () => { const fakeProjectId = 'fake-project-id'; const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); @@ -319,7 +329,7 @@ describe('v1.DatastoreAdminClient', () => { it('has getProjectId method with callback', async () => { const fakeProjectId = 'fake-project-id'; const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); client.auth.getProjectId = sinon @@ -342,7 +352,7 @@ describe('v1.DatastoreAdminClient', () => { describe('getIndex', () => { it('invokes getIndex without error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -378,7 +388,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes getIndex without error using callback', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -430,7 +440,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes getIndex with error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -463,7 +473,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes getIndex with closed client', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -481,7 +491,9 @@ describe('v1.DatastoreAdminClient', () => { ); request.indexId = defaultValue2; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.getIndex(request), expectedError); }); }); @@ -489,7 +501,7 @@ describe('v1.DatastoreAdminClient', () => { describe('exportEntities', () => { it('invokes exportEntities without error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -522,7 +534,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes exportEntities without error using callback', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -576,7 +588,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes exportEntities with call error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -607,7 +619,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes exportEntities with LRO error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -640,7 +652,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes checkExportEntitiesProgress without error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -648,8 +660,8 @@ describe('v1.DatastoreAdminClient', () => { new operationsProtos.google.longrunning.Operation(), ); expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + 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.checkExportEntitiesProgress( @@ -662,7 +674,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes checkExportEntitiesProgress with error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -683,7 +695,7 @@ describe('v1.DatastoreAdminClient', () => { describe('importEntities', () => { it('invokes importEntities without error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -716,7 +728,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes importEntities without error using callback', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -770,7 +782,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes importEntities with call error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -801,7 +813,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes importEntities with LRO error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -834,7 +846,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes checkImportEntitiesProgress without error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -842,8 +854,8 @@ describe('v1.DatastoreAdminClient', () => { new operationsProtos.google.longrunning.Operation(), ); expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + 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.checkImportEntitiesProgress( @@ -856,7 +868,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes checkImportEntitiesProgress with error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -877,7 +889,7 @@ describe('v1.DatastoreAdminClient', () => { describe('createIndex', () => { it('invokes createIndex without error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -909,7 +921,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes createIndex without error using callback', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -963,7 +975,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes createIndex with call error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -994,7 +1006,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes createIndex with LRO error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1027,7 +1039,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes checkCreateIndexProgress without error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1035,8 +1047,8 @@ describe('v1.DatastoreAdminClient', () => { new operationsProtos.google.longrunning.Operation(), ); expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + 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( @@ -1049,7 +1061,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes checkCreateIndexProgress with error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1067,7 +1079,7 @@ describe('v1.DatastoreAdminClient', () => { describe('deleteIndex', () => { it('invokes deleteIndex without error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1104,7 +1116,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes deleteIndex without error using callback', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1163,7 +1175,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes deleteIndex with call error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1199,7 +1211,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes deleteIndex with LRO error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1237,7 +1249,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes checkDeleteIndexProgress without error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1245,8 +1257,8 @@ describe('v1.DatastoreAdminClient', () => { new operationsProtos.google.longrunning.Operation(), ); expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + 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.checkDeleteIndexProgress( @@ -1259,7 +1271,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes checkDeleteIndexProgress with error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1277,7 +1289,7 @@ describe('v1.DatastoreAdminClient', () => { describe('listIndexes', () => { it('invokes listIndexes without error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1310,7 +1322,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes listIndexes without error using callback', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1359,7 +1371,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes listIndexes with error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1390,7 +1402,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes listIndexesStream without error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1444,7 +1456,7 @@ describe('v1.DatastoreAdminClient', () => { it('invokes listIndexesStream with error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1495,7 +1507,7 @@ describe('v1.DatastoreAdminClient', () => { it('uses async iteration with listIndexes without error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1538,7 +1550,7 @@ describe('v1.DatastoreAdminClient', () => { it('uses async iteration with listIndexes with error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1581,7 +1593,7 @@ describe('v1.DatastoreAdminClient', () => { describe('getOperation', () => { it('invokes getOperation without error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1602,7 +1614,7 @@ describe('v1.DatastoreAdminClient', () => { }); it('invokes getOperation without error using callback', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); const request = generateSampleMessage( @@ -1615,20 +1627,24 @@ describe('v1.DatastoreAdminClient', () => { .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); - } - }, - ); + 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); @@ -1636,7 +1652,7 @@ describe('v1.DatastoreAdminClient', () => { }); it('invokes getOperation with error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); const request = generateSampleMessage( @@ -1660,7 +1676,7 @@ describe('v1.DatastoreAdminClient', () => { describe('cancelOperation', () => { it('invokes cancelOperation without error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1682,7 +1698,7 @@ describe('v1.DatastoreAdminClient', () => { }); it('invokes cancelOperation without error using callback', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); const request = generateSampleMessage( @@ -1695,20 +1711,24 @@ describe('v1.DatastoreAdminClient', () => { .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); - } - }, - ); + 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); @@ -1716,7 +1736,7 @@ describe('v1.DatastoreAdminClient', () => { }); it('invokes cancelOperation with error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); const request = generateSampleMessage( @@ -1740,7 +1760,7 @@ describe('v1.DatastoreAdminClient', () => { describe('deleteOperation', () => { it('invokes deleteOperation without error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1762,7 +1782,7 @@ describe('v1.DatastoreAdminClient', () => { }); it('invokes deleteOperation without error using callback', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); const request = generateSampleMessage( @@ -1775,20 +1795,24 @@ describe('v1.DatastoreAdminClient', () => { .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); - } - }, - ); + 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); @@ -1796,7 +1820,7 @@ describe('v1.DatastoreAdminClient', () => { }); it('invokes deleteOperation with error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); const request = generateSampleMessage( @@ -1820,7 +1844,7 @@ describe('v1.DatastoreAdminClient', () => { describe('listOperationsAsync', () => { it('uses async iteration with listOperations without error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); const request = generateSampleMessage( @@ -1855,7 +1879,7 @@ describe('v1.DatastoreAdminClient', () => { }); it('uses async iteration with listOperations with error', async () => { const client = new datastoreadminModule.v1.DatastoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); diff --git a/handwritten/datastore/test/gapic_datastore_v1.ts b/handwritten/datastore/test/gapic_datastore_v1.ts index 23c97b88c0ed..5d08da074b51 100644 --- a/handwritten/datastore/test/gapic_datastore_v1.ts +++ b/handwritten/datastore/test/gapic_datastore_v1.ts @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,11 +19,11 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as datastoreModule from '../src'; -import {protobuf, operationsProtos} from 'google-gax'; +import { protobuf, operationsProtos } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects @@ -43,7 +43,7 @@ function getTypeDefaultValue(typeName: string, fields: string[]) { function generateSampleMessage(instance: T) { const filledObject = ( instance.constructor as typeof protobuf.Message - ).toObject(instance as protobuf.Message, {defaults: true}); + ).toObject(instance as protobuf.Message, { defaults: true }); return (instance.constructor as typeof protobuf.Message).fromObject( filledObject, ) as T; @@ -77,9 +77,9 @@ function stubAsyncIterationCall( return Promise.reject(error); } if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); + return Promise.resolve({ done: true, value: undefined }); } - return Promise.resolve({done: false, value: responses![counter++]}); + return Promise.resolve({ done: false, value: responses![counter++] }); }, }; }, @@ -197,7 +197,7 @@ describe('v1.DatastoreClient', () => { it('has initialize method and supports deferred initialization', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); assert.strictEqual(client.datastoreStub, undefined); @@ -205,35 +205,45 @@ describe('v1.DatastoreClient', () => { assert(client.datastoreStub); }); - it('has close method for the initialized client', done => { + it('has close method for the initialized client', (done) => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize().catch((err: any) => { + client.initialize().catch((err) => { throw err; }); assert(client.datastoreStub); - client.close().then(() => { - done(); - }); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; + }); }); - it('has close method for the non-initialized client', done => { + it('has close method for the non-initialized client', (done) => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); assert.strictEqual(client.datastoreStub, undefined); - client.close().then(() => { - done(); - }); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; + }); }); it('has getProjectId method', async () => { const fakeProjectId = 'fake-project-id'; const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); @@ -245,7 +255,7 @@ describe('v1.DatastoreClient', () => { it('has getProjectId method with callback', async () => { const fakeProjectId = 'fake-project-id'; const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); client.auth.getProjectId = sinon @@ -268,7 +278,7 @@ describe('v1.DatastoreClient', () => { describe('lookup', () => { it('invokes lookup without error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -296,7 +306,7 @@ describe('v1.DatastoreClient', () => { it('invokes lookup without error using callback', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -340,7 +350,7 @@ describe('v1.DatastoreClient', () => { it('invokes lookup with error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -365,7 +375,7 @@ describe('v1.DatastoreClient', () => { it('invokes lookup with closed client', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -375,7 +385,9 @@ describe('v1.DatastoreClient', () => { // path template is empty request.databaseId = 'value'; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.lookup(request), expectedError); }); }); @@ -383,7 +395,7 @@ describe('v1.DatastoreClient', () => { describe('runQuery', () => { it('invokes runQuery without error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -411,7 +423,7 @@ describe('v1.DatastoreClient', () => { it('invokes runQuery without error using callback', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -455,7 +467,7 @@ describe('v1.DatastoreClient', () => { it('invokes runQuery with error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -480,7 +492,7 @@ describe('v1.DatastoreClient', () => { it('invokes runQuery with closed client', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -490,7 +502,9 @@ describe('v1.DatastoreClient', () => { // path template is empty request.databaseId = 'value'; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.runQuery(request), expectedError); }); }); @@ -498,7 +512,7 @@ describe('v1.DatastoreClient', () => { describe('runAggregationQuery', () => { it('invokes runAggregationQuery without error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -527,7 +541,7 @@ describe('v1.DatastoreClient', () => { it('invokes runAggregationQuery without error using callback', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -571,7 +585,7 @@ describe('v1.DatastoreClient', () => { it('invokes runAggregationQuery with error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -599,7 +613,7 @@ describe('v1.DatastoreClient', () => { it('invokes runAggregationQuery with closed client', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -609,7 +623,9 @@ describe('v1.DatastoreClient', () => { // path template is empty request.databaseId = 'value'; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.runAggregationQuery(request), expectedError); }); }); @@ -617,7 +633,7 @@ describe('v1.DatastoreClient', () => { describe('beginTransaction', () => { it('invokes beginTransaction without error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -645,7 +661,7 @@ describe('v1.DatastoreClient', () => { it('invokes beginTransaction without error using callback', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -689,7 +705,7 @@ describe('v1.DatastoreClient', () => { it('invokes beginTransaction with error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -717,7 +733,7 @@ describe('v1.DatastoreClient', () => { it('invokes beginTransaction with closed client', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -727,7 +743,9 @@ describe('v1.DatastoreClient', () => { // path template is empty request.databaseId = 'value'; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.beginTransaction(request), expectedError); }); }); @@ -735,7 +753,7 @@ describe('v1.DatastoreClient', () => { describe('commit', () => { it('invokes commit without error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -763,7 +781,7 @@ describe('v1.DatastoreClient', () => { it('invokes commit without error using callback', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -807,7 +825,7 @@ describe('v1.DatastoreClient', () => { it('invokes commit with error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -832,7 +850,7 @@ describe('v1.DatastoreClient', () => { it('invokes commit with closed client', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -842,7 +860,9 @@ describe('v1.DatastoreClient', () => { // path template is empty request.databaseId = 'value'; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.commit(request), expectedError); }); }); @@ -850,7 +870,7 @@ describe('v1.DatastoreClient', () => { describe('rollback', () => { it('invokes rollback without error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -878,7 +898,7 @@ describe('v1.DatastoreClient', () => { it('invokes rollback without error using callback', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -922,7 +942,7 @@ describe('v1.DatastoreClient', () => { it('invokes rollback with error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -947,7 +967,7 @@ describe('v1.DatastoreClient', () => { it('invokes rollback with closed client', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -957,7 +977,9 @@ describe('v1.DatastoreClient', () => { // path template is empty request.databaseId = 'value'; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.rollback(request), expectedError); }); }); @@ -965,7 +987,7 @@ describe('v1.DatastoreClient', () => { describe('allocateIds', () => { it('invokes allocateIds without error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -993,7 +1015,7 @@ describe('v1.DatastoreClient', () => { it('invokes allocateIds without error using callback', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1037,7 +1059,7 @@ describe('v1.DatastoreClient', () => { it('invokes allocateIds with error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1065,7 +1087,7 @@ describe('v1.DatastoreClient', () => { it('invokes allocateIds with closed client', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1075,7 +1097,9 @@ describe('v1.DatastoreClient', () => { // path template is empty request.databaseId = 'value'; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.allocateIds(request), expectedError); }); }); @@ -1083,7 +1107,7 @@ describe('v1.DatastoreClient', () => { describe('reserveIds', () => { it('invokes reserveIds without error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1111,7 +1135,7 @@ describe('v1.DatastoreClient', () => { it('invokes reserveIds without error using callback', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1155,7 +1179,7 @@ describe('v1.DatastoreClient', () => { it('invokes reserveIds with error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1183,7 +1207,7 @@ describe('v1.DatastoreClient', () => { it('invokes reserveIds with closed client', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1193,14 +1217,16 @@ describe('v1.DatastoreClient', () => { // path template is empty request.databaseId = 'value'; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.reserveIds(request), expectedError); }); }); describe('getOperation', () => { it('invokes getOperation without error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1221,7 +1247,7 @@ describe('v1.DatastoreClient', () => { }); it('invokes getOperation without error using callback', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); const request = generateSampleMessage( @@ -1234,20 +1260,24 @@ describe('v1.DatastoreClient', () => { .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); - } - }, - ); + 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); @@ -1255,7 +1285,7 @@ describe('v1.DatastoreClient', () => { }); it('invokes getOperation with error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); const request = generateSampleMessage( @@ -1279,7 +1309,7 @@ describe('v1.DatastoreClient', () => { describe('cancelOperation', () => { it('invokes cancelOperation without error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1301,7 +1331,7 @@ describe('v1.DatastoreClient', () => { }); it('invokes cancelOperation without error using callback', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); const request = generateSampleMessage( @@ -1314,20 +1344,24 @@ describe('v1.DatastoreClient', () => { .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); - } - }, - ); + 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); @@ -1335,7 +1369,7 @@ describe('v1.DatastoreClient', () => { }); it('invokes cancelOperation with error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); const request = generateSampleMessage( @@ -1359,7 +1393,7 @@ describe('v1.DatastoreClient', () => { describe('deleteOperation', () => { it('invokes deleteOperation without error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); @@ -1381,7 +1415,7 @@ describe('v1.DatastoreClient', () => { }); it('invokes deleteOperation without error using callback', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); const request = generateSampleMessage( @@ -1394,20 +1428,24 @@ describe('v1.DatastoreClient', () => { .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); - } - }, - ); + 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); @@ -1415,7 +1453,7 @@ describe('v1.DatastoreClient', () => { }); it('invokes deleteOperation with error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); const request = generateSampleMessage( @@ -1439,7 +1477,7 @@ describe('v1.DatastoreClient', () => { describe('listOperationsAsync', () => { it('uses async iteration with listOperations without error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); const request = generateSampleMessage( @@ -1474,7 +1512,7 @@ describe('v1.DatastoreClient', () => { }); it('uses async iteration with listOperations with error', async () => { const client = new datastoreModule.v1.DatastoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); await client.initialize(); diff --git a/handwritten/datastore/tsconfig.json b/handwritten/datastore/tsconfig.json index a4b71611d51f..ca73e7bfc824 100644 --- a/handwritten/datastore/tsconfig.json +++ b/handwritten/datastore/tsconfig.json @@ -5,7 +5,7 @@ "outDir": "build", "resolveJsonModule": true, "lib": [ - "es2018", + "es2023", "dom" ] }, @@ -15,9 +15,8 @@ "test/*.ts", "test/**/*.ts", "system-test/*.ts", - "mock-server/datastore-server.ts", - "src/v1/datastore_client_config.json", - "protos/protos.json", - "src/v1/datastore_admin_client_config.json" + "src/**/*.json", + "samples/**/*.json", + "protos/protos.json" ] } diff --git a/handwritten/datastore/webpack.config.js b/handwritten/datastore/webpack.config.js index f37985e35894..6df22195e271 100644 --- a/handwritten/datastore/webpack.config.js +++ b/handwritten/datastore/webpack.config.js @@ -36,27 +36,27 @@ module.exports = { { test: /\.tsx?$/, use: 'ts-loader', - exclude: /node_modules/, + exclude: /node_modules/ }, { test: /node_modules[\\/]@grpc[\\/]grpc-js/, - use: 'null-loader', + use: 'null-loader' }, { test: /node_modules[\\/]grpc/, - use: 'null-loader', + use: 'null-loader' }, { test: /node_modules[\\/]retry-request/, - use: 'null-loader', + use: 'null-loader' }, { test: /node_modules[\\/]https?-proxy-agent/, - use: 'null-loader', + use: 'null-loader' }, { test: /node_modules[\\/]gtoken/, - use: 'null-loader', + use: 'null-loader' }, ], }, diff --git a/handwritten/logging/.OwlBot.yaml b/handwritten/logging/.OwlBot.yaml index 360ece41c701..7f3806ae0318 100644 --- a/handwritten/logging/.OwlBot.yaml +++ b/handwritten/logging/.OwlBot.yaml @@ -1,10 +1,10 @@ -# Copyright 2021 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. # You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# 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, @@ -12,13 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. - -deep-remove-regex: - - /owl-bot-staging - deep-copy-regex: - - source: /google/logging/(v.*)/.*-nodejs - dest: /owl-bot-staging/logging/$1 - -begin-after-commit-hash: fb91803ccef5d7c695139b22788b309e2197856b + - source: /google/logging/google-logging-nodejs + dest: /owl-bot-staging/google-logging +api-name: logging \ No newline at end of file diff --git a/handwritten/logging/.jsdoc.js b/handwritten/logging/.jsdoc.js index 1f6bfb791904..999b4824630f 100644 --- a/handwritten/logging/.jsdoc.js +++ b/handwritten/logging/.jsdoc.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -40,7 +40,7 @@ module.exports = { includePattern: '\\.js$' }, templates: { - copyright: 'Copyright 2024 Google LLC', + copyright: 'Copyright 2026 Google LLC', includeDate: false, sourceFiles: false, systemName: '@google-cloud/logging', diff --git a/handwritten/logging/protos/google/logging/type/http_request.proto b/handwritten/logging/protos/google/logging/type/http_request.proto index fa2dd64e8346..b31522b69c7c 100644 --- a/handwritten/logging/protos/google/logging/type/http_request.proto +++ b/handwritten/logging/protos/google/logging/type/http_request.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/handwritten/logging/protos/google/logging/type/log_severity.proto b/handwritten/logging/protos/google/logging/type/log_severity.proto index 96ff874688ab..406b8173a3aa 100644 --- a/handwritten/logging/protos/google/logging/type/log_severity.proto +++ b/handwritten/logging/protos/google/logging/type/log_severity.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/handwritten/logging/protos/google/logging/v2/log_entry.proto b/handwritten/logging/protos/google/logging/v2/log_entry.proto index 2404219f6aa2..820b047b5735 100644 --- a/handwritten/logging/protos/google/logging/v2/log_entry.proto +++ b/handwritten/logging/protos/google/logging/v2/log_entry.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/handwritten/logging/protos/google/logging/v2/logging.proto b/handwritten/logging/protos/google/logging/v2/logging.proto index cd686e9ff393..e984d6ec0d5b 100644 --- a/handwritten/logging/protos/google/logging/v2/logging.proto +++ b/handwritten/logging/protos/google/logging/v2/logging.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/handwritten/logging/protos/google/logging/v2/logging_config.proto b/handwritten/logging/protos/google/logging/v2/logging_config.proto index d914df1bae5b..05ed940b3972 100644 --- a/handwritten/logging/protos/google/logging/v2/logging_config.proto +++ b/handwritten/logging/protos/google/logging/v2/logging_config.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/handwritten/logging/protos/google/logging/v2/logging_metrics.proto b/handwritten/logging/protos/google/logging/v2/logging_metrics.proto index a387ef2b4a56..a0575cff4471 100644 --- a/handwritten/logging/protos/google/logging/v2/logging_metrics.proto +++ b/handwritten/logging/protos/google/logging/v2/logging_metrics.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/handwritten/logging/samples/generated/v2/config_service_v2.copy_log_entries.js b/handwritten/logging/samples/generated/v2/config_service_v2.copy_log_entries.js index cea748d5f793..bc4d30d85da4 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.copy_log_entries.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.copy_log_entries.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(name, destination) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.create_bucket.js b/handwritten/logging/samples/generated/v2/config_service_v2.create_bucket.js index 84fd76b4d59e..a78633507942 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.create_bucket.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.create_bucket.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(parent, bucketId, bucket) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.create_bucket_async.js b/handwritten/logging/samples/generated/v2/config_service_v2.create_bucket_async.js index 9d26cadd5c44..0cc98416c00c 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.create_bucket_async.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.create_bucket_async.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(parent, bucketId, bucket) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.create_exclusion.js b/handwritten/logging/samples/generated/v2/config_service_v2.create_exclusion.js index a5742a7b24bf..b1e6a0908c8a 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.create_exclusion.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.create_exclusion.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(parent, exclusion) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.create_link.js b/handwritten/logging/samples/generated/v2/config_service_v2.create_link.js index 31bcbe9b5419..b2923477952f 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.create_link.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.create_link.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(parent, link, linkId) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.create_sink.js b/handwritten/logging/samples/generated/v2/config_service_v2.create_sink.js index c210d088c8c3..b95361847c7a 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.create_sink.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.create_sink.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(parent, sink) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.create_view.js b/handwritten/logging/samples/generated/v2/config_service_v2.create_view.js index f7aa3784891c..30c237aa11d6 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.create_view.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.create_view.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(parent, viewId, view) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.delete_bucket.js b/handwritten/logging/samples/generated/v2/config_service_v2.delete_bucket.js index 7c3e0d3e7de7..94443cc58703 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.delete_bucket.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.delete_bucket.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(name) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.delete_exclusion.js b/handwritten/logging/samples/generated/v2/config_service_v2.delete_exclusion.js index d0e11e399978..c6b6b2d28cc6 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.delete_exclusion.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.delete_exclusion.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(name) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.delete_link.js b/handwritten/logging/samples/generated/v2/config_service_v2.delete_link.js index 61e21816f2e2..c8065914749c 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.delete_link.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.delete_link.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(name) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.delete_sink.js b/handwritten/logging/samples/generated/v2/config_service_v2.delete_sink.js index 57cd54a80bff..18088005bc9c 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.delete_sink.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.delete_sink.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(sinkName) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.delete_view.js b/handwritten/logging/samples/generated/v2/config_service_v2.delete_view.js index 4c3ac7a4844e..b99989576e74 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.delete_view.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.delete_view.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(name) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.get_bucket.js b/handwritten/logging/samples/generated/v2/config_service_v2.get_bucket.js index 1bcf694211d1..f85aa92d6aa0 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.get_bucket.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.get_bucket.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(name) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.get_cmek_settings.js b/handwritten/logging/samples/generated/v2/config_service_v2.get_cmek_settings.js index 39a9c897bfec..c138860cef23 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.get_cmek_settings.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.get_cmek_settings.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(name) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.get_exclusion.js b/handwritten/logging/samples/generated/v2/config_service_v2.get_exclusion.js index 34e779244b54..a14d73f7db63 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.get_exclusion.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.get_exclusion.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(name) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.get_link.js b/handwritten/logging/samples/generated/v2/config_service_v2.get_link.js index 23afd1bbf045..54622e6ea094 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.get_link.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.get_link.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(name) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.get_settings.js b/handwritten/logging/samples/generated/v2/config_service_v2.get_settings.js index 2f157e764f22..578f4e52a706 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.get_settings.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.get_settings.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(name) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.get_sink.js b/handwritten/logging/samples/generated/v2/config_service_v2.get_sink.js index a27ea5ed874a..5e0e2d045a7a 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.get_sink.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.get_sink.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(sinkName) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.get_view.js b/handwritten/logging/samples/generated/v2/config_service_v2.get_view.js index f6851c090f33..1e7a6c232788 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.get_view.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.get_view.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(name) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.list_buckets.js b/handwritten/logging/samples/generated/v2/config_service_v2.list_buckets.js index eecf060419f9..cea04327caf8 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.list_buckets.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.list_buckets.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(parent) { @@ -66,7 +68,7 @@ function main(parent) { // Run request const iterable = loggingClient.listBucketsAsync(request); for await (const response of iterable) { - console.log(response); + console.log(response); } } diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.list_exclusions.js b/handwritten/logging/samples/generated/v2/config_service_v2.list_exclusions.js index 213a30bb6606..91646b57072f 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.list_exclusions.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.list_exclusions.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(parent) { @@ -63,7 +65,7 @@ function main(parent) { // Run request const iterable = loggingClient.listExclusionsAsync(request); for await (const response of iterable) { - console.log(response); + console.log(response); } } diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.list_links.js b/handwritten/logging/samples/generated/v2/config_service_v2.list_links.js index 09b94f34333e..f2a67ec42075 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.list_links.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.list_links.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(parent) { @@ -60,7 +62,7 @@ function main(parent) { // Run request const iterable = loggingClient.listLinksAsync(request); for await (const response of iterable) { - console.log(response); + console.log(response); } } diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.list_sinks.js b/handwritten/logging/samples/generated/v2/config_service_v2.list_sinks.js index e48139c6bc01..502f1ca1d791 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.list_sinks.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.list_sinks.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(parent) { @@ -63,7 +65,7 @@ function main(parent) { // Run request const iterable = loggingClient.listSinksAsync(request); for await (const response of iterable) { - console.log(response); + console.log(response); } } diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.list_views.js b/handwritten/logging/samples/generated/v2/config_service_v2.list_views.js index c68583702e48..4685f8e0af57 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.list_views.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.list_views.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(parent) { @@ -60,7 +62,7 @@ function main(parent) { // Run request const iterable = loggingClient.listViewsAsync(request); for await (const response of iterable) { - console.log(response); + console.log(response); } } diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.undelete_bucket.js b/handwritten/logging/samples/generated/v2/config_service_v2.undelete_bucket.js index 4721db37b467..7621abdf21ba 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.undelete_bucket.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.undelete_bucket.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(name) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.update_bucket.js b/handwritten/logging/samples/generated/v2/config_service_v2.update_bucket.js index 0d2138d8f45a..2d727570f288 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.update_bucket.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.update_bucket.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(name, bucket, updateMask) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.update_bucket_async.js b/handwritten/logging/samples/generated/v2/config_service_v2.update_bucket_async.js index 05cdad75cef3..4748c59bf582 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.update_bucket_async.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.update_bucket_async.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(name, bucket, updateMask) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.update_cmek_settings.js b/handwritten/logging/samples/generated/v2/config_service_v2.update_cmek_settings.js index 9f60a26a743e..4372c6b45c4e 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.update_cmek_settings.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.update_cmek_settings.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(name, cmekSettings) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.update_exclusion.js b/handwritten/logging/samples/generated/v2/config_service_v2.update_exclusion.js index 90e9a1cf1e6e..9682a7fe9b5b 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.update_exclusion.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.update_exclusion.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(name, exclusion, updateMask) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.update_settings.js b/handwritten/logging/samples/generated/v2/config_service_v2.update_settings.js index 837122b5be6d..d999f34a0e8f 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.update_settings.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.update_settings.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(name, settings) { diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.update_sink.js b/handwritten/logging/samples/generated/v2/config_service_v2.update_sink.js index bb78c55d0356..54b35fc59339 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.update_sink.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.update_sink.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(sinkName, sink) { @@ -43,7 +45,7 @@ function main(sinkName, sink) { */ // const sink = {} /** - * Optional. See sinks.create google.logging.v2.ConfigServiceV2.CreateSink + * Optional. See sinks.create google.logging.v2.ConfigServiceV2.CreateSink * for a description of this field. When updating a sink, the effect of this * field on the value of `writer_identity` in the updated sink depends on both * the old and new values of this field: diff --git a/handwritten/logging/samples/generated/v2/config_service_v2.update_view.js b/handwritten/logging/samples/generated/v2/config_service_v2.update_view.js index 6717f1d8d23f..a9d9e9d5a55b 100644 --- a/handwritten/logging/samples/generated/v2/config_service_v2.update_view.js +++ b/handwritten/logging/samples/generated/v2/config_service_v2.update_view.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(name, view) { diff --git a/handwritten/logging/samples/generated/v2/logging_service_v2.delete_log.js b/handwritten/logging/samples/generated/v2/logging_service_v2.delete_log.js index 4bb09342ad39..cffc95d6c8bc 100644 --- a/handwritten/logging/samples/generated/v2/logging_service_v2.delete_log.js +++ b/handwritten/logging/samples/generated/v2/logging_service_v2.delete_log.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(logName) { diff --git a/handwritten/logging/samples/generated/v2/logging_service_v2.list_log_entries.js b/handwritten/logging/samples/generated/v2/logging_service_v2.list_log_entries.js index 1857cae39b7c..fc3ab769abd1 100644 --- a/handwritten/logging/samples/generated/v2/logging_service_v2.list_log_entries.js +++ b/handwritten/logging/samples/generated/v2/logging_service_v2.list_log_entries.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(resourceNames) { @@ -89,7 +91,7 @@ function main(resourceNames) { // Run request const iterable = loggingClient.listLogEntriesAsync(request); for await (const response of iterable) { - console.log(response); + console.log(response); } } diff --git a/handwritten/logging/samples/generated/v2/logging_service_v2.list_logs.js b/handwritten/logging/samples/generated/v2/logging_service_v2.list_logs.js index 688d137a8de2..ea22c08fb25a 100644 --- a/handwritten/logging/samples/generated/v2/logging_service_v2.list_logs.js +++ b/handwritten/logging/samples/generated/v2/logging_service_v2.list_logs.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(parent) { @@ -77,7 +79,7 @@ function main(parent) { // Run request const iterable = loggingClient.listLogsAsync(request); for await (const response of iterable) { - console.log(response); + console.log(response); } } diff --git a/handwritten/logging/samples/generated/v2/logging_service_v2.list_monitored_resource_descriptors.js b/handwritten/logging/samples/generated/v2/logging_service_v2.list_monitored_resource_descriptors.js index 60a67502e704..0d00fea56963 100644 --- a/handwritten/logging/samples/generated/v2/logging_service_v2.list_monitored_resource_descriptors.js +++ b/handwritten/logging/samples/generated/v2/logging_service_v2.list_monitored_resource_descriptors.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main() { @@ -48,13 +50,13 @@ function main() { async function callListMonitoredResourceDescriptors() { // Construct request - const request = {}; + const request = { + }; // Run request - const iterable = - loggingClient.listMonitoredResourceDescriptorsAsync(request); + const iterable = loggingClient.listMonitoredResourceDescriptorsAsync(request); for await (const response of iterable) { - console.log(response); + console.log(response); } } diff --git a/handwritten/logging/samples/generated/v2/logging_service_v2.tail_log_entries.js b/handwritten/logging/samples/generated/v2/logging_service_v2.tail_log_entries.js index c1a4e1c9e356..c45d65d04e1f 100644 --- a/handwritten/logging/samples/generated/v2/logging_service_v2.tail_log_entries.js +++ b/handwritten/logging/samples/generated/v2/logging_service_v2.tail_log_entries.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(resourceNames) { @@ -69,15 +71,9 @@ function main(resourceNames) { // Run request const stream = await loggingClient.tailLogEntries(); - stream.on('data', response => { - console.log(response); - }); - stream.on('error', err => { - throw err; - }); - stream.on('end', () => { - /* API call completed */ - }); + stream.on('data', (response) => { console.log(response) }); + stream.on('error', (err) => { throw(err) }); + stream.on('end', () => { /* API call completed */ }); stream.write(request); stream.end(); } diff --git a/handwritten/logging/samples/generated/v2/logging_service_v2.write_log_entries.js b/handwritten/logging/samples/generated/v2/logging_service_v2.write_log_entries.js index ec3cecba66ca..f6fc4e022546 100644 --- a/handwritten/logging/samples/generated/v2/logging_service_v2.write_log_entries.js +++ b/handwritten/logging/samples/generated/v2/logging_service_v2.write_log_entries.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(entries) { diff --git a/handwritten/logging/samples/generated/v2/metrics_service_v2.create_log_metric.js b/handwritten/logging/samples/generated/v2/metrics_service_v2.create_log_metric.js index 21144f293c18..8daaf940287e 100644 --- a/handwritten/logging/samples/generated/v2/metrics_service_v2.create_log_metric.js +++ b/handwritten/logging/samples/generated/v2/metrics_service_v2.create_log_metric.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(parent, metric) { diff --git a/handwritten/logging/samples/generated/v2/metrics_service_v2.delete_log_metric.js b/handwritten/logging/samples/generated/v2/metrics_service_v2.delete_log_metric.js index 162f8ab079d6..0b53ce24557c 100644 --- a/handwritten/logging/samples/generated/v2/metrics_service_v2.delete_log_metric.js +++ b/handwritten/logging/samples/generated/v2/metrics_service_v2.delete_log_metric.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(metricName) { diff --git a/handwritten/logging/samples/generated/v2/metrics_service_v2.get_log_metric.js b/handwritten/logging/samples/generated/v2/metrics_service_v2.get_log_metric.js index dde0f30f8f16..ec5d653d7b77 100644 --- a/handwritten/logging/samples/generated/v2/metrics_service_v2.get_log_metric.js +++ b/handwritten/logging/samples/generated/v2/metrics_service_v2.get_log_metric.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(metricName) { diff --git a/handwritten/logging/samples/generated/v2/metrics_service_v2.list_log_metrics.js b/handwritten/logging/samples/generated/v2/metrics_service_v2.list_log_metrics.js index 4ffff33a1bd8..84325b16285f 100644 --- a/handwritten/logging/samples/generated/v2/metrics_service_v2.list_log_metrics.js +++ b/handwritten/logging/samples/generated/v2/metrics_service_v2.list_log_metrics.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(parent) { @@ -60,7 +62,7 @@ function main(parent) { // Run request const iterable = loggingClient.listLogMetricsAsync(request); for await (const response of iterable) { - console.log(response); + console.log(response); } } diff --git a/handwritten/logging/samples/generated/v2/metrics_service_v2.update_log_metric.js b/handwritten/logging/samples/generated/v2/metrics_service_v2.update_log_metric.js index f414710dacf1..22f8e91bf828 100644 --- a/handwritten/logging/samples/generated/v2/metrics_service_v2.update_log_metric.js +++ b/handwritten/logging/samples/generated/v2/metrics_service_v2.update_log_metric.js @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** + + 'use strict'; function main(metricName, metric) { diff --git a/handwritten/logging/samples/generated/v2/snippet_metadata_google.logging.v2.json b/handwritten/logging/samples/generated/v2/snippet_metadata_google.logging.v2.json index ca8724bf4fa4..c67987806adf 100644 --- a/handwritten/logging/samples/generated/v2/snippet_metadata_google.logging.v2.json +++ b/handwritten/logging/samples/generated/v2/snippet_metadata_google.logging.v2.json @@ -1,1963 +1,1963 @@ { - "clientLibrary": { - "name": "nodejs-logging", - "version": "11.2.1", - "language": "TYPESCRIPT", - "apis": [ - { - "id": "google.logging.v2", - "version": "v2" - } - ] - }, - "snippets": [ + "clientLibrary": { + "name": "nodejs-logging", + "version": "0.1.0", + "language": "TYPESCRIPT", + "apis": [ + { + "id": "google.logging.v2", + "version": "v2" + } + ] + }, + "snippets": [ + { + "regionTag": "logging_v2_generated_ConfigServiceV2_ListBuckets_async", + "title": "logging listBuckets Sample", + "origin": "API_DEFINITION", + "description": " Lists log buckets.", + "canonical": true, + "file": "config_service_v2.list_buckets.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_ListBuckets_async", - "title": "logging listBuckets Sample", - "origin": "API_DEFINITION", - "description": " Lists log buckets.", - "canonical": true, - "file": "config_service_v2.list_buckets.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 75, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "ListBuckets", - "fullName": "google.logging.v2.ConfigServiceV2.ListBuckets", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "page_token", - "type": "TYPE_STRING" - }, - { - "name": "page_size", - "type": "TYPE_INT32" - } - ], - "resultType": ".google.logging.v2.ListBucketsResponse", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "ListBuckets", - "fullName": "google.logging.v2.ConfigServiceV2.ListBuckets", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 75, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "ListBuckets", + "fullName": "google.logging.v2.ConfigServiceV2.ListBuckets", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "page_token", + "type": "TYPE_STRING" + }, + { + "name": "page_size", + "type": "TYPE_INT32" + } + ], + "resultType": ".google.logging.v2.ListBucketsResponse", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "ListBuckets", + "fullName": "google.logging.v2.ConfigServiceV2.ListBuckets", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_GetBucket_async", + "title": "logging getBucket Sample", + "origin": "API_DEFINITION", + "description": " Gets a log bucket.", + "canonical": true, + "file": "config_service_v2.get_bucket.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_GetBucket_async", - "title": "logging getBucket Sample", - "origin": "API_DEFINITION", - "description": " Gets a log bucket.", - "canonical": true, - "file": "config_service_v2.get_bucket.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 59, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "GetBucket", - "fullName": "google.logging.v2.ConfigServiceV2.GetBucket", - "async": true, - "parameters": [ - { - "name": "name", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.logging.v2.LogBucket", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "GetBucket", - "fullName": "google.logging.v2.ConfigServiceV2.GetBucket", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 59, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "GetBucket", + "fullName": "google.logging.v2.ConfigServiceV2.GetBucket", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.logging.v2.LogBucket", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "GetBucket", + "fullName": "google.logging.v2.ConfigServiceV2.GetBucket", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_CreateBucketAsync_async", + "title": "logging createBucketAsync Sample", + "origin": "API_DEFINITION", + "description": " Creates a log bucket asynchronously that can be used to store log entries. After a bucket has been created, the bucket's location cannot be changed.", + "canonical": true, + "file": "config_service_v2.create_bucket_async.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_CreateBucketAsync_async", - "title": "logging createBucketAsync Sample", - "origin": "API_DEFINITION", - "description": " Creates a log bucket asynchronously that can be used to store log entries. After a bucket has been created, the bucket's location cannot be changed.", - "canonical": true, - "file": "config_service_v2.create_bucket_async.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 71, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "CreateBucketAsync", - "fullName": "google.logging.v2.ConfigServiceV2.CreateBucketAsync", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "bucket_id", - "type": "TYPE_STRING" - }, - { - "name": "bucket", - "type": ".google.logging.v2.LogBucket" - } - ], - "resultType": ".google.longrunning.Operation", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "CreateBucketAsync", - "fullName": "google.logging.v2.ConfigServiceV2.CreateBucketAsync", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 71, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "CreateBucketAsync", + "fullName": "google.logging.v2.ConfigServiceV2.CreateBucketAsync", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "bucket_id", + "type": "TYPE_STRING" + }, + { + "name": "bucket", + "type": ".google.logging.v2.LogBucket" + } + ], + "resultType": ".google.longrunning.Operation", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "CreateBucketAsync", + "fullName": "google.logging.v2.ConfigServiceV2.CreateBucketAsync", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_UpdateBucketAsync_async", + "title": "logging updateBucketAsync Sample", + "origin": "API_DEFINITION", + "description": " Updates a log bucket asynchronously. If the bucket has a `lifecycle_state` of `DELETE_REQUESTED`, then `FAILED_PRECONDITION` will be returned. After a bucket has been created, the bucket's location cannot be changed.", + "canonical": true, + "file": "config_service_v2.update_bucket_async.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_UpdateBucketAsync_async", - "title": "logging updateBucketAsync Sample", - "origin": "API_DEFINITION", - "description": " Updates a log bucket asynchronously. If the bucket has a `lifecycle_state` of `DELETE_REQUESTED`, then `FAILED_PRECONDITION` will be returned. After a bucket has been created, the bucket's location cannot be changed.", - "canonical": true, - "file": "config_service_v2.update_bucket_async.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 75, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "UpdateBucketAsync", - "fullName": "google.logging.v2.ConfigServiceV2.UpdateBucketAsync", - "async": true, - "parameters": [ - { - "name": "name", - "type": "TYPE_STRING" - }, - { - "name": "bucket", - "type": ".google.logging.v2.LogBucket" - }, - { - "name": "update_mask", - "type": ".google.protobuf.FieldMask" - } - ], - "resultType": ".google.longrunning.Operation", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "UpdateBucketAsync", - "fullName": "google.logging.v2.ConfigServiceV2.UpdateBucketAsync", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 75, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "UpdateBucketAsync", + "fullName": "google.logging.v2.ConfigServiceV2.UpdateBucketAsync", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + }, + { + "name": "bucket", + "type": ".google.logging.v2.LogBucket" + }, + { + "name": "update_mask", + "type": ".google.protobuf.FieldMask" + } + ], + "resultType": ".google.longrunning.Operation", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "UpdateBucketAsync", + "fullName": "google.logging.v2.ConfigServiceV2.UpdateBucketAsync", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_CreateBucket_async", + "title": "logging createBucket Sample", + "origin": "API_DEFINITION", + "description": " Creates a log bucket that can be used to store log entries. After a bucket has been created, the bucket's location cannot be changed.", + "canonical": true, + "file": "config_service_v2.create_bucket.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_CreateBucket_async", - "title": "logging createBucket Sample", - "origin": "API_DEFINITION", - "description": " Creates a log bucket that can be used to store log entries. After a bucket has been created, the bucket's location cannot be changed.", - "canonical": true, - "file": "config_service_v2.create_bucket.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 70, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "CreateBucket", - "fullName": "google.logging.v2.ConfigServiceV2.CreateBucket", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "bucket_id", - "type": "TYPE_STRING" - }, - { - "name": "bucket", - "type": ".google.logging.v2.LogBucket" - } - ], - "resultType": ".google.logging.v2.LogBucket", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "CreateBucket", - "fullName": "google.logging.v2.ConfigServiceV2.CreateBucket", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 70, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "CreateBucket", + "fullName": "google.logging.v2.ConfigServiceV2.CreateBucket", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "bucket_id", + "type": "TYPE_STRING" + }, + { + "name": "bucket", + "type": ".google.logging.v2.LogBucket" + } + ], + "resultType": ".google.logging.v2.LogBucket", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "CreateBucket", + "fullName": "google.logging.v2.ConfigServiceV2.CreateBucket", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_UpdateBucket_async", + "title": "logging updateBucket Sample", + "origin": "API_DEFINITION", + "description": " Updates a log bucket. If the bucket has a `lifecycle_state` of `DELETE_REQUESTED`, then `FAILED_PRECONDITION` will be returned. After a bucket has been created, the bucket's location cannot be changed.", + "canonical": true, + "file": "config_service_v2.update_bucket.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_UpdateBucket_async", - "title": "logging updateBucket Sample", - "origin": "API_DEFINITION", - "description": " Updates a log bucket. If the bucket has a `lifecycle_state` of `DELETE_REQUESTED`, then `FAILED_PRECONDITION` will be returned. After a bucket has been created, the bucket's location cannot be changed.", - "canonical": true, - "file": "config_service_v2.update_bucket.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 74, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "UpdateBucket", - "fullName": "google.logging.v2.ConfigServiceV2.UpdateBucket", - "async": true, - "parameters": [ - { - "name": "name", - "type": "TYPE_STRING" - }, - { - "name": "bucket", - "type": ".google.logging.v2.LogBucket" - }, - { - "name": "update_mask", - "type": ".google.protobuf.FieldMask" - } - ], - "resultType": ".google.logging.v2.LogBucket", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "UpdateBucket", - "fullName": "google.logging.v2.ConfigServiceV2.UpdateBucket", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 74, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "UpdateBucket", + "fullName": "google.logging.v2.ConfigServiceV2.UpdateBucket", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + }, + { + "name": "bucket", + "type": ".google.logging.v2.LogBucket" + }, + { + "name": "update_mask", + "type": ".google.protobuf.FieldMask" + } + ], + "resultType": ".google.logging.v2.LogBucket", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "UpdateBucket", + "fullName": "google.logging.v2.ConfigServiceV2.UpdateBucket", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteBucket_async", + "title": "logging deleteBucket Sample", + "origin": "API_DEFINITION", + "description": " Deletes a log bucket. Changes the bucket's `lifecycle_state` to the `DELETE_REQUESTED` state. After 7 days, the bucket will be purged and all log entries in the bucket will be permanently deleted.", + "canonical": true, + "file": "config_service_v2.delete_bucket.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteBucket_async", - "title": "logging deleteBucket Sample", - "origin": "API_DEFINITION", - "description": " Deletes a log bucket. Changes the bucket's `lifecycle_state` to the `DELETE_REQUESTED` state. After 7 days, the bucket will be purged and all log entries in the bucket will be permanently deleted.", - "canonical": true, - "file": "config_service_v2.delete_bucket.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 59, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "DeleteBucket", - "fullName": "google.logging.v2.ConfigServiceV2.DeleteBucket", - "async": true, - "parameters": [ - { - "name": "name", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.protobuf.Empty", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "DeleteBucket", - "fullName": "google.logging.v2.ConfigServiceV2.DeleteBucket", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 59, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "DeleteBucket", + "fullName": "google.logging.v2.ConfigServiceV2.DeleteBucket", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.protobuf.Empty", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "DeleteBucket", + "fullName": "google.logging.v2.ConfigServiceV2.DeleteBucket", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_UndeleteBucket_async", + "title": "logging undeleteBucket Sample", + "origin": "API_DEFINITION", + "description": " Undeletes a log bucket. A bucket that has been deleted can be undeleted within the grace period of 7 days.", + "canonical": true, + "file": "config_service_v2.undelete_bucket.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_UndeleteBucket_async", - "title": "logging undeleteBucket Sample", - "origin": "API_DEFINITION", - "description": " Undeletes a log bucket. A bucket that has been deleted can be undeleted within the grace period of 7 days.", - "canonical": true, - "file": "config_service_v2.undelete_bucket.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 59, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "UndeleteBucket", - "fullName": "google.logging.v2.ConfigServiceV2.UndeleteBucket", - "async": true, - "parameters": [ - { - "name": "name", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.protobuf.Empty", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "UndeleteBucket", - "fullName": "google.logging.v2.ConfigServiceV2.UndeleteBucket", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 59, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "UndeleteBucket", + "fullName": "google.logging.v2.ConfigServiceV2.UndeleteBucket", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.protobuf.Empty", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "UndeleteBucket", + "fullName": "google.logging.v2.ConfigServiceV2.UndeleteBucket", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_ListViews_async", + "title": "logging listViews Sample", + "origin": "API_DEFINITION", + "description": " Lists views on a log bucket.", + "canonical": true, + "file": "config_service_v2.list_views.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_ListViews_async", - "title": "logging listViews Sample", - "origin": "API_DEFINITION", - "description": " Lists views on a log bucket.", - "canonical": true, - "file": "config_service_v2.list_views.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 69, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "ListViews", - "fullName": "google.logging.v2.ConfigServiceV2.ListViews", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "page_token", - "type": "TYPE_STRING" - }, - { - "name": "page_size", - "type": "TYPE_INT32" - } - ], - "resultType": ".google.logging.v2.ListViewsResponse", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "ListViews", - "fullName": "google.logging.v2.ConfigServiceV2.ListViews", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 69, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "ListViews", + "fullName": "google.logging.v2.ConfigServiceV2.ListViews", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "page_token", + "type": "TYPE_STRING" + }, + { + "name": "page_size", + "type": "TYPE_INT32" + } + ], + "resultType": ".google.logging.v2.ListViewsResponse", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "ListViews", + "fullName": "google.logging.v2.ConfigServiceV2.ListViews", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_GetView_async", + "title": "logging getView Sample", + "origin": "API_DEFINITION", + "description": " Gets a view on a log bucket..", + "canonical": true, + "file": "config_service_v2.get_view.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_GetView_async", - "title": "logging getView Sample", - "origin": "API_DEFINITION", - "description": " Gets a view on a log bucket..", - "canonical": true, - "file": "config_service_v2.get_view.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 56, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "GetView", - "fullName": "google.logging.v2.ConfigServiceV2.GetView", - "async": true, - "parameters": [ - { - "name": "name", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.logging.v2.LogView", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "GetView", - "fullName": "google.logging.v2.ConfigServiceV2.GetView", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 56, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "GetView", + "fullName": "google.logging.v2.ConfigServiceV2.GetView", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.logging.v2.LogView", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "GetView", + "fullName": "google.logging.v2.ConfigServiceV2.GetView", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_CreateView_async", + "title": "logging createView Sample", + "origin": "API_DEFINITION", + "description": " Creates a view over log entries in a log bucket. A bucket may contain a maximum of 30 views.", + "canonical": true, + "file": "config_service_v2.create_view.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_CreateView_async", - "title": "logging createView Sample", - "origin": "API_DEFINITION", - "description": " Creates a view over log entries in a log bucket. A bucket may contain a maximum of 30 views.", - "canonical": true, - "file": "config_service_v2.create_view.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 68, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "CreateView", - "fullName": "google.logging.v2.ConfigServiceV2.CreateView", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "view_id", - "type": "TYPE_STRING" - }, - { - "name": "view", - "type": ".google.logging.v2.LogView" - } - ], - "resultType": ".google.logging.v2.LogView", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "CreateView", - "fullName": "google.logging.v2.ConfigServiceV2.CreateView", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 68, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "CreateView", + "fullName": "google.logging.v2.ConfigServiceV2.CreateView", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "view_id", + "type": "TYPE_STRING" + }, + { + "name": "view", + "type": ".google.logging.v2.LogView" + } + ], + "resultType": ".google.logging.v2.LogView", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "CreateView", + "fullName": "google.logging.v2.ConfigServiceV2.CreateView", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_UpdateView_async", + "title": "logging updateView Sample", + "origin": "API_DEFINITION", + "description": " Updates a view on a log bucket. This method replaces the following fields in the existing view with values from the new view: `filter`. If an `UNAVAILABLE` error is returned, this indicates that system is not in a state where it can update the view. If this occurs, please try again in a few minutes.", + "canonical": true, + "file": "config_service_v2.update_view.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_UpdateView_async", - "title": "logging updateView Sample", - "origin": "API_DEFINITION", - "description": " Updates a view on a log bucket. This method replaces the following fields in the existing view with values from the new view: `filter`. If an `UNAVAILABLE` error is returned, this indicates that system is not in a state where it can update the view. If this occurs, please try again in a few minutes.", - "canonical": true, - "file": "config_service_v2.update_view.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 70, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "UpdateView", - "fullName": "google.logging.v2.ConfigServiceV2.UpdateView", - "async": true, - "parameters": [ - { - "name": "name", - "type": "TYPE_STRING" - }, - { - "name": "view", - "type": ".google.logging.v2.LogView" - }, - { - "name": "update_mask", - "type": ".google.protobuf.FieldMask" - } - ], - "resultType": ".google.logging.v2.LogView", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "UpdateView", - "fullName": "google.logging.v2.ConfigServiceV2.UpdateView", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 70, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "UpdateView", + "fullName": "google.logging.v2.ConfigServiceV2.UpdateView", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + }, + { + "name": "view", + "type": ".google.logging.v2.LogView" + }, + { + "name": "update_mask", + "type": ".google.protobuf.FieldMask" + } + ], + "resultType": ".google.logging.v2.LogView", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "UpdateView", + "fullName": "google.logging.v2.ConfigServiceV2.UpdateView", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteView_async", + "title": "logging deleteView Sample", + "origin": "API_DEFINITION", + "description": " Deletes a view on a log bucket. If an `UNAVAILABLE` error is returned, this indicates that system is not in a state where it can delete the view. If this occurs, please try again in a few minutes.", + "canonical": true, + "file": "config_service_v2.delete_view.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteView_async", - "title": "logging deleteView Sample", - "origin": "API_DEFINITION", - "description": " Deletes a view on a log bucket. If an `UNAVAILABLE` error is returned, this indicates that system is not in a state where it can delete the view. If this occurs, please try again in a few minutes.", - "canonical": true, - "file": "config_service_v2.delete_view.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 56, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "DeleteView", - "fullName": "google.logging.v2.ConfigServiceV2.DeleteView", - "async": true, - "parameters": [ - { - "name": "name", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.protobuf.Empty", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "DeleteView", - "fullName": "google.logging.v2.ConfigServiceV2.DeleteView", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 56, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "DeleteView", + "fullName": "google.logging.v2.ConfigServiceV2.DeleteView", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.protobuf.Empty", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "DeleteView", + "fullName": "google.logging.v2.ConfigServiceV2.DeleteView", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_ListSinks_async", + "title": "logging listSinks Sample", + "origin": "API_DEFINITION", + "description": " Lists sinks.", + "canonical": true, + "file": "config_service_v2.list_sinks.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_ListSinks_async", - "title": "logging listSinks Sample", - "origin": "API_DEFINITION", - "description": " Lists sinks.", - "canonical": true, - "file": "config_service_v2.list_sinks.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 72, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "ListSinks", - "fullName": "google.logging.v2.ConfigServiceV2.ListSinks", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "page_token", - "type": "TYPE_STRING" - }, - { - "name": "page_size", - "type": "TYPE_INT32" - } - ], - "resultType": ".google.logging.v2.ListSinksResponse", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "ListSinks", - "fullName": "google.logging.v2.ConfigServiceV2.ListSinks", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 72, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "ListSinks", + "fullName": "google.logging.v2.ConfigServiceV2.ListSinks", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "page_token", + "type": "TYPE_STRING" + }, + { + "name": "page_size", + "type": "TYPE_INT32" + } + ], + "resultType": ".google.logging.v2.ListSinksResponse", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "ListSinks", + "fullName": "google.logging.v2.ConfigServiceV2.ListSinks", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_GetSink_async", + "title": "logging getSink Sample", + "origin": "API_DEFINITION", + "description": " Gets a sink.", + "canonical": true, + "file": "config_service_v2.get_sink.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_GetSink_async", - "title": "logging getSink Sample", - "origin": "API_DEFINITION", - "description": " Gets a sink.", - "canonical": true, - "file": "config_service_v2.get_sink.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 59, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "GetSink", - "fullName": "google.logging.v2.ConfigServiceV2.GetSink", - "async": true, - "parameters": [ - { - "name": "sink_name", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.logging.v2.LogSink", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "GetSink", - "fullName": "google.logging.v2.ConfigServiceV2.GetSink", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 59, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "GetSink", + "fullName": "google.logging.v2.ConfigServiceV2.GetSink", + "async": true, + "parameters": [ + { + "name": "sink_name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.logging.v2.LogSink", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "GetSink", + "fullName": "google.logging.v2.ConfigServiceV2.GetSink", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_CreateSink_async", + "title": "logging createSink Sample", + "origin": "API_DEFINITION", + "description": " Creates a sink that exports specified log entries to a destination. The export of newly-ingested log entries begins immediately, unless the sink's `writer_identity` is not permitted to write to the destination. A sink can export log entries only from the resource owning the sink.", + "canonical": true, + "file": "config_service_v2.create_sink.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_CreateSink_async", - "title": "logging createSink Sample", - "origin": "API_DEFINITION", - "description": " Creates a sink that exports specified log entries to a destination. The export of newly-ingested log entries begins immediately, unless the sink's `writer_identity` is not permitted to write to the destination. A sink can export log entries only from the resource owning the sink.", - "canonical": true, - "file": "config_service_v2.create_sink.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 80, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "CreateSink", - "fullName": "google.logging.v2.ConfigServiceV2.CreateSink", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "sink", - "type": ".google.logging.v2.LogSink" - }, - { - "name": "unique_writer_identity", - "type": "TYPE_BOOL" - } - ], - "resultType": ".google.logging.v2.LogSink", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "CreateSink", - "fullName": "google.logging.v2.ConfigServiceV2.CreateSink", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 80, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "CreateSink", + "fullName": "google.logging.v2.ConfigServiceV2.CreateSink", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "sink", + "type": ".google.logging.v2.LogSink" + }, + { + "name": "unique_writer_identity", + "type": "TYPE_BOOL" + } + ], + "resultType": ".google.logging.v2.LogSink", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "CreateSink", + "fullName": "google.logging.v2.ConfigServiceV2.CreateSink", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_UpdateSink_async", + "title": "logging updateSink Sample", + "origin": "API_DEFINITION", + "description": " Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: `destination`, and `filter`. The updated sink might also have a new `writer_identity`; see the `unique_writer_identity` field.", + "canonical": true, + "file": "config_service_v2.update_sink.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_UpdateSink_async", - "title": "logging updateSink Sample", - "origin": "API_DEFINITION", - "description": " Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: `destination`, and `filter`. The updated sink might also have a new `writer_identity`; see the `unique_writer_identity` field.", - "canonical": true, - "file": "config_service_v2.update_sink.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 93, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "UpdateSink", - "fullName": "google.logging.v2.ConfigServiceV2.UpdateSink", - "async": true, - "parameters": [ - { - "name": "sink_name", - "type": "TYPE_STRING" - }, - { - "name": "sink", - "type": ".google.logging.v2.LogSink" - }, - { - "name": "unique_writer_identity", - "type": "TYPE_BOOL" - }, - { - "name": "update_mask", - "type": ".google.protobuf.FieldMask" - } - ], - "resultType": ".google.logging.v2.LogSink", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "UpdateSink", - "fullName": "google.logging.v2.ConfigServiceV2.UpdateSink", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 93, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "UpdateSink", + "fullName": "google.logging.v2.ConfigServiceV2.UpdateSink", + "async": true, + "parameters": [ + { + "name": "sink_name", + "type": "TYPE_STRING" + }, + { + "name": "sink", + "type": ".google.logging.v2.LogSink" + }, + { + "name": "unique_writer_identity", + "type": "TYPE_BOOL" + }, + { + "name": "update_mask", + "type": ".google.protobuf.FieldMask" + } + ], + "resultType": ".google.logging.v2.LogSink", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "UpdateSink", + "fullName": "google.logging.v2.ConfigServiceV2.UpdateSink", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteSink_async", + "title": "logging deleteSink Sample", + "origin": "API_DEFINITION", + "description": " Deletes a sink. If the sink has a unique `writer_identity`, then that service account is also deleted.", + "canonical": true, + "file": "config_service_v2.delete_sink.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteSink_async", - "title": "logging deleteSink Sample", - "origin": "API_DEFINITION", - "description": " Deletes a sink. If the sink has a unique `writer_identity`, then that service account is also deleted.", - "canonical": true, - "file": "config_service_v2.delete_sink.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 60, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "DeleteSink", - "fullName": "google.logging.v2.ConfigServiceV2.DeleteSink", - "async": true, - "parameters": [ - { - "name": "sink_name", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.protobuf.Empty", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "DeleteSink", - "fullName": "google.logging.v2.ConfigServiceV2.DeleteSink", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 60, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "DeleteSink", + "fullName": "google.logging.v2.ConfigServiceV2.DeleteSink", + "async": true, + "parameters": [ + { + "name": "sink_name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.protobuf.Empty", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "DeleteSink", + "fullName": "google.logging.v2.ConfigServiceV2.DeleteSink", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_CreateLink_async", + "title": "logging createLink Sample", + "origin": "API_DEFINITION", + "description": " Asynchronously creates a linked dataset in BigQuery which makes it possible to use BigQuery to read the logs stored in the log bucket. A log bucket may currently only contain one link.", + "canonical": true, + "file": "config_service_v2.create_link.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_CreateLink_async", - "title": "logging createLink Sample", - "origin": "API_DEFINITION", - "description": " Asynchronously creates a linked dataset in BigQuery which makes it possible to use BigQuery to read the logs stored in the log bucket. A log bucket may currently only contain one link.", - "canonical": true, - "file": "config_service_v2.create_link.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 70, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "CreateLink", - "fullName": "google.logging.v2.ConfigServiceV2.CreateLink", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "link", - "type": ".google.logging.v2.Link" - }, - { - "name": "link_id", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.longrunning.Operation", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "CreateLink", - "fullName": "google.logging.v2.ConfigServiceV2.CreateLink", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 70, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "CreateLink", + "fullName": "google.logging.v2.ConfigServiceV2.CreateLink", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "link", + "type": ".google.logging.v2.Link" + }, + { + "name": "link_id", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.longrunning.Operation", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "CreateLink", + "fullName": "google.logging.v2.ConfigServiceV2.CreateLink", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteLink_async", + "title": "logging deleteLink Sample", + "origin": "API_DEFINITION", + "description": " Deletes a link. This will also delete the corresponding BigQuery linked dataset.", + "canonical": true, + "file": "config_service_v2.delete_link.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteLink_async", - "title": "logging deleteLink Sample", - "origin": "API_DEFINITION", - "description": " Deletes a link. This will also delete the corresponding BigQuery linked dataset.", - "canonical": true, - "file": "config_service_v2.delete_link.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 58, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "DeleteLink", - "fullName": "google.logging.v2.ConfigServiceV2.DeleteLink", - "async": true, - "parameters": [ - { - "name": "name", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.longrunning.Operation", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "DeleteLink", - "fullName": "google.logging.v2.ConfigServiceV2.DeleteLink", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 58, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "DeleteLink", + "fullName": "google.logging.v2.ConfigServiceV2.DeleteLink", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.longrunning.Operation", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "DeleteLink", + "fullName": "google.logging.v2.ConfigServiceV2.DeleteLink", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_ListLinks_async", + "title": "logging listLinks Sample", + "origin": "API_DEFINITION", + "description": " Lists links.", + "canonical": true, + "file": "config_service_v2.list_links.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_ListLinks_async", - "title": "logging listLinks Sample", - "origin": "API_DEFINITION", - "description": " Lists links.", - "canonical": true, - "file": "config_service_v2.list_links.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 69, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "ListLinks", - "fullName": "google.logging.v2.ConfigServiceV2.ListLinks", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "page_token", - "type": "TYPE_STRING" - }, - { - "name": "page_size", - "type": "TYPE_INT32" - } - ], - "resultType": ".google.logging.v2.ListLinksResponse", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "ListLinks", - "fullName": "google.logging.v2.ConfigServiceV2.ListLinks", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 69, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "ListLinks", + "fullName": "google.logging.v2.ConfigServiceV2.ListLinks", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "page_token", + "type": "TYPE_STRING" + }, + { + "name": "page_size", + "type": "TYPE_INT32" + } + ], + "resultType": ".google.logging.v2.ListLinksResponse", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "ListLinks", + "fullName": "google.logging.v2.ConfigServiceV2.ListLinks", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_GetLink_async", + "title": "logging getLink Sample", + "origin": "API_DEFINITION", + "description": " Gets a link.", + "canonical": true, + "file": "config_service_v2.get_link.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_GetLink_async", - "title": "logging getLink Sample", - "origin": "API_DEFINITION", - "description": " Gets a link.", - "canonical": true, - "file": "config_service_v2.get_link.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 57, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "GetLink", - "fullName": "google.logging.v2.ConfigServiceV2.GetLink", - "async": true, - "parameters": [ - { - "name": "name", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.logging.v2.Link", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "GetLink", - "fullName": "google.logging.v2.ConfigServiceV2.GetLink", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 57, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "GetLink", + "fullName": "google.logging.v2.ConfigServiceV2.GetLink", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.logging.v2.Link", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "GetLink", + "fullName": "google.logging.v2.ConfigServiceV2.GetLink", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_ListExclusions_async", + "title": "logging listExclusions Sample", + "origin": "API_DEFINITION", + "description": " Lists all the exclusions on the _Default sink in a parent resource.", + "canonical": true, + "file": "config_service_v2.list_exclusions.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_ListExclusions_async", - "title": "logging listExclusions Sample", - "origin": "API_DEFINITION", - "description": " Lists all the exclusions on the _Default sink in a parent resource.", - "canonical": true, - "file": "config_service_v2.list_exclusions.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 72, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "ListExclusions", - "fullName": "google.logging.v2.ConfigServiceV2.ListExclusions", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "page_token", - "type": "TYPE_STRING" - }, - { - "name": "page_size", - "type": "TYPE_INT32" - } - ], - "resultType": ".google.logging.v2.ListExclusionsResponse", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "ListExclusions", - "fullName": "google.logging.v2.ConfigServiceV2.ListExclusions", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 72, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "ListExclusions", + "fullName": "google.logging.v2.ConfigServiceV2.ListExclusions", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "page_token", + "type": "TYPE_STRING" + }, + { + "name": "page_size", + "type": "TYPE_INT32" + } + ], + "resultType": ".google.logging.v2.ListExclusionsResponse", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "ListExclusions", + "fullName": "google.logging.v2.ConfigServiceV2.ListExclusions", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_GetExclusion_async", + "title": "logging getExclusion Sample", + "origin": "API_DEFINITION", + "description": " Gets the description of an exclusion in the _Default sink.", + "canonical": true, + "file": "config_service_v2.get_exclusion.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_GetExclusion_async", - "title": "logging getExclusion Sample", - "origin": "API_DEFINITION", - "description": " Gets the description of an exclusion in the _Default sink.", - "canonical": true, - "file": "config_service_v2.get_exclusion.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 59, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "GetExclusion", - "fullName": "google.logging.v2.ConfigServiceV2.GetExclusion", - "async": true, - "parameters": [ - { - "name": "name", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.logging.v2.LogExclusion", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "GetExclusion", - "fullName": "google.logging.v2.ConfigServiceV2.GetExclusion", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 59, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "GetExclusion", + "fullName": "google.logging.v2.ConfigServiceV2.GetExclusion", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.logging.v2.LogExclusion", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "GetExclusion", + "fullName": "google.logging.v2.ConfigServiceV2.GetExclusion", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_CreateExclusion_async", + "title": "logging createExclusion Sample", + "origin": "API_DEFINITION", + "description": " Creates a new exclusion in the _Default sink in a specified parent resource. Only log entries belonging to that resource can be excluded. You can have up to 10 exclusions in a resource.", + "canonical": true, + "file": "config_service_v2.create_exclusion.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_CreateExclusion_async", - "title": "logging createExclusion Sample", - "origin": "API_DEFINITION", - "description": " Creates a new exclusion in the _Default sink in a specified parent resource. Only log entries belonging to that resource can be excluded. You can have up to 10 exclusions in a resource.", - "canonical": true, - "file": "config_service_v2.create_exclusion.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 66, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "CreateExclusion", - "fullName": "google.logging.v2.ConfigServiceV2.CreateExclusion", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "exclusion", - "type": ".google.logging.v2.LogExclusion" - } - ], - "resultType": ".google.logging.v2.LogExclusion", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "CreateExclusion", - "fullName": "google.logging.v2.ConfigServiceV2.CreateExclusion", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 66, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "CreateExclusion", + "fullName": "google.logging.v2.ConfigServiceV2.CreateExclusion", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "exclusion", + "type": ".google.logging.v2.LogExclusion" + } + ], + "resultType": ".google.logging.v2.LogExclusion", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "CreateExclusion", + "fullName": "google.logging.v2.ConfigServiceV2.CreateExclusion", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_UpdateExclusion_async", + "title": "logging updateExclusion Sample", + "origin": "API_DEFINITION", + "description": " Changes one or more properties of an existing exclusion in the _Default sink.", + "canonical": true, + "file": "config_service_v2.update_exclusion.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_UpdateExclusion_async", - "title": "logging updateExclusion Sample", - "origin": "API_DEFINITION", - "description": " Changes one or more properties of an existing exclusion in the _Default sink.", - "canonical": true, - "file": "config_service_v2.update_exclusion.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 76, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "UpdateExclusion", - "fullName": "google.logging.v2.ConfigServiceV2.UpdateExclusion", - "async": true, - "parameters": [ - { - "name": "name", - "type": "TYPE_STRING" - }, - { - "name": "exclusion", - "type": ".google.logging.v2.LogExclusion" - }, - { - "name": "update_mask", - "type": ".google.protobuf.FieldMask" - } - ], - "resultType": ".google.logging.v2.LogExclusion", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "UpdateExclusion", - "fullName": "google.logging.v2.ConfigServiceV2.UpdateExclusion", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 76, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "UpdateExclusion", + "fullName": "google.logging.v2.ConfigServiceV2.UpdateExclusion", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + }, + { + "name": "exclusion", + "type": ".google.logging.v2.LogExclusion" + }, + { + "name": "update_mask", + "type": ".google.protobuf.FieldMask" + } + ], + "resultType": ".google.logging.v2.LogExclusion", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "UpdateExclusion", + "fullName": "google.logging.v2.ConfigServiceV2.UpdateExclusion", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteExclusion_async", + "title": "logging deleteExclusion Sample", + "origin": "API_DEFINITION", + "description": " Deletes an exclusion in the _Default sink.", + "canonical": true, + "file": "config_service_v2.delete_exclusion.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_DeleteExclusion_async", - "title": "logging deleteExclusion Sample", - "origin": "API_DEFINITION", - "description": " Deletes an exclusion in the _Default sink.", - "canonical": true, - "file": "config_service_v2.delete_exclusion.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 59, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "DeleteExclusion", - "fullName": "google.logging.v2.ConfigServiceV2.DeleteExclusion", - "async": true, - "parameters": [ - { - "name": "name", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.protobuf.Empty", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "DeleteExclusion", - "fullName": "google.logging.v2.ConfigServiceV2.DeleteExclusion", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 59, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "DeleteExclusion", + "fullName": "google.logging.v2.ConfigServiceV2.DeleteExclusion", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.protobuf.Empty", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "DeleteExclusion", + "fullName": "google.logging.v2.ConfigServiceV2.DeleteExclusion", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_GetCmekSettings_async", + "title": "logging getCmekSettings Sample", + "origin": "API_DEFINITION", + "description": " Gets the Logging CMEK settings for the given resource. Note: CMEK for the Log Router can be configured for Google Cloud projects, folders, organizations and billing accounts. Once configured for an organization, it applies to all projects and folders in the Google Cloud organization. See [Enabling CMEK for Log Router](https://cloud.google.com/logging/docs/routing/managed-encryption) for more information.", + "canonical": true, + "file": "config_service_v2.get_cmek_settings.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_GetCmekSettings_async", - "title": "logging getCmekSettings Sample", - "origin": "API_DEFINITION", - "description": " Gets the Logging CMEK settings for the given resource. Note: CMEK for the Log Router can be configured for Google Cloud projects, folders, organizations and billing accounts. Once configured for an organization, it applies to all projects and folders in the Google Cloud organization. See [Enabling CMEK for Log Router](https://cloud.google.com/logging/docs/routing/managed-encryption) for more information.", - "canonical": true, - "file": "config_service_v2.get_cmek_settings.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 63, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "GetCmekSettings", - "fullName": "google.logging.v2.ConfigServiceV2.GetCmekSettings", - "async": true, - "parameters": [ - { - "name": "name", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.logging.v2.CmekSettings", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "GetCmekSettings", - "fullName": "google.logging.v2.ConfigServiceV2.GetCmekSettings", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 63, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "GetCmekSettings", + "fullName": "google.logging.v2.ConfigServiceV2.GetCmekSettings", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.logging.v2.CmekSettings", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "GetCmekSettings", + "fullName": "google.logging.v2.ConfigServiceV2.GetCmekSettings", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_UpdateCmekSettings_async", + "title": "logging updateCmekSettings Sample", + "origin": "API_DEFINITION", + "description": " Updates the Log Router CMEK settings for the given resource. Note: CMEK for the Log Router can currently only be configured for Google Cloud organizations. Once configured, it applies to all projects and folders in the Google Cloud organization. [UpdateCmekSettings][google.logging.v2.ConfigServiceV2.UpdateCmekSettings] will fail if 1) `kms_key_name` is invalid, or 2) the associated service account does not have the required `roles/cloudkms.cryptoKeyEncrypterDecrypter` role assigned for the key, or 3) access to the key is disabled. See [Enabling CMEK for Log Router](https://cloud.google.com/logging/docs/routing/managed-encryption) for more information.", + "canonical": true, + "file": "config_service_v2.update_cmek_settings.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_UpdateCmekSettings_async", - "title": "logging updateCmekSettings Sample", - "origin": "API_DEFINITION", - "description": " Updates the Log Router CMEK settings for the given resource. Note: CMEK for the Log Router can currently only be configured for Google Cloud organizations. Once configured, it applies to all projects and folders in the Google Cloud organization. [UpdateCmekSettings][google.logging.v2.ConfigServiceV2.UpdateCmekSettings] will fail if 1) `kms_key_name` is invalid, or 2) the associated service account does not have the required `roles/cloudkms.cryptoKeyEncrypterDecrypter` role assigned for the key, or 3) access to the key is disabled. See [Enabling CMEK for Log Router](https://cloud.google.com/logging/docs/routing/managed-encryption) for more information.", - "canonical": true, - "file": "config_service_v2.update_cmek_settings.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 78, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "UpdateCmekSettings", - "fullName": "google.logging.v2.ConfigServiceV2.UpdateCmekSettings", - "async": true, - "parameters": [ - { - "name": "name", - "type": "TYPE_STRING" - }, - { - "name": "cmek_settings", - "type": ".google.logging.v2.CmekSettings" - }, - { - "name": "update_mask", - "type": ".google.protobuf.FieldMask" - } - ], - "resultType": ".google.logging.v2.CmekSettings", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "UpdateCmekSettings", - "fullName": "google.logging.v2.ConfigServiceV2.UpdateCmekSettings", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 78, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "UpdateCmekSettings", + "fullName": "google.logging.v2.ConfigServiceV2.UpdateCmekSettings", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + }, + { + "name": "cmek_settings", + "type": ".google.logging.v2.CmekSettings" + }, + { + "name": "update_mask", + "type": ".google.protobuf.FieldMask" + } + ], + "resultType": ".google.logging.v2.CmekSettings", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "UpdateCmekSettings", + "fullName": "google.logging.v2.ConfigServiceV2.UpdateCmekSettings", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_GetSettings_async", + "title": "logging getSettings Sample", + "origin": "API_DEFINITION", + "description": " Gets the Log Router settings for the given resource. Note: Settings for the Log Router can be get for Google Cloud projects, folders, organizations and billing accounts. Currently it can only be configured for organizations. Once configured for an organization, it applies to all projects and folders in the Google Cloud organization. See [Enabling CMEK for Log Router](https://cloud.google.com/logging/docs/routing/managed-encryption) for more information.", + "canonical": true, + "file": "config_service_v2.get_settings.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_GetSettings_async", - "title": "logging getSettings Sample", - "origin": "API_DEFINITION", - "description": " Gets the Log Router settings for the given resource. Note: Settings for the Log Router can be get for Google Cloud projects, folders, organizations and billing accounts. Currently it can only be configured for organizations. Once configured for an organization, it applies to all projects and folders in the Google Cloud organization. See [Enabling CMEK for Log Router](https://cloud.google.com/logging/docs/routing/managed-encryption) for more information.", - "canonical": true, - "file": "config_service_v2.get_settings.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 63, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "GetSettings", - "fullName": "google.logging.v2.ConfigServiceV2.GetSettings", - "async": true, - "parameters": [ - { - "name": "name", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.logging.v2.Settings", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "GetSettings", - "fullName": "google.logging.v2.ConfigServiceV2.GetSettings", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 63, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "GetSettings", + "fullName": "google.logging.v2.ConfigServiceV2.GetSettings", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.logging.v2.Settings", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "GetSettings", + "fullName": "google.logging.v2.ConfigServiceV2.GetSettings", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_UpdateSettings_async", + "title": "logging updateSettings Sample", + "origin": "API_DEFINITION", + "description": " Updates the Log Router settings for the given resource. Note: Settings for the Log Router can currently only be configured for Google Cloud organizations. Once configured, it applies to all projects and folders in the Google Cloud organization. [UpdateSettings][google.logging.v2.ConfigServiceV2.UpdateSettings] will fail if 1) `kms_key_name` is invalid, or 2) the associated service account does not have the required `roles/cloudkms.cryptoKeyEncrypterDecrypter` role assigned for the key, or 3) access to the key is disabled. 4) `location_id` is not supported by Logging. 5) `location_id` violate OrgPolicy. See [Enabling CMEK for Log Router](https://cloud.google.com/logging/docs/routing/managed-encryption) for more information.", + "canonical": true, + "file": "config_service_v2.update_settings.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_UpdateSettings_async", - "title": "logging updateSettings Sample", - "origin": "API_DEFINITION", - "description": " Updates the Log Router settings for the given resource. Note: Settings for the Log Router can currently only be configured for Google Cloud organizations. Once configured, it applies to all projects and folders in the Google Cloud organization. [UpdateSettings][google.logging.v2.ConfigServiceV2.UpdateSettings] will fail if 1) `kms_key_name` is invalid, or 2) the associated service account does not have the required `roles/cloudkms.cryptoKeyEncrypterDecrypter` role assigned for the key, or 3) access to the key is disabled. 4) `location_id` is not supported by Logging. 5) `location_id` violate OrgPolicy. See [Enabling CMEK for Log Router](https://cloud.google.com/logging/docs/routing/managed-encryption) for more information.", - "canonical": true, - "file": "config_service_v2.update_settings.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 75, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "UpdateSettings", - "fullName": "google.logging.v2.ConfigServiceV2.UpdateSettings", - "async": true, - "parameters": [ - { - "name": "name", - "type": "TYPE_STRING" - }, - { - "name": "settings", - "type": ".google.logging.v2.Settings" - }, - { - "name": "update_mask", - "type": ".google.protobuf.FieldMask" - } - ], - "resultType": ".google.logging.v2.Settings", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "UpdateSettings", - "fullName": "google.logging.v2.ConfigServiceV2.UpdateSettings", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 75, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "UpdateSettings", + "fullName": "google.logging.v2.ConfigServiceV2.UpdateSettings", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + }, + { + "name": "settings", + "type": ".google.logging.v2.Settings" + }, + { + "name": "update_mask", + "type": ".google.protobuf.FieldMask" + } + ], + "resultType": ".google.logging.v2.Settings", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "UpdateSettings", + "fullName": "google.logging.v2.ConfigServiceV2.UpdateSettings", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_ConfigServiceV2_CopyLogEntries_async", + "title": "logging copyLogEntries Sample", + "origin": "API_DEFINITION", + "description": " Copies a set of log entries from a log bucket to a Cloud Storage bucket.", + "canonical": true, + "file": "config_service_v2.copy_log_entries.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_ConfigServiceV2_CopyLogEntries_async", - "title": "logging copyLogEntries Sample", - "origin": "API_DEFINITION", - "description": " Copies a set of log entries from a log bucket to a Cloud Storage bucket.", - "canonical": true, - "file": "config_service_v2.copy_log_entries.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 66, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "CopyLogEntries", - "fullName": "google.logging.v2.ConfigServiceV2.CopyLogEntries", - "async": true, - "parameters": [ - { - "name": "name", - "type": "TYPE_STRING" - }, - { - "name": "filter", - "type": "TYPE_STRING" - }, - { - "name": "destination", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.longrunning.Operation", - "client": { - "shortName": "ConfigServiceV2Client", - "fullName": "google.logging.v2.ConfigServiceV2Client" - }, - "method": { - "shortName": "CopyLogEntries", - "fullName": "google.logging.v2.ConfigServiceV2.CopyLogEntries", - "service": { - "shortName": "ConfigServiceV2", - "fullName": "google.logging.v2.ConfigServiceV2" - } - } - } + "start": 25, + "end": 66, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "CopyLogEntries", + "fullName": "google.logging.v2.ConfigServiceV2.CopyLogEntries", + "async": true, + "parameters": [ + { + "name": "name", + "type": "TYPE_STRING" + }, + { + "name": "filter", + "type": "TYPE_STRING" + }, + { + "name": "destination", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.longrunning.Operation", + "client": { + "shortName": "ConfigServiceV2Client", + "fullName": "google.logging.v2.ConfigServiceV2Client" }, + "method": { + "shortName": "CopyLogEntries", + "fullName": "google.logging.v2.ConfigServiceV2.CopyLogEntries", + "service": { + "shortName": "ConfigServiceV2", + "fullName": "google.logging.v2.ConfigServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_LoggingServiceV2_DeleteLog_async", + "title": "logging deleteLog Sample", + "origin": "API_DEFINITION", + "description": " Deletes all the log entries in a log for the _Default Log Bucket. The log reappears if it receives new entries. Log entries written shortly before the delete operation might not be deleted. Entries received after the delete operation with a timestamp before the operation will be deleted.", + "canonical": true, + "file": "logging_service_v2.delete_log.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_LoggingServiceV2_DeleteLog_async", - "title": "logging deleteLog Sample", - "origin": "API_DEFINITION", - "description": " Deletes all the log entries in a log for the _Default Log Bucket. The log reappears if it receives new entries. Log entries written shortly before the delete operation might not be deleted. Entries received after the delete operation with a timestamp before the operation will be deleted.", - "canonical": true, - "file": "logging_service_v2.delete_log.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 62, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "DeleteLog", - "fullName": "google.logging.v2.LoggingServiceV2.DeleteLog", - "async": true, - "parameters": [ - { - "name": "log_name", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.protobuf.Empty", - "client": { - "shortName": "LoggingServiceV2Client", - "fullName": "google.logging.v2.LoggingServiceV2Client" - }, - "method": { - "shortName": "DeleteLog", - "fullName": "google.logging.v2.LoggingServiceV2.DeleteLog", - "service": { - "shortName": "LoggingServiceV2", - "fullName": "google.logging.v2.LoggingServiceV2" - } - } - } + "start": 25, + "end": 62, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "DeleteLog", + "fullName": "google.logging.v2.LoggingServiceV2.DeleteLog", + "async": true, + "parameters": [ + { + "name": "log_name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.protobuf.Empty", + "client": { + "shortName": "LoggingServiceV2Client", + "fullName": "google.logging.v2.LoggingServiceV2Client" }, + "method": { + "shortName": "DeleteLog", + "fullName": "google.logging.v2.LoggingServiceV2.DeleteLog", + "service": { + "shortName": "LoggingServiceV2", + "fullName": "google.logging.v2.LoggingServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_LoggingServiceV2_WriteLogEntries_async", + "title": "logging writeLogEntries Sample", + "origin": "API_DEFINITION", + "description": " Writes log entries to Logging. This API method is the only way to send log entries to Logging. This method is used, directly or indirectly, by the Logging agent (fluentd) and all logging libraries configured to use Logging. A single request may contain log entries for a maximum of 1000 different resources (projects, organizations, billing accounts or folders)", + "canonical": true, + "file": "logging_service_v2.write_log_entries.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_LoggingServiceV2_WriteLogEntries_async", - "title": "logging writeLogEntries Sample", - "origin": "API_DEFINITION", - "description": " Writes log entries to Logging. This API method is the only way to send log entries to Logging. This method is used, directly or indirectly, by the Logging agent (fluentd) and all logging libraries configured to use Logging. A single request may contain log entries for a maximum of 1000 different resources (projects, organizations, billing accounts or folders)", - "canonical": true, - "file": "logging_service_v2.write_log_entries.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 121, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "WriteLogEntries", - "fullName": "google.logging.v2.LoggingServiceV2.WriteLogEntries", - "async": true, - "parameters": [ - { - "name": "log_name", - "type": "TYPE_STRING" - }, - { - "name": "resource", - "type": ".google.api.MonitoredResource" - }, - { - "name": "labels", - "type": "TYPE_MESSAGE[]" - }, - { - "name": "entries", - "type": "TYPE_MESSAGE[]" - }, - { - "name": "partial_success", - "type": "TYPE_BOOL" - }, - { - "name": "dry_run", - "type": "TYPE_BOOL" - } - ], - "resultType": ".google.logging.v2.WriteLogEntriesResponse", - "client": { - "shortName": "LoggingServiceV2Client", - "fullName": "google.logging.v2.LoggingServiceV2Client" - }, - "method": { - "shortName": "WriteLogEntries", - "fullName": "google.logging.v2.LoggingServiceV2.WriteLogEntries", - "service": { - "shortName": "LoggingServiceV2", - "fullName": "google.logging.v2.LoggingServiceV2" - } - } - } + "start": 25, + "end": 121, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "WriteLogEntries", + "fullName": "google.logging.v2.LoggingServiceV2.WriteLogEntries", + "async": true, + "parameters": [ + { + "name": "log_name", + "type": "TYPE_STRING" + }, + { + "name": "resource", + "type": ".google.api.MonitoredResource" + }, + { + "name": "labels", + "type": "TYPE_MESSAGE[]" + }, + { + "name": "entries", + "type": "TYPE_MESSAGE[]" + }, + { + "name": "partial_success", + "type": "TYPE_BOOL" + }, + { + "name": "dry_run", + "type": "TYPE_BOOL" + } + ], + "resultType": ".google.logging.v2.WriteLogEntriesResponse", + "client": { + "shortName": "LoggingServiceV2Client", + "fullName": "google.logging.v2.LoggingServiceV2Client" }, + "method": { + "shortName": "WriteLogEntries", + "fullName": "google.logging.v2.LoggingServiceV2.WriteLogEntries", + "service": { + "shortName": "LoggingServiceV2", + "fullName": "google.logging.v2.LoggingServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_LoggingServiceV2_ListLogEntries_async", + "title": "logging listLogEntries Sample", + "origin": "API_DEFINITION", + "description": " Lists log entries. Use this method to retrieve log entries that originated from a project/folder/organization/billing account. For ways to export log entries, see [Exporting Logs](https://cloud.google.com/logging/docs/export).", + "canonical": true, + "file": "logging_service_v2.list_log_entries.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_LoggingServiceV2_ListLogEntries_async", - "title": "logging listLogEntries Sample", - "origin": "API_DEFINITION", - "description": " Lists log entries. Use this method to retrieve log entries that originated from a project/folder/organization/billing account. For ways to export log entries, see [Exporting Logs](https://cloud.google.com/logging/docs/export).", - "canonical": true, - "file": "logging_service_v2.list_log_entries.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 98, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "ListLogEntries", - "fullName": "google.logging.v2.LoggingServiceV2.ListLogEntries", - "async": true, - "parameters": [ - { - "name": "resource_names", - "type": "TYPE_STRING[]" - }, - { - "name": "filter", - "type": "TYPE_STRING" - }, - { - "name": "order_by", - "type": "TYPE_STRING" - }, - { - "name": "page_size", - "type": "TYPE_INT32" - }, - { - "name": "page_token", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.logging.v2.ListLogEntriesResponse", - "client": { - "shortName": "LoggingServiceV2Client", - "fullName": "google.logging.v2.LoggingServiceV2Client" - }, - "method": { - "shortName": "ListLogEntries", - "fullName": "google.logging.v2.LoggingServiceV2.ListLogEntries", - "service": { - "shortName": "LoggingServiceV2", - "fullName": "google.logging.v2.LoggingServiceV2" - } - } - } + "start": 25, + "end": 98, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "ListLogEntries", + "fullName": "google.logging.v2.LoggingServiceV2.ListLogEntries", + "async": true, + "parameters": [ + { + "name": "resource_names", + "type": "TYPE_STRING[]" + }, + { + "name": "filter", + "type": "TYPE_STRING" + }, + { + "name": "order_by", + "type": "TYPE_STRING" + }, + { + "name": "page_size", + "type": "TYPE_INT32" + }, + { + "name": "page_token", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.logging.v2.ListLogEntriesResponse", + "client": { + "shortName": "LoggingServiceV2Client", + "fullName": "google.logging.v2.LoggingServiceV2Client" }, + "method": { + "shortName": "ListLogEntries", + "fullName": "google.logging.v2.LoggingServiceV2.ListLogEntries", + "service": { + "shortName": "LoggingServiceV2", + "fullName": "google.logging.v2.LoggingServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_LoggingServiceV2_ListMonitoredResourceDescriptors_async", + "title": "logging listMonitoredResourceDescriptors Sample", + "origin": "API_DEFINITION", + "description": " Lists the descriptors for monitored resource types used by Logging.", + "canonical": true, + "file": "logging_service_v2.list_monitored_resource_descriptors.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_LoggingServiceV2_ListMonitoredResourceDescriptors_async", - "title": "logging listMonitoredResourceDescriptors Sample", - "origin": "API_DEFINITION", - "description": " Lists the descriptors for monitored resource types used by Logging.", - "canonical": true, - "file": "logging_service_v2.list_monitored_resource_descriptors.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 63, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "ListMonitoredResourceDescriptors", - "fullName": "google.logging.v2.LoggingServiceV2.ListMonitoredResourceDescriptors", - "async": true, - "parameters": [ - { - "name": "page_size", - "type": "TYPE_INT32" - }, - { - "name": "page_token", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.logging.v2.ListMonitoredResourceDescriptorsResponse", - "client": { - "shortName": "LoggingServiceV2Client", - "fullName": "google.logging.v2.LoggingServiceV2Client" - }, - "method": { - "shortName": "ListMonitoredResourceDescriptors", - "fullName": "google.logging.v2.LoggingServiceV2.ListMonitoredResourceDescriptors", - "service": { - "shortName": "LoggingServiceV2", - "fullName": "google.logging.v2.LoggingServiceV2" - } - } - } + "start": 25, + "end": 63, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "ListMonitoredResourceDescriptors", + "fullName": "google.logging.v2.LoggingServiceV2.ListMonitoredResourceDescriptors", + "async": true, + "parameters": [ + { + "name": "page_size", + "type": "TYPE_INT32" + }, + { + "name": "page_token", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.logging.v2.ListMonitoredResourceDescriptorsResponse", + "client": { + "shortName": "LoggingServiceV2Client", + "fullName": "google.logging.v2.LoggingServiceV2Client" }, + "method": { + "shortName": "ListMonitoredResourceDescriptors", + "fullName": "google.logging.v2.LoggingServiceV2.ListMonitoredResourceDescriptors", + "service": { + "shortName": "LoggingServiceV2", + "fullName": "google.logging.v2.LoggingServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_LoggingServiceV2_ListLogs_async", + "title": "logging listLogs Sample", + "origin": "API_DEFINITION", + "description": " Lists the logs in projects, organizations, folders, or billing accounts. Only logs that have entries are listed.", + "canonical": true, + "file": "logging_service_v2.list_logs.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_LoggingServiceV2_ListLogs_async", - "title": "logging listLogs Sample", - "origin": "API_DEFINITION", - "description": " Lists the logs in projects, organizations, folders, or billing accounts. Only logs that have entries are listed.", - "canonical": true, - "file": "logging_service_v2.list_logs.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 86, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "ListLogs", - "fullName": "google.logging.v2.LoggingServiceV2.ListLogs", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "resource_names", - "type": "TYPE_STRING[]" - }, - { - "name": "page_size", - "type": "TYPE_INT32" - }, - { - "name": "page_token", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.logging.v2.ListLogsResponse", - "client": { - "shortName": "LoggingServiceV2Client", - "fullName": "google.logging.v2.LoggingServiceV2Client" - }, - "method": { - "shortName": "ListLogs", - "fullName": "google.logging.v2.LoggingServiceV2.ListLogs", - "service": { - "shortName": "LoggingServiceV2", - "fullName": "google.logging.v2.LoggingServiceV2" - } - } - } + "start": 25, + "end": 86, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "ListLogs", + "fullName": "google.logging.v2.LoggingServiceV2.ListLogs", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "resource_names", + "type": "TYPE_STRING[]" + }, + { + "name": "page_size", + "type": "TYPE_INT32" + }, + { + "name": "page_token", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.logging.v2.ListLogsResponse", + "client": { + "shortName": "LoggingServiceV2Client", + "fullName": "google.logging.v2.LoggingServiceV2Client" }, + "method": { + "shortName": "ListLogs", + "fullName": "google.logging.v2.LoggingServiceV2.ListLogs", + "service": { + "shortName": "LoggingServiceV2", + "fullName": "google.logging.v2.LoggingServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_LoggingServiceV2_TailLogEntries_async", + "title": "logging tailLogEntries Sample", + "origin": "API_DEFINITION", + "description": " Streaming read of log entries as they are ingested. Until the stream is terminated, it will continue reading logs.", + "canonical": true, + "file": "logging_service_v2.tail_log_entries.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_LoggingServiceV2_TailLogEntries_async", - "title": "logging tailLogEntries Sample", - "origin": "API_DEFINITION", - "description": " Streaming read of log entries as they are ingested. Until the stream is terminated, it will continue reading logs.", - "canonical": true, - "file": "logging_service_v2.tail_log_entries.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 81, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "TailLogEntries", - "fullName": "google.logging.v2.LoggingServiceV2.TailLogEntries", - "async": true, - "parameters": [ - { - "name": "resource_names", - "type": "TYPE_STRING[]" - }, - { - "name": "filter", - "type": "TYPE_STRING" - }, - { - "name": "buffer_window", - "type": ".google.protobuf.Duration" - } - ], - "resultType": ".google.logging.v2.TailLogEntriesResponse", - "client": { - "shortName": "LoggingServiceV2Client", - "fullName": "google.logging.v2.LoggingServiceV2Client" - }, - "method": { - "shortName": "TailLogEntries", - "fullName": "google.logging.v2.LoggingServiceV2.TailLogEntries", - "service": { - "shortName": "LoggingServiceV2", - "fullName": "google.logging.v2.LoggingServiceV2" - } - } - } + "start": 25, + "end": 81, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "TailLogEntries", + "fullName": "google.logging.v2.LoggingServiceV2.TailLogEntries", + "async": true, + "parameters": [ + { + "name": "resource_names", + "type": "TYPE_STRING[]" + }, + { + "name": "filter", + "type": "TYPE_STRING" + }, + { + "name": "buffer_window", + "type": ".google.protobuf.Duration" + } + ], + "resultType": ".google.logging.v2.TailLogEntriesResponse", + "client": { + "shortName": "LoggingServiceV2Client", + "fullName": "google.logging.v2.LoggingServiceV2Client" }, + "method": { + "shortName": "TailLogEntries", + "fullName": "google.logging.v2.LoggingServiceV2.TailLogEntries", + "service": { + "shortName": "LoggingServiceV2", + "fullName": "google.logging.v2.LoggingServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_MetricsServiceV2_ListLogMetrics_async", + "title": "logging listLogMetrics Sample", + "origin": "API_DEFINITION", + "description": " Lists logs-based metrics.", + "canonical": true, + "file": "metrics_service_v2.list_log_metrics.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_MetricsServiceV2_ListLogMetrics_async", - "title": "logging listLogMetrics Sample", - "origin": "API_DEFINITION", - "description": " Lists logs-based metrics.", - "canonical": true, - "file": "metrics_service_v2.list_log_metrics.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 69, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "ListLogMetrics", - "fullName": "google.logging.v2.MetricsServiceV2.ListLogMetrics", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "page_token", - "type": "TYPE_STRING" - }, - { - "name": "page_size", - "type": "TYPE_INT32" - } - ], - "resultType": ".google.logging.v2.ListLogMetricsResponse", - "client": { - "shortName": "MetricsServiceV2Client", - "fullName": "google.logging.v2.MetricsServiceV2Client" - }, - "method": { - "shortName": "ListLogMetrics", - "fullName": "google.logging.v2.MetricsServiceV2.ListLogMetrics", - "service": { - "shortName": "MetricsServiceV2", - "fullName": "google.logging.v2.MetricsServiceV2" - } - } - } + "start": 25, + "end": 69, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "ListLogMetrics", + "fullName": "google.logging.v2.MetricsServiceV2.ListLogMetrics", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "page_token", + "type": "TYPE_STRING" + }, + { + "name": "page_size", + "type": "TYPE_INT32" + } + ], + "resultType": ".google.logging.v2.ListLogMetricsResponse", + "client": { + "shortName": "MetricsServiceV2Client", + "fullName": "google.logging.v2.MetricsServiceV2Client" }, + "method": { + "shortName": "ListLogMetrics", + "fullName": "google.logging.v2.MetricsServiceV2.ListLogMetrics", + "service": { + "shortName": "MetricsServiceV2", + "fullName": "google.logging.v2.MetricsServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_MetricsServiceV2_GetLogMetric_async", + "title": "logging getLogMetric Sample", + "origin": "API_DEFINITION", + "description": " Gets a logs-based metric.", + "canonical": true, + "file": "metrics_service_v2.get_log_metric.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_MetricsServiceV2_GetLogMetric_async", - "title": "logging getLogMetric Sample", - "origin": "API_DEFINITION", - "description": " Gets a logs-based metric.", - "canonical": true, - "file": "metrics_service_v2.get_log_metric.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 54, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "GetLogMetric", - "fullName": "google.logging.v2.MetricsServiceV2.GetLogMetric", - "async": true, - "parameters": [ - { - "name": "metric_name", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.logging.v2.LogMetric", - "client": { - "shortName": "MetricsServiceV2Client", - "fullName": "google.logging.v2.MetricsServiceV2Client" - }, - "method": { - "shortName": "GetLogMetric", - "fullName": "google.logging.v2.MetricsServiceV2.GetLogMetric", - "service": { - "shortName": "MetricsServiceV2", - "fullName": "google.logging.v2.MetricsServiceV2" - } - } - } + "start": 25, + "end": 54, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "GetLogMetric", + "fullName": "google.logging.v2.MetricsServiceV2.GetLogMetric", + "async": true, + "parameters": [ + { + "name": "metric_name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.logging.v2.LogMetric", + "client": { + "shortName": "MetricsServiceV2Client", + "fullName": "google.logging.v2.MetricsServiceV2Client" }, + "method": { + "shortName": "GetLogMetric", + "fullName": "google.logging.v2.MetricsServiceV2.GetLogMetric", + "service": { + "shortName": "MetricsServiceV2", + "fullName": "google.logging.v2.MetricsServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_MetricsServiceV2_CreateLogMetric_async", + "title": "logging createLogMetric Sample", + "origin": "API_DEFINITION", + "description": " Creates a logs-based metric.", + "canonical": true, + "file": "metrics_service_v2.create_log_metric.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_MetricsServiceV2_CreateLogMetric_async", - "title": "logging createLogMetric Sample", - "origin": "API_DEFINITION", - "description": " Creates a logs-based metric.", - "canonical": true, - "file": "metrics_service_v2.create_log_metric.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 61, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "CreateLogMetric", - "fullName": "google.logging.v2.MetricsServiceV2.CreateLogMetric", - "async": true, - "parameters": [ - { - "name": "parent", - "type": "TYPE_STRING" - }, - { - "name": "metric", - "type": ".google.logging.v2.LogMetric" - } - ], - "resultType": ".google.logging.v2.LogMetric", - "client": { - "shortName": "MetricsServiceV2Client", - "fullName": "google.logging.v2.MetricsServiceV2Client" - }, - "method": { - "shortName": "CreateLogMetric", - "fullName": "google.logging.v2.MetricsServiceV2.CreateLogMetric", - "service": { - "shortName": "MetricsServiceV2", - "fullName": "google.logging.v2.MetricsServiceV2" - } - } - } + "start": 25, + "end": 61, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "CreateLogMetric", + "fullName": "google.logging.v2.MetricsServiceV2.CreateLogMetric", + "async": true, + "parameters": [ + { + "name": "parent", + "type": "TYPE_STRING" + }, + { + "name": "metric", + "type": ".google.logging.v2.LogMetric" + } + ], + "resultType": ".google.logging.v2.LogMetric", + "client": { + "shortName": "MetricsServiceV2Client", + "fullName": "google.logging.v2.MetricsServiceV2Client" }, + "method": { + "shortName": "CreateLogMetric", + "fullName": "google.logging.v2.MetricsServiceV2.CreateLogMetric", + "service": { + "shortName": "MetricsServiceV2", + "fullName": "google.logging.v2.MetricsServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_MetricsServiceV2_UpdateLogMetric_async", + "title": "logging updateLogMetric Sample", + "origin": "API_DEFINITION", + "description": " Creates or updates a logs-based metric.", + "canonical": true, + "file": "metrics_service_v2.update_log_metric.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_MetricsServiceV2_UpdateLogMetric_async", - "title": "logging updateLogMetric Sample", - "origin": "API_DEFINITION", - "description": " Creates or updates a logs-based metric.", - "canonical": true, - "file": "metrics_service_v2.update_log_metric.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 62, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "UpdateLogMetric", - "fullName": "google.logging.v2.MetricsServiceV2.UpdateLogMetric", - "async": true, - "parameters": [ - { - "name": "metric_name", - "type": "TYPE_STRING" - }, - { - "name": "metric", - "type": ".google.logging.v2.LogMetric" - } - ], - "resultType": ".google.logging.v2.LogMetric", - "client": { - "shortName": "MetricsServiceV2Client", - "fullName": "google.logging.v2.MetricsServiceV2Client" - }, - "method": { - "shortName": "UpdateLogMetric", - "fullName": "google.logging.v2.MetricsServiceV2.UpdateLogMetric", - "service": { - "shortName": "MetricsServiceV2", - "fullName": "google.logging.v2.MetricsServiceV2" - } - } - } + "start": 25, + "end": 62, + "type": "FULL" + } + ], + "clientMethod": { + "shortName": "UpdateLogMetric", + "fullName": "google.logging.v2.MetricsServiceV2.UpdateLogMetric", + "async": true, + "parameters": [ + { + "name": "metric_name", + "type": "TYPE_STRING" + }, + { + "name": "metric", + "type": ".google.logging.v2.LogMetric" + } + ], + "resultType": ".google.logging.v2.LogMetric", + "client": { + "shortName": "MetricsServiceV2Client", + "fullName": "google.logging.v2.MetricsServiceV2Client" }, + "method": { + "shortName": "UpdateLogMetric", + "fullName": "google.logging.v2.MetricsServiceV2.UpdateLogMetric", + "service": { + "shortName": "MetricsServiceV2", + "fullName": "google.logging.v2.MetricsServiceV2" + } + } + } + }, + { + "regionTag": "logging_v2_generated_MetricsServiceV2_DeleteLogMetric_async", + "title": "logging deleteLogMetric Sample", + "origin": "API_DEFINITION", + "description": " Deletes a logs-based metric.", + "canonical": true, + "file": "metrics_service_v2.delete_log_metric.js", + "language": "JAVASCRIPT", + "segments": [ { - "regionTag": "logging_v2_generated_MetricsServiceV2_DeleteLogMetric_async", - "title": "logging deleteLogMetric Sample", - "origin": "API_DEFINITION", - "description": " Deletes a logs-based metric.", - "canonical": true, - "file": "metrics_service_v2.delete_log_metric.js", - "language": "JAVASCRIPT", - "segments": [ - { - "start": 25, - "end": 54, - "type": "FULL" - } - ], - "clientMethod": { - "shortName": "DeleteLogMetric", - "fullName": "google.logging.v2.MetricsServiceV2.DeleteLogMetric", - "async": true, - "parameters": [ - { - "name": "metric_name", - "type": "TYPE_STRING" - } - ], - "resultType": ".google.protobuf.Empty", - "client": { - "shortName": "MetricsServiceV2Client", - "fullName": "google.logging.v2.MetricsServiceV2Client" - }, - "method": { - "shortName": "DeleteLogMetric", - "fullName": "google.logging.v2.MetricsServiceV2.DeleteLogMetric", - "service": { - "shortName": "MetricsServiceV2", - "fullName": "google.logging.v2.MetricsServiceV2" - } - } - } + "start": 25, + "end": 54, + "type": "FULL" } - ] -} \ No newline at end of file + ], + "clientMethod": { + "shortName": "DeleteLogMetric", + "fullName": "google.logging.v2.MetricsServiceV2.DeleteLogMetric", + "async": true, + "parameters": [ + { + "name": "metric_name", + "type": "TYPE_STRING" + } + ], + "resultType": ".google.protobuf.Empty", + "client": { + "shortName": "MetricsServiceV2Client", + "fullName": "google.logging.v2.MetricsServiceV2Client" + }, + "method": { + "shortName": "DeleteLogMetric", + "fullName": "google.logging.v2.MetricsServiceV2.DeleteLogMetric", + "service": { + "shortName": "MetricsServiceV2", + "fullName": "google.logging.v2.MetricsServiceV2" + } + } + } + } + ] +} diff --git a/handwritten/logging/src/v2/config_service_v2_client.ts b/handwritten/logging/src/v2/config_service_v2_client.ts index 11d0e92a5fd3..64450c3c4734 100644 --- a/handwritten/logging/src/v2/config_service_v2_client.ts +++ b/handwritten/logging/src/v2/config_service_v2_client.ts @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -28,9 +28,10 @@ import type { PaginationCallback, GaxCall, } from 'google-gax'; -import {Transform} from 'stream'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -52,9 +53,11 @@ export class ConfigServiceV2Client { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; + private _log = logging.log('logging'); + auth: gax.GoogleAuth; descriptors: Descriptors = { page: {}, @@ -63,10 +66,10 @@ export class ConfigServiceV2Client { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - configServiceV2Stub?: Promise<{[name: string]: Function}>; + configServiceV2Stub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ConfigServiceV2Client. @@ -90,7 +93,7 @@ export class ConfigServiceV2Client { * 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. @@ -142,7 +145,7 @@ export class ConfigServiceV2Client { const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // Request numeric enum values if REST transport is used. opts.numericEnums = true; @@ -345,7 +348,7 @@ export class ConfigServiceV2Client { ), }; - const protoFilesRoot = this._gaxModule.protobuf.Root.fromJSON(jsonProtos); + const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); // This API contains "long-running operations", which return a // an Operation object that allows for tracking of the operation, // rather than holding a request open. @@ -383,20 +386,20 @@ export class ConfigServiceV2Client { selector: 'google.longrunning.Operations.GetOperation', get: '/v2/{name=*/*/locations/*/operations/*}', additional_bindings: [ - {get: '/v2/{name=projects/*/locations/*/operations/*}'}, - {get: '/v2/{name=organizations/*/locations/*/operations/*}'}, - {get: '/v2/{name=folders/*/locations/*/operations/*}'}, - {get: '/v2/{name=billingAccounts/*/locations/*/operations/*}'}, + { get: '/v2/{name=projects/*/locations/*/operations/*}' }, + { get: '/v2/{name=organizations/*/locations/*/operations/*}' }, + { get: '/v2/{name=folders/*/locations/*/operations/*}' }, + { get: '/v2/{name=billingAccounts/*/locations/*/operations/*}' }, ], }, { selector: 'google.longrunning.Operations.ListOperations', get: '/v2/{name=*/*/locations/*}/operations', additional_bindings: [ - {get: '/v2/{name=projects/*/locations/*}/operations'}, - {get: '/v2/{name=organizations/*/locations/*}/operations'}, - {get: '/v2/{name=folders/*/locations/*}/operations'}, - {get: '/v2/{name=billingAccounts/*/locations/*}/operations'}, + { get: '/v2/{name=projects/*/locations/*}/operations' }, + { get: '/v2/{name=organizations/*/locations/*}/operations' }, + { get: '/v2/{name=folders/*/locations/*}/operations' }, + { get: '/v2/{name=billingAccounts/*/locations/*}/operations' }, ], }, ]; @@ -468,7 +471,7 @@ export class ConfigServiceV2Client { 'google.logging.v2.ConfigServiceV2', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')}, + { 'x-goog-api-client': clientHeader.join(' ') }, ); // Set up a dictionary of "inner API calls"; the core implementation @@ -508,7 +511,7 @@ export class ConfigServiceV2Client { (this._protos as any).google.logging.v2.ConfigServiceV2, this._opts, this._providedCustomServicePath, - ) as Promise<{[method: string]: Function}>; + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -548,7 +551,7 @@ export class ConfigServiceV2Client { ]; for (const methodName of configServiceV2StubMethods) { const callPromise = this.configServiceV2Stub.then( - stub => + (stub) => (...args: Array<{}>) => { if (this._terminated) { return Promise.reject('The client has already been closed.'); @@ -755,8 +758,50 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.getBucket(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('getBucket request %j', request); + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IGetBucketRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getBucket response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getBucket(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IGetBucketRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getBucket response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Creates a log bucket that can be used to store log entries. After a bucket @@ -852,8 +897,50 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize(); - return this.innerApiCalls.createBucket(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('createBucket request %j', request); + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.ICreateBucketRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createBucket response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .createBucket(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.ICreateBucketRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createBucket response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Updates a log bucket. @@ -959,8 +1046,50 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.updateBucket(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('updateBucket request %j', request); + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IUpdateBucketRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('updateBucket response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .updateBucket(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IUpdateBucketRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateBucket response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Deletes a log bucket. @@ -1054,8 +1183,50 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.deleteBucket(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('deleteBucket request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteBucketRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteBucket response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .deleteBucket(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteBucketRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteBucket response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Undeletes a log bucket. A bucket that has been deleted can be undeleted @@ -1146,8 +1317,50 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.undeleteBucket(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('undeleteBucket request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IUndeleteBucketRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('undeleteBucket response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .undeleteBucket(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IUndeleteBucketRequest | undefined, + {} | undefined, + ]) => { + this._log.info('undeleteBucket response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Gets a view on a log bucket.. @@ -1234,8 +1447,50 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.getView(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('getView request %j', request); + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IGetViewRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getView response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getView(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IGetViewRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getView response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Creates a view over log entries in a log bucket. A bucket may contain a @@ -1329,8 +1584,50 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize(); - return this.innerApiCalls.createView(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('createView request %j', request); + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.ICreateViewRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createView response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .createView(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogView, + protos.google.logging.v2.ICreateViewRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createView response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Updates a view on a log bucket. This method replaces the following fields @@ -1432,8 +1729,50 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.updateView(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('updateView request %j', request); + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IUpdateViewRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('updateView response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .updateView(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogView, + protos.google.logging.v2.IUpdateViewRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateView response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Deletes a view on a log bucket. @@ -1523,8 +1862,50 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.deleteView(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('deleteView request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteViewRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteView response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .deleteView(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteViewRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteView response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Gets a sink. @@ -1614,8 +1995,50 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ sink_name: request.sinkName ?? '', }); - this.initialize(); - return this.innerApiCalls.getSink(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('getSink request %j', request); + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IGetSinkRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getSink response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getSink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IGetSinkRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getSink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Creates a sink that exports specified log entries to a destination. The @@ -1725,8 +2148,50 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize(); - return this.innerApiCalls.createSink(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('createSink request %j', request); + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.ICreateSinkRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createSink response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .createSink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.ICreateSinkRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createSink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Updates a sink. This method replaces the following fields in the existing @@ -1853,8 +2318,50 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ sink_name: request.sinkName ?? '', }); - this.initialize(); - return this.innerApiCalls.updateSink(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('updateSink request %j', request); + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IUpdateSinkRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('updateSink response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .updateSink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogSink, + protos.google.logging.v2.IUpdateSinkRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateSink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Deletes a sink. If the sink has a unique `writer_identity`, then that @@ -1946,8 +2453,50 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ sink_name: request.sinkName ?? '', }); - this.initialize(); - return this.innerApiCalls.deleteSink(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('deleteSink request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteSinkRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteSink response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .deleteSink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteSinkRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteSink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Gets a link. @@ -2033,8 +2582,50 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.getLink(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('getLink request %j', request); + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILink, + protos.google.logging.v2.IGetLinkRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getLink response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILink, + protos.google.logging.v2.IGetLinkRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getLink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Gets the description of an exclusion in the _Default sink. @@ -2124,8 +2715,50 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.getExclusion(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('getExclusion request %j', request); + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IGetExclusionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getExclusion response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getExclusion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IGetExclusionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getExclusion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Creates a new exclusion in the _Default sink in a specified parent @@ -2221,8 +2854,50 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize(); - return this.innerApiCalls.createExclusion(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('createExclusion request %j', request); + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.ICreateExclusionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createExclusion response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .createExclusion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.ICreateExclusionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createExclusion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Changes one or more properties of an existing exclusion in the _Default @@ -2325,8 +3000,50 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.updateExclusion(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('updateExclusion request %j', request); + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IUpdateExclusionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('updateExclusion response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .updateExclusion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogExclusion, + protos.google.logging.v2.IUpdateExclusionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateExclusion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Deletes an exclusion in the _Default sink. @@ -2416,8 +3133,50 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.deleteExclusion(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('deleteExclusion request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteExclusionRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteExclusion response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .deleteExclusion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteExclusionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteExclusion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Gets the Logging CMEK settings for the given resource. @@ -2521,8 +3280,50 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.getCmekSettings(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('getCmekSettings request %j', request); + const wrappedCallback: + | Callback< + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IGetCmekSettingsRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getCmekSettings response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getCmekSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IGetCmekSettingsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getCmekSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Updates the Log Router CMEK settings for the given resource. @@ -2646,8 +3447,52 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.updateCmekSettings(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('updateCmekSettings request %j', request); + const wrappedCallback: + | Callback< + protos.google.logging.v2.ICmekSettings, + | protos.google.logging.v2.IUpdateCmekSettingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('updateCmekSettings response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .updateCmekSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ICmekSettings, + protos.google.logging.v2.IUpdateCmekSettingsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateCmekSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Gets the Log Router settings for the given resource. @@ -2751,8 +3596,50 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.getSettings(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('getSettings request %j', request); + const wrappedCallback: + | Callback< + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IGetSettingsRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getSettings response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IGetSettingsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Updates the Log Router settings for the given resource. @@ -2872,8 +3759,50 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.updateSettings(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('updateSettings request %j', request); + const wrappedCallback: + | Callback< + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IUpdateSettingsRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('updateSettings response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .updateSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ISettings, + protos.google.logging.v2.IUpdateSettingsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** @@ -2991,8 +3920,40 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize(); - return this.innerApiCalls.createBucketAsync(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IBucketMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('createBucketAsync response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('createBucketAsync request %j', request); + return this.innerApiCalls + .createBucketAsync(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IBucketMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createBucketAsync response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } /** * Check the status of the long running operation returned by `createBucketAsync()`. @@ -3013,9 +3974,10 @@ export class ConfigServiceV2Client { protos.google.logging.v2.BucketMetadata > > { + this._log.info('createBucketAsync long-running'); const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( - {name}, + { name }, ); const [operation] = await this.operationsClient.getOperation(request); const decodeOperation = new this._gaxModule.Operation( @@ -3152,8 +4114,40 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.updateBucketAsync(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IBucketMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('updateBucketAsync response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('updateBucketAsync request %j', request); + return this.innerApiCalls + .updateBucketAsync(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.logging.v2.ILogBucket, + protos.google.logging.v2.IBucketMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('updateBucketAsync response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } /** * Check the status of the long running operation returned by `updateBucketAsync()`. @@ -3174,9 +4168,10 @@ export class ConfigServiceV2Client { protos.google.logging.v2.BucketMetadata > > { + this._log.info('updateBucketAsync long-running'); const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( - {name}, + { name }, ); const [operation] = await this.operationsClient.getOperation(request); const decodeOperation = new this._gaxModule.Operation( @@ -3301,8 +4296,40 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize(); - return this.innerApiCalls.createLink(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.logging.v2.ILink, + protos.google.logging.v2.ILinkMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('createLink response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('createLink request %j', request); + return this.innerApiCalls + .createLink(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.logging.v2.ILink, + protos.google.logging.v2.ILinkMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createLink response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } /** * Check the status of the long running operation returned by `createLink()`. @@ -3323,9 +4350,10 @@ export class ConfigServiceV2Client { protos.google.logging.v2.LinkMetadata > > { + this._log.info('createLink long-running'); const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( - {name}, + { name }, ); const [operation] = await this.operationsClient.getOperation(request); const decodeOperation = new this._gaxModule.Operation( @@ -3443,8 +4471,40 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ name: request.name ?? '', }); - this.initialize(); - return this.innerApiCalls.deleteLink(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.ILinkMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('deleteLink response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('deleteLink request %j', request); + return this.innerApiCalls + .deleteLink(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.ILinkMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('deleteLink response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } /** * Check the status of the long running operation returned by `deleteLink()`. @@ -3465,9 +4525,10 @@ export class ConfigServiceV2Client { protos.google.logging.v2.LinkMetadata > > { + this._log.info('deleteLink long-running'); const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( - {name}, + { name }, ); const [operation] = await this.operationsClient.getOperation(request); const decodeOperation = new this._gaxModule.Operation( @@ -3584,8 +4645,40 @@ export class ConfigServiceV2Client { options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize(); - return this.innerApiCalls.copyLogEntries(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.logging.v2.ICopyLogEntriesResponse, + protos.google.logging.v2.ICopyLogEntriesMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('copyLogEntries response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('copyLogEntries request %j', request); + return this.innerApiCalls + .copyLogEntries(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.logging.v2.ICopyLogEntriesResponse, + protos.google.logging.v2.ICopyLogEntriesMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('copyLogEntries response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } /** * Check the status of the long running operation returned by `copyLogEntries()`. @@ -3606,9 +4699,10 @@ export class ConfigServiceV2Client { protos.google.logging.v2.CopyLogEntriesMetadata > > { + this._log.info('copyLogEntries long-running'); const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( - {name}, + { name }, ); const [operation] = await this.operationsClient.getOperation(request); const decodeOperation = new this._gaxModule.Operation( @@ -3721,12 +4815,38 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize(); - return this.innerApiCalls.listBuckets(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListBucketsRequest, + protos.google.logging.v2.IListBucketsResponse | null | undefined, + protos.google.logging.v2.ILogBucket + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listBuckets values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listBuckets request %j', request); + return this.innerApiCalls + .listBuckets(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.logging.v2.ILogBucket[], + protos.google.logging.v2.IListBucketsRequest | null, + protos.google.logging.v2.IListBucketsResponse, + ]) => { + this._log.info('listBuckets values %j', response); + return [response, input, output]; + }, + ); } /** - * Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream object. + * Equivalent to `listBuckets`, but returns a NodeJS Stream object. * @param {Object} request * The request object that will be sent. * @param {string} request.parent @@ -3774,7 +4894,10 @@ export class ConfigServiceV2Client { }); const defaultCallSettings = this._defaults['listBuckets']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('listBuckets stream %j', request); return this.descriptors.page.listBuckets.createStream( this.innerApiCalls.listBuckets as GaxCall, request, @@ -3834,7 +4957,10 @@ export class ConfigServiceV2Client { }); const defaultCallSettings = this._defaults['listBuckets']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('listBuckets iterate %j', request); return this.descriptors.page.listBuckets.asyncIterate( this.innerApiCalls['listBuckets'] as GaxCall, request as {}, @@ -3935,12 +5061,38 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize(); - return this.innerApiCalls.listViews(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListViewsRequest, + protos.google.logging.v2.IListViewsResponse | null | undefined, + protos.google.logging.v2.ILogView + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listViews values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listViews request %j', request); + return this.innerApiCalls + .listViews(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.logging.v2.ILogView[], + protos.google.logging.v2.IListViewsRequest | null, + protos.google.logging.v2.IListViewsResponse, + ]) => { + this._log.info('listViews values %j', response); + return [response, input, output]; + }, + ); } /** - * Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream object. + * Equivalent to `listViews`, but returns a NodeJS Stream object. * @param {Object} request * The request object that will be sent. * @param {string} request.parent @@ -3982,7 +5134,10 @@ export class ConfigServiceV2Client { }); const defaultCallSettings = this._defaults['listViews']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('listViews stream %j', request); return this.descriptors.page.listViews.createStream( this.innerApiCalls.listViews as GaxCall, request, @@ -4036,7 +5191,10 @@ export class ConfigServiceV2Client { }); const defaultCallSettings = this._defaults['listViews']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('listViews iterate %j', request); return this.descriptors.page.listViews.asyncIterate( this.innerApiCalls['listViews'] as GaxCall, request as {}, @@ -4139,12 +5297,38 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize(); - return this.innerApiCalls.listSinks(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListSinksRequest, + protos.google.logging.v2.IListSinksResponse | null | undefined, + protos.google.logging.v2.ILogSink + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listSinks values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listSinks request %j', request); + return this.innerApiCalls + .listSinks(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.logging.v2.ILogSink[], + protos.google.logging.v2.IListSinksRequest | null, + protos.google.logging.v2.IListSinksResponse, + ]) => { + this._log.info('listSinks values %j', response); + return [response, input, output]; + }, + ); } /** - * Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream object. + * Equivalent to `listSinks`, but returns a NodeJS Stream object. * @param {Object} request * The request object that will be sent. * @param {string} request.parent @@ -4188,7 +5372,10 @@ export class ConfigServiceV2Client { }); const defaultCallSettings = this._defaults['listSinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('listSinks stream %j', request); return this.descriptors.page.listSinks.createStream( this.innerApiCalls.listSinks as GaxCall, request, @@ -4244,7 +5431,10 @@ export class ConfigServiceV2Client { }); const defaultCallSettings = this._defaults['listSinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('listSinks iterate %j', request); return this.descriptors.page.listSinks.asyncIterate( this.innerApiCalls['listSinks'] as GaxCall, request as {}, @@ -4344,12 +5534,38 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize(); - return this.innerApiCalls.listLinks(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListLinksRequest, + protos.google.logging.v2.IListLinksResponse | null | undefined, + protos.google.logging.v2.ILink + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listLinks values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listLinks request %j', request); + return this.innerApiCalls + .listLinks(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.logging.v2.ILink[], + protos.google.logging.v2.IListLinksRequest | null, + protos.google.logging.v2.IListLinksResponse, + ]) => { + this._log.info('listLinks values %j', response); + return [response, input, output]; + }, + ); } /** - * Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream object. + * Equivalent to `listLinks`, but returns a NodeJS Stream object. * @param {Object} request * The request object that will be sent. * @param {string} request.parent @@ -4390,7 +5606,10 @@ export class ConfigServiceV2Client { }); const defaultCallSettings = this._defaults['listLinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('listLinks stream %j', request); return this.descriptors.page.listLinks.createStream( this.innerApiCalls.listLinks as GaxCall, request, @@ -4443,7 +5662,10 @@ export class ConfigServiceV2Client { }); const defaultCallSettings = this._defaults['listLinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('listLinks iterate %j', request); return this.descriptors.page.listLinks.asyncIterate( this.innerApiCalls['listLinks'] as GaxCall, request as {}, @@ -4546,12 +5768,38 @@ export class ConfigServiceV2Client { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize(); - return this.innerApiCalls.listExclusions(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListExclusionsRequest, + protos.google.logging.v2.IListExclusionsResponse | null | undefined, + protos.google.logging.v2.ILogExclusion + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listExclusions values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listExclusions request %j', request); + return this.innerApiCalls + .listExclusions(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.logging.v2.ILogExclusion[], + protos.google.logging.v2.IListExclusionsRequest | null, + protos.google.logging.v2.IListExclusionsResponse, + ]) => { + this._log.info('listExclusions values %j', response); + return [response, input, output]; + }, + ); } /** - * Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream object. + * Equivalent to `listExclusions`, but returns a NodeJS Stream object. * @param {Object} request * The request object that will be sent. * @param {string} request.parent @@ -4595,7 +5843,10 @@ export class ConfigServiceV2Client { }); const defaultCallSettings = this._defaults['listExclusions']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('listExclusions stream %j', request); return this.descriptors.page.listExclusions.createStream( this.innerApiCalls.listExclusions as GaxCall, request, @@ -4651,7 +5902,10 @@ export class ConfigServiceV2Client { }); const defaultCallSettings = this._defaults['listExclusions']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('listExclusions iterate %j', request); return this.descriptors.page.listExclusions.asyncIterate( this.innerApiCalls['listExclusions'] as GaxCall, request as {}, @@ -4690,7 +5944,7 @@ export class ConfigServiceV2Client { */ getOperation( request: protos.google.longrunning.GetOperationRequest, - options?: + optionsOrCallback?: | gax.CallOptions | Callback< protos.google.longrunning.Operation, @@ -4703,6 +5957,20 @@ export class ConfigServiceV2Client { {} | 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 ?? '', + }); return this.operationsClient.getOperation(request, options, callback); } /** @@ -4738,7 +6006,14 @@ export class ConfigServiceV2Client { listOperationsAsync( request: protos.google.longrunning.ListOperationsRequest, options?: gax.CallOptions, - ): AsyncIterable { + ): 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); } /** @@ -4774,11 +6049,11 @@ export class ConfigServiceV2Client { */ cancelOperation( request: protos.google.longrunning.CancelOperationRequest, - options?: + optionsOrCallback?: | gax.CallOptions | Callback< - protos.google.protobuf.Empty, protos.google.longrunning.CancelOperationRequest, + protos.google.protobuf.Empty, {} | undefined | null >, callback?: Callback< @@ -4787,9 +6062,22 @@ export class ConfigServiceV2Client { {} | 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 ?? '', + }); return this.operationsClient.cancelOperation(request, options, callback); } - /** * Deletes a long-running operation. This method indicates that the client is * no longer interested in the operation result. It does not cancel the @@ -4817,7 +6105,7 @@ export class ConfigServiceV2Client { */ deleteOperation( request: protos.google.longrunning.DeleteOperationRequest, - options?: + optionsOrCallback?: | gax.CallOptions | Callback< protos.google.protobuf.Empty, @@ -4830,6 +6118,20 @@ export class ConfigServiceV2Client { {} | 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 ?? '', + }); return this.operationsClient.deleteOperation(request, options, callback); } @@ -6541,10 +7843,11 @@ export class ConfigServiceV2Client { */ close(): Promise { if (this.configServiceV2Stub && !this._terminated) { - return this.configServiceV2Stub.then(stub => { + return this.configServiceV2Stub.then((stub) => { + this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); - this.operationsClient.close(); + void this.operationsClient.close(); }); } return Promise.resolve(); diff --git a/handwritten/logging/src/v2/index.ts b/handwritten/logging/src/v2/index.ts index 2cc712044a0a..2aca5a517ff1 100644 --- a/handwritten/logging/src/v2/index.ts +++ b/handwritten/logging/src/v2/index.ts @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,6 +16,6 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {ConfigServiceV2Client} from './config_service_v2_client'; -export {LoggingServiceV2Client} from './logging_service_v2_client'; -export {MetricsServiceV2Client} from './metrics_service_v2_client'; +export { ConfigServiceV2Client } from './config_service_v2_client'; +export { LoggingServiceV2Client } from './logging_service_v2_client'; +export { MetricsServiceV2Client } from './metrics_service_v2_client'; diff --git a/handwritten/logging/src/v2/logging_service_v2_client.ts b/handwritten/logging/src/v2/logging_service_v2_client.ts index 5995243420cb..15ed400567ba 100644 --- a/handwritten/logging/src/v2/logging_service_v2_client.ts +++ b/handwritten/logging/src/v2/logging_service_v2_client.ts @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 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,9 +26,10 @@ import type { PaginationCallback, GaxCall, } from 'google-gax'; -import {Transform, PassThrough} from 'stream'; +import { Transform, PassThrough } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -50,9 +51,11 @@ export class LoggingServiceV2Client { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; + private _log = logging.log('logging'); + auth: gax.GoogleAuth; descriptors: Descriptors = { page: {}, @@ -61,9 +64,9 @@ export class LoggingServiceV2Client { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - loggingServiceV2Stub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + loggingServiceV2Stub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of LoggingServiceV2Client. @@ -87,7 +90,7 @@ export class LoggingServiceV2Client { * 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. @@ -139,7 +142,7 @@ export class LoggingServiceV2Client { const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // Request numeric enum values if REST transport is used. opts.numericEnums = true; @@ -339,7 +342,7 @@ export class LoggingServiceV2Client { ), }; - const protoFilesRoot = this._gaxModule.protobuf.Root.fromJSON(jsonProtos); + const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); // Some methods on this API support automatically batching // requests; denote this. @@ -360,7 +363,7 @@ export class LoggingServiceV2Client { 'google.logging.v2.LoggingServiceV2', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')}, + { 'x-goog-api-client': clientHeader.join(' ') }, ); // Set up a dictionary of "inner API calls"; the core implementation @@ -400,7 +403,7 @@ export class LoggingServiceV2Client { (this._protos as any).google.logging.v2.LoggingServiceV2, this._opts, this._providedCustomServicePath, - ) as Promise<{[method: string]: Function}>; + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -414,11 +417,11 @@ export class LoggingServiceV2Client { ]; for (const methodName of loggingServiceV2StubMethods) { const callPromise = this.loggingServiceV2Stub.then( - stub => + (stub) => (...args: Array<{}>) => { if (this._terminated) { if (methodName in this.descriptors.stream) { - const stream = new PassThrough(); + const stream = new PassThrough({ objectMode: true }); setImmediate(() => { stream.emit( 'error', @@ -641,8 +644,50 @@ export class LoggingServiceV2Client { this._gaxModule.routingHeader.fromParams({ log_name: request.logName ?? '', }); - this.initialize(); - return this.innerApiCalls.deleteLog(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('deleteLog request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteLog response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .deleteLog(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteLog response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Writes log entries to Logging. This API method is the @@ -792,8 +837,50 @@ export class LoggingServiceV2Client { options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize(); - return this.innerApiCalls.writeLogEntries(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('writeLogEntries request %j', request); + const wrappedCallback: + | Callback< + protos.google.logging.v2.IWriteLogEntriesResponse, + protos.google.logging.v2.IWriteLogEntriesRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('writeLogEntries response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .writeLogEntries(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.IWriteLogEntriesResponse, + protos.google.logging.v2.IWriteLogEntriesRequest | undefined, + {} | undefined, + ]) => { + this._log.info('writeLogEntries response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** @@ -812,7 +899,10 @@ export class LoggingServiceV2Client { * region_tag:logging_v2_generated_LoggingServiceV2_TailLogEntries_async */ tailLogEntries(options?: CallOptions): gax.CancellableStream { - this.initialize(); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('tailLogEntries stream %j', options); return this.innerApiCalls.tailLogEntries(null, options); } @@ -936,12 +1026,38 @@ export class LoggingServiceV2Client { options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize(); - return this.innerApiCalls.listLogEntries(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListLogEntriesRequest, + protos.google.logging.v2.IListLogEntriesResponse | null | undefined, + protos.google.logging.v2.ILogEntry + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listLogEntries values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listLogEntries request %j', request); + return this.innerApiCalls + .listLogEntries(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.logging.v2.ILogEntry[], + protos.google.logging.v2.IListLogEntriesRequest | null, + protos.google.logging.v2.IListLogEntriesResponse, + ]) => { + this._log.info('listLogEntries values %j', response); + return [response, input, output]; + }, + ); } /** - * Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream object. + * Equivalent to `listLogEntries`, but returns a NodeJS Stream object. * @param {Object} request * The request object that will be sent. * @param {string[]} request.resourceNames @@ -1006,7 +1122,10 @@ export class LoggingServiceV2Client { options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listLogEntries']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('listLogEntries stream %j', request); return this.descriptors.page.listLogEntries.createStream( this.innerApiCalls.listLogEntries as GaxCall, request, @@ -1083,7 +1202,10 @@ export class LoggingServiceV2Client { options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listLogEntries']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('listLogEntries iterate %j', request); return this.descriptors.page.listLogEntries.asyncIterate( this.innerApiCalls['listLogEntries'] as GaxCall, request as {}, @@ -1183,16 +1305,43 @@ export class LoggingServiceV2Client { options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - this.initialize(); - return this.innerApiCalls.listMonitoredResourceDescriptors( - request, - options, - callback, - ); + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest, + | protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse + | null + | undefined, + protos.google.api.IMonitoredResourceDescriptor + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listMonitoredResourceDescriptors values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listMonitoredResourceDescriptors request %j', request); + return this.innerApiCalls + .listMonitoredResourceDescriptors(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.api.IMonitoredResourceDescriptor[], + protos.google.logging.v2.IListMonitoredResourceDescriptorsRequest | null, + protos.google.logging.v2.IListMonitoredResourceDescriptorsResponse, + ]) => { + this._log.info( + 'listMonitoredResourceDescriptors values %j', + response, + ); + return [response, input, output]; + }, + ); } /** - * Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream object. + * Equivalent to `listMonitoredResourceDescriptors`, but returns a NodeJS Stream object. * @param {Object} request * The request object that will be sent. * @param {number} [request.pageSize] @@ -1226,7 +1375,10 @@ export class LoggingServiceV2Client { const defaultCallSettings = this._defaults['listMonitoredResourceDescriptors']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('listMonitoredResourceDescriptors stream %j', request); return this.descriptors.page.listMonitoredResourceDescriptors.createStream( this.innerApiCalls.listMonitoredResourceDescriptors as GaxCall, request, @@ -1272,7 +1424,10 @@ export class LoggingServiceV2Client { const defaultCallSettings = this._defaults['listMonitoredResourceDescriptors']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('listMonitoredResourceDescriptors iterate %j', request); return this.descriptors.page.listMonitoredResourceDescriptors.asyncIterate( this.innerApiCalls['listMonitoredResourceDescriptors'] as GaxCall, request as {}, @@ -1392,12 +1547,38 @@ export class LoggingServiceV2Client { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize(); - return this.innerApiCalls.listLogs(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListLogsRequest, + protos.google.logging.v2.IListLogsResponse | null | undefined, + string + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listLogs values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listLogs request %j', request); + return this.innerApiCalls + .listLogs(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + string[], + protos.google.logging.v2.IListLogsRequest | null, + protos.google.logging.v2.IListLogsResponse, + ]) => { + this._log.info('listLogs values %j', response); + return [response, input, output]; + }, + ); } /** - * Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream object. + * Equivalent to `listLogs`, but returns a NodeJS Stream object. * @param {Object} request * The request object that will be sent. * @param {string} request.parent @@ -1457,7 +1638,10 @@ export class LoggingServiceV2Client { }); const defaultCallSettings = this._defaults['listLogs']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('listLogs stream %j', request); return this.descriptors.page.listLogs.createStream( this.innerApiCalls.listLogs as GaxCall, request, @@ -1529,7 +1713,10 @@ export class LoggingServiceV2Client { }); const defaultCallSettings = this._defaults['listLogs']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('listLogs iterate %j', request); return this.descriptors.page.listLogs.asyncIterate( this.innerApiCalls['listLogs'] as GaxCall, request as {}, @@ -3208,7 +3395,8 @@ export class LoggingServiceV2Client { */ close(): Promise { if (this.loggingServiceV2Stub && !this._terminated) { - return this.loggingServiceV2Stub.then(stub => { + return this.loggingServiceV2Stub.then((stub) => { + this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); }); diff --git a/handwritten/logging/src/v2/metrics_service_v2_client.ts b/handwritten/logging/src/v2/metrics_service_v2_client.ts index 5c00af6ca8b4..3c0ff03971cb 100644 --- a/handwritten/logging/src/v2/metrics_service_v2_client.ts +++ b/handwritten/logging/src/v2/metrics_service_v2_client.ts @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 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,9 +26,10 @@ import type { PaginationCallback, GaxCall, } from 'google-gax'; -import {Transform} from 'stream'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -50,9 +51,11 @@ export class MetricsServiceV2Client { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; + private _log = logging.log('logging'); + auth: gax.GoogleAuth; descriptors: Descriptors = { page: {}, @@ -61,9 +64,9 @@ export class MetricsServiceV2Client { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - metricsServiceV2Stub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + metricsServiceV2Stub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of MetricsServiceV2Client. @@ -87,7 +90,7 @@ export class MetricsServiceV2Client { * 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. @@ -139,7 +142,7 @@ export class MetricsServiceV2Client { const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts); // Request numeric enum values if REST transport is used. opts.numericEnums = true; @@ -324,7 +327,7 @@ export class MetricsServiceV2Client { 'google.logging.v2.MetricsServiceV2', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')}, + { 'x-goog-api-client': clientHeader.join(' ') }, ); // Set up a dictionary of "inner API calls"; the core implementation @@ -364,7 +367,7 @@ export class MetricsServiceV2Client { (this._protos as any).google.logging.v2.MetricsServiceV2, this._opts, this._providedCustomServicePath, - ) as Promise<{[method: string]: Function}>; + ) as Promise<{ [method: string]: Function }>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -377,7 +380,7 @@ export class MetricsServiceV2Client { ]; for (const methodName of metricsServiceV2StubMethods) { const callPromise = this.metricsServiceV2Stub.then( - stub => + (stub) => (...args: Array<{}>) => { if (this._terminated) { return Promise.reject('The client has already been closed.'); @@ -575,8 +578,50 @@ export class MetricsServiceV2Client { this._gaxModule.routingHeader.fromParams({ metric_name: request.metricName ?? '', }); - this.initialize(); - return this.innerApiCalls.getLogMetric(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('getLogMetric request %j', request); + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IGetLogMetricRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getLogMetric response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .getLogMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IGetLogMetricRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getLogMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Creates a logs-based metric. @@ -664,8 +709,50 @@ export class MetricsServiceV2Client { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize(); - return this.innerApiCalls.createLogMetric(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('createLogMetric request %j', request); + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.ICreateLogMetricRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createLogMetric response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .createLogMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.ICreateLogMetricRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createLogMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Creates or updates a logs-based metric. @@ -754,8 +841,50 @@ export class MetricsServiceV2Client { this._gaxModule.routingHeader.fromParams({ metric_name: request.metricName ?? '', }); - this.initialize(); - return this.innerApiCalls.updateLogMetric(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('updateLogMetric request %j', request); + const wrappedCallback: + | Callback< + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IUpdateLogMetricRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('updateLogMetric response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .updateLogMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.logging.v2.ILogMetric, + protos.google.logging.v2.IUpdateLogMetricRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateLogMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** * Deletes a logs-based metric. @@ -838,8 +967,50 @@ export class MetricsServiceV2Client { this._gaxModule.routingHeader.fromParams({ metric_name: request.metricName ?? '', }); - this.initialize(); - return this.innerApiCalls.deleteLogMetric(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('deleteLogMetric request %j', request); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogMetricRequest | null | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteLogMetric response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls + .deleteLogMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.logging.v2.IDeleteLogMetricRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteLogMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); + } + throw error; + }); } /** @@ -935,12 +1106,38 @@ export class MetricsServiceV2Client { this._gaxModule.routingHeader.fromParams({ parent: request.parent ?? '', }); - this.initialize(); - return this.innerApiCalls.listLogMetrics(request, options, callback); + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.logging.v2.IListLogMetricsRequest, + protos.google.logging.v2.IListLogMetricsResponse | null | undefined, + protos.google.logging.v2.ILogMetric + > + | undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listLogMetrics values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listLogMetrics request %j', request); + return this.innerApiCalls + .listLogMetrics(request, options, wrappedCallback) + ?.then( + ([response, input, output]: [ + protos.google.logging.v2.ILogMetric[], + protos.google.logging.v2.IListLogMetricsRequest | null, + protos.google.logging.v2.IListLogMetricsResponse, + ]) => { + this._log.info('listLogMetrics values %j', response); + return [response, input, output]; + }, + ); } /** - * Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream object. + * Equivalent to `listLogMetrics`, but returns a NodeJS Stream object. * @param {Object} request * The request object that will be sent. * @param {string} request.parent @@ -981,7 +1178,10 @@ export class MetricsServiceV2Client { }); const defaultCallSettings = this._defaults['listLogMetrics']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('listLogMetrics stream %j', request); return this.descriptors.page.listLogMetrics.createStream( this.innerApiCalls.listLogMetrics as GaxCall, request, @@ -1034,7 +1234,10 @@ export class MetricsServiceV2Client { }); const defaultCallSettings = this._defaults['listLogMetrics']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch((err) => { + throw err; + }); + this._log.info('listLogMetrics iterate %j', request); return this.descriptors.page.listLogMetrics.asyncIterate( this.innerApiCalls['listLogMetrics'] as GaxCall, request as {}, @@ -2713,7 +2916,8 @@ export class MetricsServiceV2Client { */ close(): Promise { if (this.metricsServiceV2Stub && !this._terminated) { - return this.metricsServiceV2Stub.then(stub => { + return this.metricsServiceV2Stub.then((stub) => { + this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); }); diff --git a/handwritten/logging/system-test/install.ts b/handwritten/logging/system-test/install.ts index 22bbd83361c4..ccf167042d2e 100644 --- a/handwritten/logging/system-test/install.ts +++ b/handwritten/logging/system-test/install.ts @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -16,9 +16,9 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { it('TypeScript code', async function () { @@ -41,7 +41,7 @@ describe('📦 pack-n-play test', () => { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - ts: readFileSync( + cjs: readFileSync( './system-test/fixtures/sample/src/index.js', ).toString(), }, diff --git a/handwritten/logging/test/gapic_config_service_v2_v2.ts b/handwritten/logging/test/gapic_config_service_v2_v2.ts index 590ace19a7b1..74d54c9ce69d 100644 --- a/handwritten/logging/test/gapic_config_service_v2_v2.ts +++ b/handwritten/logging/test/gapic_config_service_v2_v2.ts @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,13 +19,13 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as configservicev2Module from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects @@ -45,7 +45,7 @@ function getTypeDefaultValue(typeName: string, fields: string[]) { function generateSampleMessage(instance: T) { const filledObject = ( instance.constructor as typeof protobuf.Message - ).toObject(instance as protobuf.Message, {defaults: true}); + ).toObject(instance as protobuf.Message, { defaults: true }); return (instance.constructor as typeof protobuf.Message).fromObject( filledObject, ) as T; @@ -149,9 +149,9 @@ function stubAsyncIterationCall( return Promise.reject(error); } if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); + return Promise.resolve({ done: true, value: undefined }); } - return Promise.resolve({done: false, value: responses![counter++]}); + return Promise.resolve({ done: false, value: responses![counter++] }); }, }; }, @@ -271,7 +271,7 @@ describe('v2.ConfigServiceV2Client', () => { it('has initialize method and supports deferred initialization', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); assert.strictEqual(client.configServiceV2Stub, undefined); @@ -279,33 +279,45 @@ describe('v2.ConfigServiceV2Client', () => { assert(client.configServiceV2Stub); }); - it('has close method for the initialized client', done => { + it('has close method for the initialized client', (done) => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); - assert(client.configServiceV2Stub); - client.close().then(() => { - done(); + client.initialize().catch((err) => { + throw err; }); + assert(client.configServiceV2Stub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; + }); }); - it('has close method for the non-initialized client', done => { + it('has close method for the non-initialized client', (done) => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); assert.strictEqual(client.configServiceV2Stub, undefined); - client.close().then(() => { - done(); - }); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; + }); }); it('has getProjectId method', async () => { const fakeProjectId = 'fake-project-id'; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); @@ -317,7 +329,7 @@ describe('v2.ConfigServiceV2Client', () => { it('has getProjectId method with callback', async () => { const fakeProjectId = 'fake-project-id'; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); client.auth.getProjectId = sinon @@ -340,10 +352,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('getBucket', () => { it('invokes getBucket without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetBucketRequest(), ); @@ -352,7 +364,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogBucket(), ); @@ -371,10 +383,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes getBucket without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetBucketRequest(), ); @@ -383,7 +395,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogBucket(), ); @@ -418,10 +430,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes getBucket with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetBucketRequest(), ); @@ -430,7 +442,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.getBucket = stubSimpleCall(undefined, expectedError); await assert.rejects(client.getBucket(request), expectedError); @@ -446,10 +458,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes getBucket with closed client', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetBucketRequest(), ); @@ -459,7 +471,9 @@ describe('v2.ConfigServiceV2Client', () => { ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.getBucket(request), expectedError); }); }); @@ -467,10 +481,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('createBucket', () => { it('invokes createBucket without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateBucketRequest(), ); @@ -479,7 +493,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogBucket(), ); @@ -498,10 +512,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes createBucket without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateBucketRequest(), ); @@ -510,7 +524,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogBucket(), ); @@ -545,10 +559,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes createBucket with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateBucketRequest(), ); @@ -557,7 +571,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.createBucket = stubSimpleCall( undefined, @@ -576,10 +590,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes createBucket with closed client', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateBucketRequest(), ); @@ -589,7 +603,9 @@ describe('v2.ConfigServiceV2Client', () => { ); request.parent = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.createBucket(request), expectedError); }); }); @@ -597,10 +613,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('updateBucket', () => { it('invokes updateBucket without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateBucketRequest(), ); @@ -609,7 +625,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogBucket(), ); @@ -628,10 +644,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes updateBucket without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateBucketRequest(), ); @@ -640,7 +656,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogBucket(), ); @@ -675,10 +691,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes updateBucket with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateBucketRequest(), ); @@ -687,7 +703,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.updateBucket = stubSimpleCall( undefined, @@ -706,10 +722,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes updateBucket with closed client', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateBucketRequest(), ); @@ -719,7 +735,9 @@ describe('v2.ConfigServiceV2Client', () => { ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.updateBucket(request), expectedError); }); }); @@ -727,10 +745,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('deleteBucket', () => { it('invokes deleteBucket without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteBucketRequest(), ); @@ -739,7 +757,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.protobuf.Empty(), ); @@ -758,10 +776,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes deleteBucket without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteBucketRequest(), ); @@ -770,7 +788,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.protobuf.Empty(), ); @@ -805,10 +823,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes deleteBucket with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteBucketRequest(), ); @@ -817,7 +835,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.deleteBucket = stubSimpleCall( undefined, @@ -836,10 +854,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes deleteBucket with closed client', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteBucketRequest(), ); @@ -849,7 +867,9 @@ describe('v2.ConfigServiceV2Client', () => { ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.deleteBucket(request), expectedError); }); }); @@ -857,10 +877,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('undeleteBucket', () => { it('invokes undeleteBucket without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UndeleteBucketRequest(), ); @@ -869,7 +889,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.protobuf.Empty(), ); @@ -888,10 +908,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes undeleteBucket without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UndeleteBucketRequest(), ); @@ -900,7 +920,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.protobuf.Empty(), ); @@ -935,10 +955,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes undeleteBucket with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UndeleteBucketRequest(), ); @@ -947,7 +967,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.undeleteBucket = stubSimpleCall( undefined, @@ -966,10 +986,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes undeleteBucket with closed client', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UndeleteBucketRequest(), ); @@ -979,7 +999,9 @@ describe('v2.ConfigServiceV2Client', () => { ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.undeleteBucket(request), expectedError); }); }); @@ -987,10 +1009,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('getView', () => { it('invokes getView without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetViewRequest(), ); @@ -999,7 +1021,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogView(), ); @@ -1018,10 +1040,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes getView without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetViewRequest(), ); @@ -1030,7 +1052,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogView(), ); @@ -1065,10 +1087,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes getView with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetViewRequest(), ); @@ -1077,7 +1099,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.getView = stubSimpleCall(undefined, expectedError); await assert.rejects(client.getView(request), expectedError); @@ -1093,10 +1115,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes getView with closed client', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetViewRequest(), ); @@ -1106,7 +1128,9 @@ describe('v2.ConfigServiceV2Client', () => { ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.getView(request), expectedError); }); }); @@ -1114,10 +1138,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('createView', () => { it('invokes createView without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateViewRequest(), ); @@ -1126,7 +1150,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogView(), ); @@ -1145,10 +1169,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes createView without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateViewRequest(), ); @@ -1157,7 +1181,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogView(), ); @@ -1192,10 +1216,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes createView with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateViewRequest(), ); @@ -1204,7 +1228,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.createView = stubSimpleCall( undefined, @@ -1223,10 +1247,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes createView with closed client', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateViewRequest(), ); @@ -1236,7 +1260,9 @@ describe('v2.ConfigServiceV2Client', () => { ); request.parent = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.createView(request), expectedError); }); }); @@ -1244,10 +1270,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('updateView', () => { it('invokes updateView without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateViewRequest(), ); @@ -1256,7 +1282,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogView(), ); @@ -1275,10 +1301,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes updateView without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateViewRequest(), ); @@ -1287,7 +1313,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogView(), ); @@ -1322,10 +1348,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes updateView with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateViewRequest(), ); @@ -1334,7 +1360,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.updateView = stubSimpleCall( undefined, @@ -1353,10 +1379,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes updateView with closed client', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateViewRequest(), ); @@ -1366,7 +1392,9 @@ describe('v2.ConfigServiceV2Client', () => { ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.updateView(request), expectedError); }); }); @@ -1374,10 +1402,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('deleteView', () => { it('invokes deleteView without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteViewRequest(), ); @@ -1386,7 +1414,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.protobuf.Empty(), ); @@ -1405,10 +1433,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes deleteView without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteViewRequest(), ); @@ -1417,7 +1445,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.protobuf.Empty(), ); @@ -1452,10 +1480,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes deleteView with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteViewRequest(), ); @@ -1464,7 +1492,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.deleteView = stubSimpleCall( undefined, @@ -1483,10 +1511,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes deleteView with closed client', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteViewRequest(), ); @@ -1496,7 +1524,9 @@ describe('v2.ConfigServiceV2Client', () => { ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.deleteView(request), expectedError); }); }); @@ -1504,10 +1534,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('getSink', () => { it('invokes getSink without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetSinkRequest(), ); @@ -1516,7 +1546,7 @@ describe('v2.ConfigServiceV2Client', () => { ['sinkName'], ); request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1}`; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogSink(), ); @@ -1535,10 +1565,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes getSink without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetSinkRequest(), ); @@ -1547,7 +1577,7 @@ describe('v2.ConfigServiceV2Client', () => { ['sinkName'], ); request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1}`; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogSink(), ); @@ -1582,10 +1612,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes getSink with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetSinkRequest(), ); @@ -1594,7 +1624,7 @@ describe('v2.ConfigServiceV2Client', () => { ['sinkName'], ); request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1}`; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.getSink = stubSimpleCall(undefined, expectedError); await assert.rejects(client.getSink(request), expectedError); @@ -1610,10 +1640,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes getSink with closed client', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetSinkRequest(), ); @@ -1623,7 +1653,9 @@ describe('v2.ConfigServiceV2Client', () => { ); request.sinkName = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.getSink(request), expectedError); }); }); @@ -1631,10 +1663,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('createSink', () => { it('invokes createSink without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateSinkRequest(), ); @@ -1643,7 +1675,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogSink(), ); @@ -1662,10 +1694,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes createSink without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateSinkRequest(), ); @@ -1674,7 +1706,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogSink(), ); @@ -1709,10 +1741,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes createSink with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateSinkRequest(), ); @@ -1721,7 +1753,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.createSink = stubSimpleCall( undefined, @@ -1740,10 +1772,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes createSink with closed client', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateSinkRequest(), ); @@ -1753,7 +1785,9 @@ describe('v2.ConfigServiceV2Client', () => { ); request.parent = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.createSink(request), expectedError); }); }); @@ -1761,10 +1795,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('updateSink', () => { it('invokes updateSink without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateSinkRequest(), ); @@ -1773,7 +1807,7 @@ describe('v2.ConfigServiceV2Client', () => { ['sinkName'], ); request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1}`; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogSink(), ); @@ -1792,10 +1826,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes updateSink without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateSinkRequest(), ); @@ -1804,7 +1838,7 @@ describe('v2.ConfigServiceV2Client', () => { ['sinkName'], ); request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1}`; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogSink(), ); @@ -1839,10 +1873,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes updateSink with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateSinkRequest(), ); @@ -1851,7 +1885,7 @@ describe('v2.ConfigServiceV2Client', () => { ['sinkName'], ); request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1}`; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.updateSink = stubSimpleCall( undefined, @@ -1870,10 +1904,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes updateSink with closed client', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateSinkRequest(), ); @@ -1883,7 +1917,9 @@ describe('v2.ConfigServiceV2Client', () => { ); request.sinkName = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.updateSink(request), expectedError); }); }); @@ -1891,10 +1927,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('deleteSink', () => { it('invokes deleteSink without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteSinkRequest(), ); @@ -1903,7 +1939,7 @@ describe('v2.ConfigServiceV2Client', () => { ['sinkName'], ); request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1}`; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.protobuf.Empty(), ); @@ -1922,10 +1958,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes deleteSink without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteSinkRequest(), ); @@ -1934,7 +1970,7 @@ describe('v2.ConfigServiceV2Client', () => { ['sinkName'], ); request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1}`; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.protobuf.Empty(), ); @@ -1969,10 +2005,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes deleteSink with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteSinkRequest(), ); @@ -1981,7 +2017,7 @@ describe('v2.ConfigServiceV2Client', () => { ['sinkName'], ); request.sinkName = defaultValue1; - const expectedHeaderRequestParams = `sink_name=${defaultValue1}`; + const expectedHeaderRequestParams = `sink_name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.deleteSink = stubSimpleCall( undefined, @@ -2000,10 +2036,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes deleteSink with closed client', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteSinkRequest(), ); @@ -2013,7 +2049,9 @@ describe('v2.ConfigServiceV2Client', () => { ); request.sinkName = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.deleteSink(request), expectedError); }); }); @@ -2021,10 +2059,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('getLink', () => { it('invokes getLink without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetLinkRequest(), ); @@ -2033,7 +2071,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.Link(), ); @@ -2052,10 +2090,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes getLink without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetLinkRequest(), ); @@ -2064,7 +2102,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.Link(), ); @@ -2099,10 +2137,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes getLink with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetLinkRequest(), ); @@ -2111,7 +2149,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.getLink = stubSimpleCall(undefined, expectedError); await assert.rejects(client.getLink(request), expectedError); @@ -2127,10 +2165,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes getLink with closed client', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetLinkRequest(), ); @@ -2140,7 +2178,9 @@ describe('v2.ConfigServiceV2Client', () => { ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.getLink(request), expectedError); }); }); @@ -2148,10 +2188,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('getExclusion', () => { it('invokes getExclusion without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetExclusionRequest(), ); @@ -2160,7 +2200,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogExclusion(), ); @@ -2179,10 +2219,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes getExclusion without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetExclusionRequest(), ); @@ -2191,7 +2231,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogExclusion(), ); @@ -2226,10 +2266,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes getExclusion with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetExclusionRequest(), ); @@ -2238,7 +2278,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.getExclusion = stubSimpleCall( undefined, @@ -2257,10 +2297,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes getExclusion with closed client', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetExclusionRequest(), ); @@ -2270,7 +2310,9 @@ describe('v2.ConfigServiceV2Client', () => { ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.getExclusion(request), expectedError); }); }); @@ -2278,10 +2320,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('createExclusion', () => { it('invokes createExclusion without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateExclusionRequest(), ); @@ -2290,7 +2332,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogExclusion(), ); @@ -2309,10 +2351,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes createExclusion without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateExclusionRequest(), ); @@ -2321,7 +2363,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogExclusion(), ); @@ -2356,10 +2398,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes createExclusion with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateExclusionRequest(), ); @@ -2368,7 +2410,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.createExclusion = stubSimpleCall( undefined, @@ -2387,10 +2429,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes createExclusion with closed client', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateExclusionRequest(), ); @@ -2400,7 +2442,9 @@ describe('v2.ConfigServiceV2Client', () => { ); request.parent = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.createExclusion(request), expectedError); }); }); @@ -2408,10 +2452,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('updateExclusion', () => { it('invokes updateExclusion without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateExclusionRequest(), ); @@ -2420,7 +2464,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogExclusion(), ); @@ -2439,10 +2483,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes updateExclusion without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateExclusionRequest(), ); @@ -2451,7 +2495,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogExclusion(), ); @@ -2486,10 +2530,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes updateExclusion with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateExclusionRequest(), ); @@ -2498,7 +2542,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.updateExclusion = stubSimpleCall( undefined, @@ -2517,10 +2561,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes updateExclusion with closed client', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateExclusionRequest(), ); @@ -2530,7 +2574,9 @@ describe('v2.ConfigServiceV2Client', () => { ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.updateExclusion(request), expectedError); }); }); @@ -2538,10 +2584,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('deleteExclusion', () => { it('invokes deleteExclusion without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteExclusionRequest(), ); @@ -2550,7 +2596,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.protobuf.Empty(), ); @@ -2569,10 +2615,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes deleteExclusion without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteExclusionRequest(), ); @@ -2581,7 +2627,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.protobuf.Empty(), ); @@ -2616,10 +2662,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes deleteExclusion with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteExclusionRequest(), ); @@ -2628,7 +2674,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.deleteExclusion = stubSimpleCall( undefined, @@ -2647,10 +2693,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes deleteExclusion with closed client', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteExclusionRequest(), ); @@ -2660,7 +2706,9 @@ describe('v2.ConfigServiceV2Client', () => { ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.deleteExclusion(request), expectedError); }); }); @@ -2668,10 +2716,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('getCmekSettings', () => { it('invokes getCmekSettings without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetCmekSettingsRequest(), ); @@ -2680,7 +2728,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.CmekSettings(), ); @@ -2699,10 +2747,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes getCmekSettings without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetCmekSettingsRequest(), ); @@ -2711,7 +2759,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.CmekSettings(), ); @@ -2746,10 +2794,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes getCmekSettings with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetCmekSettingsRequest(), ); @@ -2758,7 +2806,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.getCmekSettings = stubSimpleCall( undefined, @@ -2777,10 +2825,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes getCmekSettings with closed client', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetCmekSettingsRequest(), ); @@ -2790,7 +2838,9 @@ describe('v2.ConfigServiceV2Client', () => { ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.getCmekSettings(request), expectedError); }); }); @@ -2798,10 +2848,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('updateCmekSettings', () => { it('invokes updateCmekSettings without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateCmekSettingsRequest(), ); @@ -2810,7 +2860,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.CmekSettings(), ); @@ -2830,10 +2880,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes updateCmekSettings without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateCmekSettingsRequest(), ); @@ -2842,7 +2892,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.CmekSettings(), ); @@ -2877,10 +2927,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes updateCmekSettings with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateCmekSettingsRequest(), ); @@ -2889,7 +2939,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.updateCmekSettings = stubSimpleCall( undefined, @@ -2908,10 +2958,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes updateCmekSettings with closed client', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateCmekSettingsRequest(), ); @@ -2921,7 +2971,9 @@ describe('v2.ConfigServiceV2Client', () => { ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.updateCmekSettings(request), expectedError); }); }); @@ -2929,10 +2981,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('getSettings', () => { it('invokes getSettings without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetSettingsRequest(), ); @@ -2941,7 +2993,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.Settings(), ); @@ -2960,10 +3012,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes getSettings without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetSettingsRequest(), ); @@ -2972,7 +3024,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.Settings(), ); @@ -3007,10 +3059,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes getSettings with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetSettingsRequest(), ); @@ -3019,7 +3071,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.getSettings = stubSimpleCall( undefined, @@ -3038,10 +3090,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes getSettings with closed client', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetSettingsRequest(), ); @@ -3051,7 +3103,9 @@ describe('v2.ConfigServiceV2Client', () => { ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.getSettings(request), expectedError); }); }); @@ -3059,10 +3113,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('updateSettings', () => { it('invokes updateSettings without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateSettingsRequest(), ); @@ -3071,7 +3125,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.Settings(), ); @@ -3090,10 +3144,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes updateSettings without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateSettingsRequest(), ); @@ -3102,7 +3156,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.Settings(), ); @@ -3137,10 +3191,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes updateSettings with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateSettingsRequest(), ); @@ -3149,7 +3203,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.updateSettings = stubSimpleCall( undefined, @@ -3168,10 +3222,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes updateSettings with closed client', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateSettingsRequest(), ); @@ -3181,7 +3235,9 @@ describe('v2.ConfigServiceV2Client', () => { ); request.name = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.updateSettings(request), expectedError); }); }); @@ -3189,10 +3245,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('createBucketAsync', () => { it('invokes createBucketAsync without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateBucketRequest(), ); @@ -3201,7 +3257,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.longrunning.Operation(), ); @@ -3222,10 +3278,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes createBucketAsync without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateBucketRequest(), ); @@ -3234,7 +3290,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.longrunning.Operation(), ); @@ -3276,10 +3332,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes createBucketAsync with call error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateBucketRequest(), ); @@ -3288,7 +3344,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.createBucketAsync = stubLongRunningCall( undefined, @@ -3307,10 +3363,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes createBucketAsync with LRO error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateBucketRequest(), ); @@ -3319,7 +3375,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.createBucketAsync = stubLongRunningCall( undefined, @@ -3340,16 +3396,16 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes checkCreateBucketAsyncProgress without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + 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('')}; + 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.checkCreateBucketAsyncProgress( @@ -3362,10 +3418,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes checkCreateBucketAsyncProgress with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const expectedError = new Error('expected'); client.operationsClient.getOperation = stubSimpleCall( @@ -3383,10 +3439,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('updateBucketAsync', () => { it('invokes updateBucketAsync without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateBucketRequest(), ); @@ -3395,7 +3451,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.longrunning.Operation(), ); @@ -3416,10 +3472,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes updateBucketAsync without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateBucketRequest(), ); @@ -3428,7 +3484,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.longrunning.Operation(), ); @@ -3470,10 +3526,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes updateBucketAsync with call error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateBucketRequest(), ); @@ -3482,7 +3538,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.updateBucketAsync = stubLongRunningCall( undefined, @@ -3501,10 +3557,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes updateBucketAsync with LRO error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateBucketRequest(), ); @@ -3513,7 +3569,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.updateBucketAsync = stubLongRunningCall( undefined, @@ -3534,16 +3590,16 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes checkUpdateBucketAsyncProgress without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + 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('')}; + 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.checkUpdateBucketAsyncProgress( @@ -3556,10 +3612,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes checkUpdateBucketAsyncProgress with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const expectedError = new Error('expected'); client.operationsClient.getOperation = stubSimpleCall( @@ -3577,10 +3633,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('createLink', () => { it('invokes createLink without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateLinkRequest(), ); @@ -3589,7 +3645,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.longrunning.Operation(), ); @@ -3609,10 +3665,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes createLink without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateLinkRequest(), ); @@ -3621,7 +3677,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.longrunning.Operation(), ); @@ -3663,10 +3719,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes createLink with call error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateLinkRequest(), ); @@ -3675,7 +3731,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.createLink = stubLongRunningCall( undefined, @@ -3694,10 +3750,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes createLink with LRO error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateLinkRequest(), ); @@ -3706,7 +3762,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.createLink = stubLongRunningCall( undefined, @@ -3727,16 +3783,16 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes checkCreateLinkProgress without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + 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('')}; + 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.checkCreateLinkProgress( @@ -3749,10 +3805,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes checkCreateLinkProgress with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const expectedError = new Error('expected'); client.operationsClient.getOperation = stubSimpleCall( @@ -3767,10 +3823,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('deleteLink', () => { it('invokes deleteLink without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteLinkRequest(), ); @@ -3779,7 +3835,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.longrunning.Operation(), ); @@ -3799,10 +3855,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes deleteLink without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteLinkRequest(), ); @@ -3811,7 +3867,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.longrunning.Operation(), ); @@ -3853,10 +3909,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes deleteLink with call error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteLinkRequest(), ); @@ -3865,7 +3921,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.deleteLink = stubLongRunningCall( undefined, @@ -3884,10 +3940,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes deleteLink with LRO error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteLinkRequest(), ); @@ -3896,7 +3952,7 @@ describe('v2.ConfigServiceV2Client', () => { ['name'], ); request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.deleteLink = stubLongRunningCall( undefined, @@ -3917,16 +3973,16 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes checkDeleteLinkProgress without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + 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('')}; + 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.checkDeleteLinkProgress( @@ -3939,10 +3995,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes checkDeleteLinkProgress with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const expectedError = new Error('expected'); client.operationsClient.getOperation = stubSimpleCall( @@ -3957,10 +4013,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('copyLogEntries', () => { it('invokes copyLogEntries without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CopyLogEntriesRequest(), ); @@ -3976,10 +4032,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes copyLogEntries without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CopyLogEntriesRequest(), ); @@ -4016,10 +4072,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes copyLogEntries with call error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CopyLogEntriesRequest(), ); @@ -4033,10 +4089,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes copyLogEntries with LRO error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CopyLogEntriesRequest(), ); @@ -4052,16 +4108,16 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes checkCopyLogEntriesProgress without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + 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('')}; + 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.checkCopyLogEntriesProgress( @@ -4074,10 +4130,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes checkCopyLogEntriesProgress with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const expectedError = new Error('expected'); client.operationsClient.getOperation = stubSimpleCall( @@ -4095,10 +4151,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('listBuckets', () => { it('invokes listBuckets without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListBucketsRequest(), ); @@ -4107,7 +4163,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.LogBucket()), generateSampleMessage(new protos.google.logging.v2.LogBucket()), @@ -4128,10 +4184,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes listBuckets without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListBucketsRequest(), ); @@ -4140,7 +4196,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.LogBucket()), generateSampleMessage(new protos.google.logging.v2.LogBucket()), @@ -4177,10 +4233,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes listBuckets with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListBucketsRequest(), ); @@ -4189,7 +4245,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.listBuckets = stubSimpleCall( undefined, @@ -4208,10 +4264,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes listBucketsStream without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListBucketsRequest(), ); @@ -4220,7 +4276,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.LogBucket()), generateSampleMessage(new protos.google.logging.v2.LogBucket()), @@ -4259,10 +4315,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes listBucketsStream with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListBucketsRequest(), ); @@ -4271,7 +4327,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listBuckets.createStream = stubPageStreamingCall( undefined, @@ -4307,10 +4363,10 @@ describe('v2.ConfigServiceV2Client', () => { it('uses async iteration with listBuckets without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListBucketsRequest(), ); @@ -4319,7 +4375,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.LogBucket()), generateSampleMessage(new protos.google.logging.v2.LogBucket()), @@ -4350,10 +4406,10 @@ describe('v2.ConfigServiceV2Client', () => { it('uses async iteration with listBuckets with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListBucketsRequest(), ); @@ -4362,7 +4418,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listBuckets.asyncIterate = stubAsyncIterationCall( undefined, @@ -4394,10 +4450,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('listViews', () => { it('invokes listViews without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListViewsRequest(), ); @@ -4406,7 +4462,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.LogView()), generateSampleMessage(new protos.google.logging.v2.LogView()), @@ -4427,10 +4483,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes listViews without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListViewsRequest(), ); @@ -4439,7 +4495,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.LogView()), generateSampleMessage(new protos.google.logging.v2.LogView()), @@ -4476,10 +4532,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes listViews with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListViewsRequest(), ); @@ -4488,7 +4544,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.listViews = stubSimpleCall(undefined, expectedError); await assert.rejects(client.listViews(request), expectedError); @@ -4504,10 +4560,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes listViewsStream without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListViewsRequest(), ); @@ -4516,7 +4572,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.LogView()), generateSampleMessage(new protos.google.logging.v2.LogView()), @@ -4555,10 +4611,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes listViewsStream with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListViewsRequest(), ); @@ -4567,7 +4623,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listViews.createStream = stubPageStreamingCall( undefined, @@ -4603,10 +4659,10 @@ describe('v2.ConfigServiceV2Client', () => { it('uses async iteration with listViews without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListViewsRequest(), ); @@ -4615,7 +4671,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.LogView()), generateSampleMessage(new protos.google.logging.v2.LogView()), @@ -4645,10 +4701,10 @@ describe('v2.ConfigServiceV2Client', () => { it('uses async iteration with listViews with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListViewsRequest(), ); @@ -4657,7 +4713,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listViews.asyncIterate = stubAsyncIterationCall( undefined, @@ -4688,10 +4744,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('listSinks', () => { it('invokes listSinks without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListSinksRequest(), ); @@ -4700,7 +4756,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.LogSink()), generateSampleMessage(new protos.google.logging.v2.LogSink()), @@ -4721,10 +4777,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes listSinks without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListSinksRequest(), ); @@ -4733,7 +4789,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.LogSink()), generateSampleMessage(new protos.google.logging.v2.LogSink()), @@ -4770,10 +4826,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes listSinks with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListSinksRequest(), ); @@ -4782,7 +4838,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.listSinks = stubSimpleCall(undefined, expectedError); await assert.rejects(client.listSinks(request), expectedError); @@ -4798,10 +4854,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes listSinksStream without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListSinksRequest(), ); @@ -4810,7 +4866,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.LogSink()), generateSampleMessage(new protos.google.logging.v2.LogSink()), @@ -4849,10 +4905,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes listSinksStream with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListSinksRequest(), ); @@ -4861,7 +4917,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listSinks.createStream = stubPageStreamingCall( undefined, @@ -4897,10 +4953,10 @@ describe('v2.ConfigServiceV2Client', () => { it('uses async iteration with listSinks without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListSinksRequest(), ); @@ -4909,7 +4965,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.LogSink()), generateSampleMessage(new protos.google.logging.v2.LogSink()), @@ -4939,10 +4995,10 @@ describe('v2.ConfigServiceV2Client', () => { it('uses async iteration with listSinks with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListSinksRequest(), ); @@ -4951,7 +5007,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listSinks.asyncIterate = stubAsyncIterationCall( undefined, @@ -4982,10 +5038,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('listLinks', () => { it('invokes listLinks without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLinksRequest(), ); @@ -4994,7 +5050,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.Link()), generateSampleMessage(new protos.google.logging.v2.Link()), @@ -5015,10 +5071,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes listLinks without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLinksRequest(), ); @@ -5027,7 +5083,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.Link()), generateSampleMessage(new protos.google.logging.v2.Link()), @@ -5064,10 +5120,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes listLinks with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLinksRequest(), ); @@ -5076,7 +5132,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.listLinks = stubSimpleCall(undefined, expectedError); await assert.rejects(client.listLinks(request), expectedError); @@ -5092,10 +5148,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes listLinksStream without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLinksRequest(), ); @@ -5104,7 +5160,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.Link()), generateSampleMessage(new protos.google.logging.v2.Link()), @@ -5143,10 +5199,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes listLinksStream with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLinksRequest(), ); @@ -5155,7 +5211,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listLinks.createStream = stubPageStreamingCall( undefined, @@ -5191,10 +5247,10 @@ describe('v2.ConfigServiceV2Client', () => { it('uses async iteration with listLinks without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLinksRequest(), ); @@ -5203,7 +5259,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.Link()), generateSampleMessage(new protos.google.logging.v2.Link()), @@ -5233,10 +5289,10 @@ describe('v2.ConfigServiceV2Client', () => { it('uses async iteration with listLinks with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLinksRequest(), ); @@ -5245,7 +5301,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listLinks.asyncIterate = stubAsyncIterationCall( undefined, @@ -5276,10 +5332,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('listExclusions', () => { it('invokes listExclusions without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListExclusionsRequest(), ); @@ -5288,7 +5344,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.LogExclusion()), generateSampleMessage(new protos.google.logging.v2.LogExclusion()), @@ -5309,10 +5365,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes listExclusions without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListExclusionsRequest(), ); @@ -5321,7 +5377,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.LogExclusion()), generateSampleMessage(new protos.google.logging.v2.LogExclusion()), @@ -5358,10 +5414,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes listExclusions with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListExclusionsRequest(), ); @@ -5370,7 +5426,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.listExclusions = stubSimpleCall( undefined, @@ -5389,10 +5445,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes listExclusionsStream without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListExclusionsRequest(), ); @@ -5401,7 +5457,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.LogExclusion()), generateSampleMessage(new protos.google.logging.v2.LogExclusion()), @@ -5440,10 +5496,10 @@ describe('v2.ConfigServiceV2Client', () => { it('invokes listExclusionsStream with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListExclusionsRequest(), ); @@ -5452,7 +5508,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listExclusions.createStream = stubPageStreamingCall(undefined, expectedError); @@ -5486,10 +5542,10 @@ describe('v2.ConfigServiceV2Client', () => { it('uses async iteration with listExclusions without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListExclusionsRequest(), ); @@ -5498,7 +5554,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.LogExclusion()), generateSampleMessage(new protos.google.logging.v2.LogExclusion()), @@ -5529,10 +5585,10 @@ describe('v2.ConfigServiceV2Client', () => { it('uses async iteration with listExclusions with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListExclusionsRequest(), ); @@ -5541,7 +5597,7 @@ describe('v2.ConfigServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listExclusions.asyncIterate = stubAsyncIterationCall(undefined, expectedError); @@ -5570,10 +5626,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('getOperation', () => { it('invokes getOperation without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new operationsProtos.google.longrunning.GetOperationRequest(), ); @@ -5591,7 +5647,7 @@ describe('v2.ConfigServiceV2Client', () => { }); it('invokes getOperation without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); const request = generateSampleMessage( @@ -5604,20 +5660,24 @@ describe('v2.ConfigServiceV2Client', () => { .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); - } - }, - ); + 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); @@ -5625,7 +5685,7 @@ describe('v2.ConfigServiceV2Client', () => { }); it('invokes getOperation with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); const request = generateSampleMessage( @@ -5649,10 +5709,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('cancelOperation', () => { it('invokes cancelOperation without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new operationsProtos.google.longrunning.CancelOperationRequest(), ); @@ -5671,7 +5731,7 @@ describe('v2.ConfigServiceV2Client', () => { }); it('invokes cancelOperation without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); const request = generateSampleMessage( @@ -5684,20 +5744,24 @@ describe('v2.ConfigServiceV2Client', () => { .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); - } - }, - ); + 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); @@ -5705,7 +5769,7 @@ describe('v2.ConfigServiceV2Client', () => { }); it('invokes cancelOperation with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); const request = generateSampleMessage( @@ -5729,10 +5793,10 @@ describe('v2.ConfigServiceV2Client', () => { describe('deleteOperation', () => { it('invokes deleteOperation without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new operationsProtos.google.longrunning.DeleteOperationRequest(), ); @@ -5751,7 +5815,7 @@ describe('v2.ConfigServiceV2Client', () => { }); it('invokes deleteOperation without error using callback', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); const request = generateSampleMessage( @@ -5764,20 +5828,24 @@ describe('v2.ConfigServiceV2Client', () => { .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); - } - }, - ); + 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); @@ -5785,7 +5853,7 @@ describe('v2.ConfigServiceV2Client', () => { }); it('invokes deleteOperation with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); const request = generateSampleMessage( @@ -5809,7 +5877,7 @@ describe('v2.ConfigServiceV2Client', () => { describe('listOperationsAsync', () => { it('uses async iteration with listOperations without error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); const request = generateSampleMessage( @@ -5828,8 +5896,7 @@ describe('v2.ConfigServiceV2Client', () => { ]; client.operationsClient.descriptor.listOperations.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: operationsProtos.google.longrunning.ListOperationsResponse[] = - []; + const responses: operationsProtos.google.longrunning.IOperation[] = []; const iterable = client.operationsClient.listOperationsAsync(request); for await (const resource of iterable) { responses.push(resource!); @@ -5845,10 +5912,10 @@ describe('v2.ConfigServiceV2Client', () => { }); it('uses async iteration with listOperations with error', async () => { const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new operationsProtos.google.longrunning.ListOperationsRequest(), ); @@ -5857,8 +5924,7 @@ describe('v2.ConfigServiceV2Client', () => { stubAsyncIterationCall(undefined, expectedError); const iterable = client.operationsClient.listOperationsAsync(request); await assert.rejects(async () => { - const responses: operationsProtos.google.longrunning.ListOperationsResponse[] = - []; + const responses: operationsProtos.google.longrunning.IOperation[] = []; for await (const resource of iterable) { responses.push(resource!); } @@ -5874,16 +5940,16 @@ describe('v2.ConfigServiceV2Client', () => { }); describe('Path templates', () => { - describe('billingAccountCmekSettings', () => { + describe('billingAccountCmekSettings', async () => { const fakePath = '/rendered/path/billingAccountCmekSettings'; const expectedParameters = { billing_account: 'billingAccountValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountCmekSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -5923,17 +5989,17 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('billingAccountExclusion', () => { + describe('billingAccountExclusion', async () => { const fakePath = '/rendered/path/billingAccountExclusion'; const expectedParameters = { billing_account: 'billingAccountValue', exclusion: 'exclusionValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountExclusionPathTemplate.render = sinon .stub() .returns(fakePath); @@ -5986,7 +6052,7 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('billingAccountLocationBucket', () => { + describe('billingAccountLocationBucket', async () => { const fakePath = '/rendered/path/billingAccountLocationBucket'; const expectedParameters = { billing_account: 'billingAccountValue', @@ -5994,10 +6060,10 @@ describe('v2.ConfigServiceV2Client', () => { bucket: 'bucketValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountLocationBucketPathTemplate.render = sinon.stub().returns(fakePath); client.pathTemplates.billingAccountLocationBucketPathTemplate.match = @@ -6065,7 +6131,7 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('billingAccountLocationBucketLink', () => { + describe('billingAccountLocationBucketLink', async () => { const fakePath = '/rendered/path/billingAccountLocationBucketLink'; const expectedParameters = { billing_account: 'billingAccountValue', @@ -6074,10 +6140,10 @@ describe('v2.ConfigServiceV2Client', () => { link: 'linkValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountLocationBucketLinkPathTemplate.render = sinon.stub().returns(fakePath); client.pathTemplates.billingAccountLocationBucketLinkPathTemplate.match = @@ -6162,7 +6228,7 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('billingAccountLocationBucketView', () => { + describe('billingAccountLocationBucketView', async () => { const fakePath = '/rendered/path/billingAccountLocationBucketView'; const expectedParameters = { billing_account: 'billingAccountValue', @@ -6171,10 +6237,10 @@ describe('v2.ConfigServiceV2Client', () => { view: 'viewValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountLocationBucketViewPathTemplate.render = sinon.stub().returns(fakePath); client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match = @@ -6259,17 +6325,17 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('billingAccountLog', () => { + describe('billingAccountLog', async () => { const fakePath = '/rendered/path/billingAccountLog'; const expectedParameters = { billing_account: 'billingAccountValue', log: 'logValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountLogPathTemplate.render = sinon .stub() .returns(fakePath); @@ -6321,16 +6387,16 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('billingAccountSettings', () => { + describe('billingAccountSettings', async () => { const fakePath = '/rendered/path/billingAccountSettings'; const expectedParameters = { billing_account: 'billingAccountValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -6366,17 +6432,17 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('billingAccountSink', () => { + describe('billingAccountSink', async () => { const fakePath = '/rendered/path/billingAccountSink'; const expectedParameters = { billing_account: 'billingAccountValue', sink: 'sinkValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountSinkPathTemplate.render = sinon .stub() .returns(fakePath); @@ -6428,16 +6494,16 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('folderCmekSettings', () => { + describe('folderCmekSettings', async () => { const fakePath = '/rendered/path/folderCmekSettings'; const expectedParameters = { folder: 'folderValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderCmekSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -6472,17 +6538,17 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('folderExclusion', () => { + describe('folderExclusion', async () => { const fakePath = '/rendered/path/folderExclusion'; const expectedParameters = { folder: 'folderValue', exclusion: 'exclusionValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderExclusionPathTemplate.render = sinon .stub() .returns(fakePath); @@ -6524,7 +6590,7 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('folderLocationBucket', () => { + describe('folderLocationBucket', async () => { const fakePath = '/rendered/path/folderLocationBucket'; const expectedParameters = { folder: 'folderValue', @@ -6532,10 +6598,10 @@ describe('v2.ConfigServiceV2Client', () => { bucket: 'bucketValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderLocationBucketPathTemplate.render = sinon .stub() .returns(fakePath); @@ -6601,7 +6667,7 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('folderLocationBucketLink', () => { + describe('folderLocationBucketLink', async () => { const fakePath = '/rendered/path/folderLocationBucketLink'; const expectedParameters = { folder: 'folderValue', @@ -6610,10 +6676,10 @@ describe('v2.ConfigServiceV2Client', () => { link: 'linkValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderLocationBucketLinkPathTemplate.render = sinon .stub() .returns(fakePath); @@ -6696,7 +6762,7 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('folderLocationBucketView', () => { + describe('folderLocationBucketView', async () => { const fakePath = '/rendered/path/folderLocationBucketView'; const expectedParameters = { folder: 'folderValue', @@ -6705,10 +6771,10 @@ describe('v2.ConfigServiceV2Client', () => { view: 'viewValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderLocationBucketViewPathTemplate.render = sinon .stub() .returns(fakePath); @@ -6791,17 +6857,17 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('folderLog', () => { + describe('folderLog', async () => { const fakePath = '/rendered/path/folderLog'; const expectedParameters = { folder: 'folderValue', log: 'logValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderLogPathTemplate.render = sinon .stub() .returns(fakePath); @@ -6840,16 +6906,16 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('folderSettings', () => { + describe('folderSettings', async () => { const fakePath = '/rendered/path/folderSettings'; const expectedParameters = { folder: 'folderValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -6878,17 +6944,17 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('folderSink', () => { + describe('folderSink', async () => { const fakePath = '/rendered/path/folderSink'; const expectedParameters = { folder: 'folderValue', sink: 'sinkValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderSinkPathTemplate.render = sinon .stub() .returns(fakePath); @@ -6927,17 +6993,17 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('location', () => { + describe('location', async () => { const fakePath = '/rendered/path/location'; const expectedParameters = { project: 'projectValue', location: 'locationValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.locationPathTemplate.render = sinon .stub() .returns(fakePath); @@ -6976,17 +7042,17 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('logMetric', () => { + describe('logMetric', async () => { const fakePath = '/rendered/path/logMetric'; const expectedParameters = { project: 'projectValue', metric: 'metricValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.logMetricPathTemplate.render = sinon .stub() .returns(fakePath); @@ -7025,16 +7091,16 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('organizationCmekSettings', () => { + describe('organizationCmekSettings', async () => { const fakePath = '/rendered/path/organizationCmekSettings'; const expectedParameters = { organization: 'organizationValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationCmekSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -7070,17 +7136,17 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('organizationExclusion', () => { + describe('organizationExclusion', async () => { const fakePath = '/rendered/path/organizationExclusion'; const expectedParameters = { organization: 'organizationValue', exclusion: 'exclusionValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationExclusionPathTemplate.render = sinon .stub() .returns(fakePath); @@ -7133,7 +7199,7 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('organizationLocationBucket', () => { + describe('organizationLocationBucket', async () => { const fakePath = '/rendered/path/organizationLocationBucket'; const expectedParameters = { organization: 'organizationValue', @@ -7141,10 +7207,10 @@ describe('v2.ConfigServiceV2Client', () => { bucket: 'bucketValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationLocationBucketPathTemplate.render = sinon .stub() .returns(fakePath); @@ -7212,7 +7278,7 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('organizationLocationBucketLink', () => { + describe('organizationLocationBucketLink', async () => { const fakePath = '/rendered/path/organizationLocationBucketLink'; const expectedParameters = { organization: 'organizationValue', @@ -7221,10 +7287,10 @@ describe('v2.ConfigServiceV2Client', () => { link: 'linkValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationLocationBucketLinkPathTemplate.render = sinon.stub().returns(fakePath); client.pathTemplates.organizationLocationBucketLinkPathTemplate.match = @@ -7307,7 +7373,7 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('organizationLocationBucketView', () => { + describe('organizationLocationBucketView', async () => { const fakePath = '/rendered/path/organizationLocationBucketView'; const expectedParameters = { organization: 'organizationValue', @@ -7316,10 +7382,10 @@ describe('v2.ConfigServiceV2Client', () => { view: 'viewValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationLocationBucketViewPathTemplate.render = sinon.stub().returns(fakePath); client.pathTemplates.organizationLocationBucketViewPathTemplate.match = @@ -7402,17 +7468,17 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('organizationLog', () => { + describe('organizationLog', async () => { const fakePath = '/rendered/path/organizationLog'; const expectedParameters = { organization: 'organizationValue', log: 'logValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationLogPathTemplate.render = sinon .stub() .returns(fakePath); @@ -7455,16 +7521,16 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('organizationSettings', () => { + describe('organizationSettings', async () => { const fakePath = '/rendered/path/organizationSettings'; const expectedParameters = { organization: 'organizationValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -7500,17 +7566,17 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('organizationSink', () => { + describe('organizationSink', async () => { const fakePath = '/rendered/path/organizationSink'; const expectedParameters = { organization: 'organizationValue', sink: 'sinkValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationSinkPathTemplate.render = sinon .stub() .returns(fakePath); @@ -7556,16 +7622,16 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('project', () => { + describe('project', async () => { const fakePath = '/rendered/path/project'; const expectedParameters = { project: 'projectValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectPathTemplate.render = sinon .stub() .returns(fakePath); @@ -7594,16 +7660,16 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('projectCmekSettings', () => { + describe('projectCmekSettings', async () => { const fakePath = '/rendered/path/projectCmekSettings'; const expectedParameters = { project: 'projectValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectCmekSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -7638,17 +7704,17 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('projectExclusion', () => { + describe('projectExclusion', async () => { const fakePath = '/rendered/path/projectExclusion'; const expectedParameters = { project: 'projectValue', exclusion: 'exclusionValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectExclusionPathTemplate.render = sinon .stub() .returns(fakePath); @@ -7693,7 +7759,7 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('projectLocationBucket', () => { + describe('projectLocationBucket', async () => { const fakePath = '/rendered/path/projectLocationBucket'; const expectedParameters = { project: 'projectValue', @@ -7701,10 +7767,10 @@ describe('v2.ConfigServiceV2Client', () => { bucket: 'bucketValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectLocationBucketPathTemplate.render = sinon .stub() .returns(fakePath); @@ -7772,7 +7838,7 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('projectLocationBucketLink', () => { + describe('projectLocationBucketLink', async () => { const fakePath = '/rendered/path/projectLocationBucketLink'; const expectedParameters = { project: 'projectValue', @@ -7781,10 +7847,10 @@ describe('v2.ConfigServiceV2Client', () => { link: 'linkValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectLocationBucketLinkPathTemplate.render = sinon .stub() .returns(fakePath); @@ -7867,7 +7933,7 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('projectLocationBucketView', () => { + describe('projectLocationBucketView', async () => { const fakePath = '/rendered/path/projectLocationBucketView'; const expectedParameters = { project: 'projectValue', @@ -7876,10 +7942,10 @@ describe('v2.ConfigServiceV2Client', () => { view: 'viewValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectLocationBucketViewPathTemplate.render = sinon .stub() .returns(fakePath); @@ -7962,17 +8028,17 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('projectLog', () => { + describe('projectLog', async () => { const fakePath = '/rendered/path/projectLog'; const expectedParameters = { project: 'projectValue', log: 'logValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectLogPathTemplate.render = sinon .stub() .returns(fakePath); @@ -8011,16 +8077,16 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('projectSettings', () => { + describe('projectSettings', async () => { const fakePath = '/rendered/path/projectSettings'; const expectedParameters = { project: 'projectValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -8049,17 +8115,17 @@ describe('v2.ConfigServiceV2Client', () => { }); }); - describe('projectSink', () => { + describe('projectSink', async () => { const fakePath = '/rendered/path/projectSink'; const expectedParameters = { project: 'projectValue', sink: 'sinkValue', }; const client = new configservicev2Module.v2.ConfigServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectSinkPathTemplate.render = sinon .stub() .returns(fakePath); diff --git a/handwritten/logging/test/gapic_logging_service_v2_v2.ts b/handwritten/logging/test/gapic_logging_service_v2_v2.ts index fd9260826268..9005cf668f41 100644 --- a/handwritten/logging/test/gapic_logging_service_v2_v2.ts +++ b/handwritten/logging/test/gapic_logging_service_v2_v2.ts @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,13 +19,13 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as loggingservicev2Module from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects @@ -45,7 +45,7 @@ function getTypeDefaultValue(typeName: string, fields: string[]) { function generateSampleMessage(instance: T) { const filledObject = ( instance.constructor as typeof protobuf.Message - ).toObject(instance as protobuf.Message, {defaults: true}); + ).toObject(instance as protobuf.Message, { defaults: true }); return (instance.constructor as typeof protobuf.Message).fromObject( filledObject, ) as T; @@ -131,9 +131,9 @@ function stubAsyncIterationCall( return Promise.reject(error); } if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); + return Promise.resolve({ done: true, value: undefined }); } - return Promise.resolve({done: false, value: responses![counter++]}); + return Promise.resolve({ done: false, value: responses![counter++] }); }, }; }, @@ -253,7 +253,7 @@ describe('v2.LoggingServiceV2Client', () => { it('has initialize method and supports deferred initialization', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); assert.strictEqual(client.loggingServiceV2Stub, undefined); @@ -261,33 +261,45 @@ describe('v2.LoggingServiceV2Client', () => { assert(client.loggingServiceV2Stub); }); - it('has close method for the initialized client', done => { + it('has close method for the initialized client', (done) => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); - assert(client.loggingServiceV2Stub); - client.close().then(() => { - done(); + client.initialize().catch((err) => { + throw err; }); + assert(client.loggingServiceV2Stub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; + }); }); - it('has close method for the non-initialized client', done => { + it('has close method for the non-initialized client', (done) => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); assert.strictEqual(client.loggingServiceV2Stub, undefined); - client.close().then(() => { - done(); - }); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; + }); }); it('has getProjectId method', async () => { const fakeProjectId = 'fake-project-id'; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); @@ -299,7 +311,7 @@ describe('v2.LoggingServiceV2Client', () => { it('has getProjectId method with callback', async () => { const fakeProjectId = 'fake-project-id'; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); client.auth.getProjectId = sinon @@ -322,10 +334,10 @@ describe('v2.LoggingServiceV2Client', () => { describe('deleteLog', () => { it('invokes deleteLog without error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteLogRequest(), ); @@ -334,7 +346,7 @@ describe('v2.LoggingServiceV2Client', () => { ['logName'], ); request.logName = defaultValue1; - const expectedHeaderRequestParams = `log_name=${defaultValue1}`; + const expectedHeaderRequestParams = `log_name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.protobuf.Empty(), ); @@ -353,10 +365,10 @@ describe('v2.LoggingServiceV2Client', () => { it('invokes deleteLog without error using callback', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteLogRequest(), ); @@ -365,7 +377,7 @@ describe('v2.LoggingServiceV2Client', () => { ['logName'], ); request.logName = defaultValue1; - const expectedHeaderRequestParams = `log_name=${defaultValue1}`; + const expectedHeaderRequestParams = `log_name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.protobuf.Empty(), ); @@ -400,10 +412,10 @@ describe('v2.LoggingServiceV2Client', () => { it('invokes deleteLog with error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteLogRequest(), ); @@ -412,7 +424,7 @@ describe('v2.LoggingServiceV2Client', () => { ['logName'], ); request.logName = defaultValue1; - const expectedHeaderRequestParams = `log_name=${defaultValue1}`; + const expectedHeaderRequestParams = `log_name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.deleteLog = stubSimpleCall(undefined, expectedError); await assert.rejects(client.deleteLog(request), expectedError); @@ -428,10 +440,10 @@ describe('v2.LoggingServiceV2Client', () => { it('invokes deleteLog with closed client', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteLogRequest(), ); @@ -441,7 +453,9 @@ describe('v2.LoggingServiceV2Client', () => { ); request.logName = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.deleteLog(request), expectedError); }); }); @@ -449,10 +463,10 @@ describe('v2.LoggingServiceV2Client', () => { describe('writeLogEntries', () => { it('invokes writeLogEntries without error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.WriteLogEntriesRequest(), ); @@ -466,10 +480,10 @@ describe('v2.LoggingServiceV2Client', () => { it('invokes writeLogEntries without error using callback', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.WriteLogEntriesRequest(), ); @@ -499,10 +513,10 @@ describe('v2.LoggingServiceV2Client', () => { it('invokes writeLogEntries with error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.WriteLogEntriesRequest(), ); @@ -516,15 +530,17 @@ describe('v2.LoggingServiceV2Client', () => { it('invokes writeLogEntries with closed client', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.WriteLogEntriesRequest(), ); const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.writeLogEntries(request), expectedError); }); }); @@ -532,10 +548,10 @@ describe('v2.LoggingServiceV2Client', () => { describe('tailLogEntries', () => { it('invokes tailLogEntries without error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.TailLogEntriesRequest(), ); @@ -575,10 +591,10 @@ describe('v2.LoggingServiceV2Client', () => { it('invokes tailLogEntries with error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.TailLogEntriesRequest(), ); @@ -618,10 +634,10 @@ describe('v2.LoggingServiceV2Client', () => { describe('listLogEntries', () => { it('invokes listLogEntries without error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLogEntriesRequest(), ); @@ -637,10 +653,10 @@ describe('v2.LoggingServiceV2Client', () => { it('invokes listLogEntries without error using callback', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLogEntriesRequest(), ); @@ -672,10 +688,10 @@ describe('v2.LoggingServiceV2Client', () => { it('invokes listLogEntries with error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLogEntriesRequest(), ); @@ -689,10 +705,10 @@ describe('v2.LoggingServiceV2Client', () => { it('invokes listLogEntriesStream without error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLogEntriesRequest(), ); @@ -727,10 +743,10 @@ describe('v2.LoggingServiceV2Client', () => { it('invokes listLogEntriesStream with error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLogEntriesRequest(), ); @@ -760,10 +776,10 @@ describe('v2.LoggingServiceV2Client', () => { it('uses async iteration with listLogEntries without error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLogEntriesRequest(), ); @@ -790,10 +806,10 @@ describe('v2.LoggingServiceV2Client', () => { it('uses async iteration with listLogEntries with error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLogEntriesRequest(), ); @@ -819,10 +835,10 @@ describe('v2.LoggingServiceV2Client', () => { describe('listMonitoredResourceDescriptors', () => { it('invokes listMonitoredResourceDescriptors without error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest(), ); @@ -845,10 +861,10 @@ describe('v2.LoggingServiceV2Client', () => { it('invokes listMonitoredResourceDescriptors without error using callback', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest(), ); @@ -886,10 +902,10 @@ describe('v2.LoggingServiceV2Client', () => { it('invokes listMonitoredResourceDescriptors with error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest(), ); @@ -906,10 +922,10 @@ describe('v2.LoggingServiceV2Client', () => { it('invokes listMonitoredResourceDescriptorsStream without error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest(), ); @@ -959,10 +975,10 @@ describe('v2.LoggingServiceV2Client', () => { it('invokes listMonitoredResourceDescriptorsStream with error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest(), ); @@ -1001,10 +1017,10 @@ describe('v2.LoggingServiceV2Client', () => { it('uses async iteration with listMonitoredResourceDescriptors without error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest(), ); @@ -1038,10 +1054,10 @@ describe('v2.LoggingServiceV2Client', () => { it('uses async iteration with listMonitoredResourceDescriptors with error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListMonitoredResourceDescriptorsRequest(), ); @@ -1068,10 +1084,10 @@ describe('v2.LoggingServiceV2Client', () => { describe('listLogs', () => { it('invokes listLogs without error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLogsRequest(), ); @@ -1080,7 +1096,7 @@ describe('v2.LoggingServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [new String(), new String(), new String()]; client.innerApiCalls.listLogs = stubSimpleCall(expectedResponse); const [response] = await client.listLogs(request); @@ -1097,10 +1113,10 @@ describe('v2.LoggingServiceV2Client', () => { it('invokes listLogs without error using callback', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLogsRequest(), ); @@ -1109,7 +1125,7 @@ describe('v2.LoggingServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [new String(), new String(), new String()]; client.innerApiCalls.listLogs = stubSimpleCallWithCallback(expectedResponse); @@ -1139,10 +1155,10 @@ describe('v2.LoggingServiceV2Client', () => { it('invokes listLogs with error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLogsRequest(), ); @@ -1151,7 +1167,7 @@ describe('v2.LoggingServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.listLogs = stubSimpleCall(undefined, expectedError); await assert.rejects(client.listLogs(request), expectedError); @@ -1167,10 +1183,10 @@ describe('v2.LoggingServiceV2Client', () => { it('invokes listLogsStream without error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLogsRequest(), ); @@ -1179,7 +1195,7 @@ describe('v2.LoggingServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [new String(), new String(), new String()]; client.descriptors.page.listLogs.createStream = stubPageStreamingCall(expectedResponse); @@ -1214,10 +1230,10 @@ describe('v2.LoggingServiceV2Client', () => { it('invokes listLogsStream with error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLogsRequest(), ); @@ -1226,7 +1242,7 @@ describe('v2.LoggingServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listLogs.createStream = stubPageStreamingCall( undefined, @@ -1262,10 +1278,10 @@ describe('v2.LoggingServiceV2Client', () => { it('uses async iteration with listLogs without error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLogsRequest(), ); @@ -1274,7 +1290,7 @@ describe('v2.LoggingServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [new String(), new String(), new String()]; client.descriptors.page.listLogs.asyncIterate = stubAsyncIterationCall(expectedResponse); @@ -1300,10 +1316,10 @@ describe('v2.LoggingServiceV2Client', () => { it('uses async iteration with listLogs with error', async () => { const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLogsRequest(), ); @@ -1312,7 +1328,7 @@ describe('v2.LoggingServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listLogs.asyncIterate = stubAsyncIterationCall( undefined, @@ -1341,16 +1357,16 @@ describe('v2.LoggingServiceV2Client', () => { }); describe('Path templates', () => { - describe('billingAccountCmekSettings', () => { + describe('billingAccountCmekSettings', async () => { const fakePath = '/rendered/path/billingAccountCmekSettings'; const expectedParameters = { billing_account: 'billingAccountValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountCmekSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -1390,17 +1406,17 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('billingAccountExclusion', () => { + describe('billingAccountExclusion', async () => { const fakePath = '/rendered/path/billingAccountExclusion'; const expectedParameters = { billing_account: 'billingAccountValue', exclusion: 'exclusionValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountExclusionPathTemplate.render = sinon .stub() .returns(fakePath); @@ -1453,7 +1469,7 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('billingAccountLocationBucket', () => { + describe('billingAccountLocationBucket', async () => { const fakePath = '/rendered/path/billingAccountLocationBucket'; const expectedParameters = { billing_account: 'billingAccountValue', @@ -1461,10 +1477,10 @@ describe('v2.LoggingServiceV2Client', () => { bucket: 'bucketValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountLocationBucketPathTemplate.render = sinon.stub().returns(fakePath); client.pathTemplates.billingAccountLocationBucketPathTemplate.match = @@ -1532,7 +1548,7 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('billingAccountLocationBucketLink', () => { + describe('billingAccountLocationBucketLink', async () => { const fakePath = '/rendered/path/billingAccountLocationBucketLink'; const expectedParameters = { billing_account: 'billingAccountValue', @@ -1541,10 +1557,10 @@ describe('v2.LoggingServiceV2Client', () => { link: 'linkValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountLocationBucketLinkPathTemplate.render = sinon.stub().returns(fakePath); client.pathTemplates.billingAccountLocationBucketLinkPathTemplate.match = @@ -1629,7 +1645,7 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('billingAccountLocationBucketView', () => { + describe('billingAccountLocationBucketView', async () => { const fakePath = '/rendered/path/billingAccountLocationBucketView'; const expectedParameters = { billing_account: 'billingAccountValue', @@ -1638,10 +1654,10 @@ describe('v2.LoggingServiceV2Client', () => { view: 'viewValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountLocationBucketViewPathTemplate.render = sinon.stub().returns(fakePath); client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match = @@ -1726,17 +1742,17 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('billingAccountLog', () => { + describe('billingAccountLog', async () => { const fakePath = '/rendered/path/billingAccountLog'; const expectedParameters = { billing_account: 'billingAccountValue', log: 'logValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountLogPathTemplate.render = sinon .stub() .returns(fakePath); @@ -1788,16 +1804,16 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('billingAccountSettings', () => { + describe('billingAccountSettings', async () => { const fakePath = '/rendered/path/billingAccountSettings'; const expectedParameters = { billing_account: 'billingAccountValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -1833,17 +1849,17 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('billingAccountSink', () => { + describe('billingAccountSink', async () => { const fakePath = '/rendered/path/billingAccountSink'; const expectedParameters = { billing_account: 'billingAccountValue', sink: 'sinkValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountSinkPathTemplate.render = sinon .stub() .returns(fakePath); @@ -1895,16 +1911,16 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('folderCmekSettings', () => { + describe('folderCmekSettings', async () => { const fakePath = '/rendered/path/folderCmekSettings'; const expectedParameters = { folder: 'folderValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderCmekSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -1939,17 +1955,17 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('folderExclusion', () => { + describe('folderExclusion', async () => { const fakePath = '/rendered/path/folderExclusion'; const expectedParameters = { folder: 'folderValue', exclusion: 'exclusionValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderExclusionPathTemplate.render = sinon .stub() .returns(fakePath); @@ -1991,7 +2007,7 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('folderLocationBucket', () => { + describe('folderLocationBucket', async () => { const fakePath = '/rendered/path/folderLocationBucket'; const expectedParameters = { folder: 'folderValue', @@ -1999,10 +2015,10 @@ describe('v2.LoggingServiceV2Client', () => { bucket: 'bucketValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderLocationBucketPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2068,7 +2084,7 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('folderLocationBucketLink', () => { + describe('folderLocationBucketLink', async () => { const fakePath = '/rendered/path/folderLocationBucketLink'; const expectedParameters = { folder: 'folderValue', @@ -2077,10 +2093,10 @@ describe('v2.LoggingServiceV2Client', () => { link: 'linkValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderLocationBucketLinkPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2163,7 +2179,7 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('folderLocationBucketView', () => { + describe('folderLocationBucketView', async () => { const fakePath = '/rendered/path/folderLocationBucketView'; const expectedParameters = { folder: 'folderValue', @@ -2172,10 +2188,10 @@ describe('v2.LoggingServiceV2Client', () => { view: 'viewValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderLocationBucketViewPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2258,17 +2274,17 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('folderLog', () => { + describe('folderLog', async () => { const fakePath = '/rendered/path/folderLog'; const expectedParameters = { folder: 'folderValue', log: 'logValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderLogPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2307,16 +2323,16 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('folderSettings', () => { + describe('folderSettings', async () => { const fakePath = '/rendered/path/folderSettings'; const expectedParameters = { folder: 'folderValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2345,17 +2361,17 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('folderSink', () => { + describe('folderSink', async () => { const fakePath = '/rendered/path/folderSink'; const expectedParameters = { folder: 'folderValue', sink: 'sinkValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderSinkPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2394,17 +2410,17 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('logMetric', () => { + describe('logMetric', async () => { const fakePath = '/rendered/path/logMetric'; const expectedParameters = { project: 'projectValue', metric: 'metricValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.logMetricPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2443,16 +2459,16 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('organizationCmekSettings', () => { + describe('organizationCmekSettings', async () => { const fakePath = '/rendered/path/organizationCmekSettings'; const expectedParameters = { organization: 'organizationValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationCmekSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2488,17 +2504,17 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('organizationExclusion', () => { + describe('organizationExclusion', async () => { const fakePath = '/rendered/path/organizationExclusion'; const expectedParameters = { organization: 'organizationValue', exclusion: 'exclusionValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationExclusionPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2551,7 +2567,7 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('organizationLocationBucket', () => { + describe('organizationLocationBucket', async () => { const fakePath = '/rendered/path/organizationLocationBucket'; const expectedParameters = { organization: 'organizationValue', @@ -2559,10 +2575,10 @@ describe('v2.LoggingServiceV2Client', () => { bucket: 'bucketValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationLocationBucketPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2630,7 +2646,7 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('organizationLocationBucketLink', () => { + describe('organizationLocationBucketLink', async () => { const fakePath = '/rendered/path/organizationLocationBucketLink'; const expectedParameters = { organization: 'organizationValue', @@ -2639,10 +2655,10 @@ describe('v2.LoggingServiceV2Client', () => { link: 'linkValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationLocationBucketLinkPathTemplate.render = sinon.stub().returns(fakePath); client.pathTemplates.organizationLocationBucketLinkPathTemplate.match = @@ -2725,7 +2741,7 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('organizationLocationBucketView', () => { + describe('organizationLocationBucketView', async () => { const fakePath = '/rendered/path/organizationLocationBucketView'; const expectedParameters = { organization: 'organizationValue', @@ -2734,10 +2750,10 @@ describe('v2.LoggingServiceV2Client', () => { view: 'viewValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationLocationBucketViewPathTemplate.render = sinon.stub().returns(fakePath); client.pathTemplates.organizationLocationBucketViewPathTemplate.match = @@ -2820,17 +2836,17 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('organizationLog', () => { + describe('organizationLog', async () => { const fakePath = '/rendered/path/organizationLog'; const expectedParameters = { organization: 'organizationValue', log: 'logValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationLogPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2873,16 +2889,16 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('organizationSettings', () => { + describe('organizationSettings', async () => { const fakePath = '/rendered/path/organizationSettings'; const expectedParameters = { organization: 'organizationValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2918,17 +2934,17 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('organizationSink', () => { + describe('organizationSink', async () => { const fakePath = '/rendered/path/organizationSink'; const expectedParameters = { organization: 'organizationValue', sink: 'sinkValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationSinkPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2974,16 +2990,16 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('project', () => { + describe('project', async () => { const fakePath = '/rendered/path/project'; const expectedParameters = { project: 'projectValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectPathTemplate.render = sinon .stub() .returns(fakePath); @@ -3012,16 +3028,16 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('projectCmekSettings', () => { + describe('projectCmekSettings', async () => { const fakePath = '/rendered/path/projectCmekSettings'; const expectedParameters = { project: 'projectValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectCmekSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -3056,17 +3072,17 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('projectExclusion', () => { + describe('projectExclusion', async () => { const fakePath = '/rendered/path/projectExclusion'; const expectedParameters = { project: 'projectValue', exclusion: 'exclusionValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectExclusionPathTemplate.render = sinon .stub() .returns(fakePath); @@ -3111,7 +3127,7 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('projectLocationBucket', () => { + describe('projectLocationBucket', async () => { const fakePath = '/rendered/path/projectLocationBucket'; const expectedParameters = { project: 'projectValue', @@ -3119,10 +3135,10 @@ describe('v2.LoggingServiceV2Client', () => { bucket: 'bucketValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectLocationBucketPathTemplate.render = sinon .stub() .returns(fakePath); @@ -3190,7 +3206,7 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('projectLocationBucketLink', () => { + describe('projectLocationBucketLink', async () => { const fakePath = '/rendered/path/projectLocationBucketLink'; const expectedParameters = { project: 'projectValue', @@ -3199,10 +3215,10 @@ describe('v2.LoggingServiceV2Client', () => { link: 'linkValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectLocationBucketLinkPathTemplate.render = sinon .stub() .returns(fakePath); @@ -3285,7 +3301,7 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('projectLocationBucketView', () => { + describe('projectLocationBucketView', async () => { const fakePath = '/rendered/path/projectLocationBucketView'; const expectedParameters = { project: 'projectValue', @@ -3294,10 +3310,10 @@ describe('v2.LoggingServiceV2Client', () => { view: 'viewValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectLocationBucketViewPathTemplate.render = sinon .stub() .returns(fakePath); @@ -3380,17 +3396,17 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('projectLog', () => { + describe('projectLog', async () => { const fakePath = '/rendered/path/projectLog'; const expectedParameters = { project: 'projectValue', log: 'logValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectLogPathTemplate.render = sinon .stub() .returns(fakePath); @@ -3429,16 +3445,16 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('projectSettings', () => { + describe('projectSettings', async () => { const fakePath = '/rendered/path/projectSettings'; const expectedParameters = { project: 'projectValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -3467,17 +3483,17 @@ describe('v2.LoggingServiceV2Client', () => { }); }); - describe('projectSink', () => { + describe('projectSink', async () => { const fakePath = '/rendered/path/projectSink'; const expectedParameters = { project: 'projectValue', sink: 'sinkValue', }; const client = new loggingservicev2Module.v2.LoggingServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectSinkPathTemplate.render = sinon .stub() .returns(fakePath); diff --git a/handwritten/logging/test/gapic_metrics_service_v2_v2.ts b/handwritten/logging/test/gapic_metrics_service_v2_v2.ts index 90a774f07657..08d008059574 100644 --- a/handwritten/logging/test/gapic_metrics_service_v2_v2.ts +++ b/handwritten/logging/test/gapic_metrics_service_v2_v2.ts @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,13 +19,13 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as metricsservicev2Module from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects @@ -45,7 +45,7 @@ function getTypeDefaultValue(typeName: string, fields: string[]) { function generateSampleMessage(instance: T) { const filledObject = ( instance.constructor as typeof protobuf.Message - ).toObject(instance as protobuf.Message, {defaults: true}); + ).toObject(instance as protobuf.Message, { defaults: true }); return (instance.constructor as typeof protobuf.Message).fromObject( filledObject, ) as T; @@ -117,9 +117,9 @@ function stubAsyncIterationCall( return Promise.reject(error); } if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); + return Promise.resolve({ done: true, value: undefined }); } - return Promise.resolve({done: false, value: responses![counter++]}); + return Promise.resolve({ done: false, value: responses![counter++] }); }, }; }, @@ -239,7 +239,7 @@ describe('v2.MetricsServiceV2Client', () => { it('has initialize method and supports deferred initialization', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); assert.strictEqual(client.metricsServiceV2Stub, undefined); @@ -247,33 +247,45 @@ describe('v2.MetricsServiceV2Client', () => { assert(client.metricsServiceV2Stub); }); - it('has close method for the initialized client', done => { + it('has close method for the initialized client', (done) => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); - assert(client.metricsServiceV2Stub); - client.close().then(() => { - done(); + client.initialize().catch((err) => { + throw err; }); + assert(client.metricsServiceV2Stub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; + }); }); - it('has close method for the non-initialized client', done => { + it('has close method for the non-initialized client', (done) => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); assert.strictEqual(client.metricsServiceV2Stub, undefined); - client.close().then(() => { - done(); - }); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; + }); }); it('has getProjectId method', async () => { const fakeProjectId = 'fake-project-id'; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); @@ -285,7 +297,7 @@ describe('v2.MetricsServiceV2Client', () => { it('has getProjectId method with callback', async () => { const fakeProjectId = 'fake-project-id'; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); client.auth.getProjectId = sinon @@ -308,10 +320,10 @@ describe('v2.MetricsServiceV2Client', () => { describe('getLogMetric', () => { it('invokes getLogMetric without error', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetLogMetricRequest(), ); @@ -320,7 +332,7 @@ describe('v2.MetricsServiceV2Client', () => { ['metricName'], ); request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1}`; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogMetric(), ); @@ -339,10 +351,10 @@ describe('v2.MetricsServiceV2Client', () => { it('invokes getLogMetric without error using callback', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetLogMetricRequest(), ); @@ -351,7 +363,7 @@ describe('v2.MetricsServiceV2Client', () => { ['metricName'], ); request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1}`; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogMetric(), ); @@ -386,10 +398,10 @@ describe('v2.MetricsServiceV2Client', () => { it('invokes getLogMetric with error', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetLogMetricRequest(), ); @@ -398,7 +410,7 @@ describe('v2.MetricsServiceV2Client', () => { ['metricName'], ); request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1}`; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.getLogMetric = stubSimpleCall( undefined, @@ -417,10 +429,10 @@ describe('v2.MetricsServiceV2Client', () => { it('invokes getLogMetric with closed client', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.GetLogMetricRequest(), ); @@ -430,7 +442,9 @@ describe('v2.MetricsServiceV2Client', () => { ); request.metricName = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.getLogMetric(request), expectedError); }); }); @@ -438,10 +452,10 @@ describe('v2.MetricsServiceV2Client', () => { describe('createLogMetric', () => { it('invokes createLogMetric without error', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateLogMetricRequest(), ); @@ -450,7 +464,7 @@ describe('v2.MetricsServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogMetric(), ); @@ -469,10 +483,10 @@ describe('v2.MetricsServiceV2Client', () => { it('invokes createLogMetric without error using callback', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateLogMetricRequest(), ); @@ -481,7 +495,7 @@ describe('v2.MetricsServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogMetric(), ); @@ -516,10 +530,10 @@ describe('v2.MetricsServiceV2Client', () => { it('invokes createLogMetric with error', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateLogMetricRequest(), ); @@ -528,7 +542,7 @@ describe('v2.MetricsServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.createLogMetric = stubSimpleCall( undefined, @@ -547,10 +561,10 @@ describe('v2.MetricsServiceV2Client', () => { it('invokes createLogMetric with closed client', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.CreateLogMetricRequest(), ); @@ -560,7 +574,9 @@ describe('v2.MetricsServiceV2Client', () => { ); request.parent = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.createLogMetric(request), expectedError); }); }); @@ -568,10 +584,10 @@ describe('v2.MetricsServiceV2Client', () => { describe('updateLogMetric', () => { it('invokes updateLogMetric without error', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateLogMetricRequest(), ); @@ -580,7 +596,7 @@ describe('v2.MetricsServiceV2Client', () => { ['metricName'], ); request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1}`; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogMetric(), ); @@ -599,10 +615,10 @@ describe('v2.MetricsServiceV2Client', () => { it('invokes updateLogMetric without error using callback', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateLogMetricRequest(), ); @@ -611,7 +627,7 @@ describe('v2.MetricsServiceV2Client', () => { ['metricName'], ); request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1}`; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.logging.v2.LogMetric(), ); @@ -646,10 +662,10 @@ describe('v2.MetricsServiceV2Client', () => { it('invokes updateLogMetric with error', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateLogMetricRequest(), ); @@ -658,7 +674,7 @@ describe('v2.MetricsServiceV2Client', () => { ['metricName'], ); request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1}`; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.updateLogMetric = stubSimpleCall( undefined, @@ -677,10 +693,10 @@ describe('v2.MetricsServiceV2Client', () => { it('invokes updateLogMetric with closed client', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.UpdateLogMetricRequest(), ); @@ -690,7 +706,9 @@ describe('v2.MetricsServiceV2Client', () => { ); request.metricName = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.updateLogMetric(request), expectedError); }); }); @@ -698,10 +716,10 @@ describe('v2.MetricsServiceV2Client', () => { describe('deleteLogMetric', () => { it('invokes deleteLogMetric without error', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteLogMetricRequest(), ); @@ -710,7 +728,7 @@ describe('v2.MetricsServiceV2Client', () => { ['metricName'], ); request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1}`; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.protobuf.Empty(), ); @@ -729,10 +747,10 @@ describe('v2.MetricsServiceV2Client', () => { it('invokes deleteLogMetric without error using callback', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteLogMetricRequest(), ); @@ -741,7 +759,7 @@ describe('v2.MetricsServiceV2Client', () => { ['metricName'], ); request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1}`; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; const expectedResponse = generateSampleMessage( new protos.google.protobuf.Empty(), ); @@ -776,10 +794,10 @@ describe('v2.MetricsServiceV2Client', () => { it('invokes deleteLogMetric with error', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteLogMetricRequest(), ); @@ -788,7 +806,7 @@ describe('v2.MetricsServiceV2Client', () => { ['metricName'], ); request.metricName = defaultValue1; - const expectedHeaderRequestParams = `metric_name=${defaultValue1}`; + const expectedHeaderRequestParams = `metric_name=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.deleteLogMetric = stubSimpleCall( undefined, @@ -807,10 +825,10 @@ describe('v2.MetricsServiceV2Client', () => { it('invokes deleteLogMetric with closed client', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.DeleteLogMetricRequest(), ); @@ -820,7 +838,9 @@ describe('v2.MetricsServiceV2Client', () => { ); request.metricName = defaultValue1; const expectedError = new Error('The client has already been closed.'); - client.close(); + client.close().catch((err) => { + throw err; + }); await assert.rejects(client.deleteLogMetric(request), expectedError); }); }); @@ -828,10 +848,10 @@ describe('v2.MetricsServiceV2Client', () => { describe('listLogMetrics', () => { it('invokes listLogMetrics without error', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLogMetricsRequest(), ); @@ -840,7 +860,7 @@ describe('v2.MetricsServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.LogMetric()), generateSampleMessage(new protos.google.logging.v2.LogMetric()), @@ -861,10 +881,10 @@ describe('v2.MetricsServiceV2Client', () => { it('invokes listLogMetrics without error using callback', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLogMetricsRequest(), ); @@ -873,7 +893,7 @@ describe('v2.MetricsServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.LogMetric()), generateSampleMessage(new protos.google.logging.v2.LogMetric()), @@ -910,10 +930,10 @@ describe('v2.MetricsServiceV2Client', () => { it('invokes listLogMetrics with error', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLogMetricsRequest(), ); @@ -922,7 +942,7 @@ describe('v2.MetricsServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.innerApiCalls.listLogMetrics = stubSimpleCall( undefined, @@ -941,10 +961,10 @@ describe('v2.MetricsServiceV2Client', () => { it('invokes listLogMetricsStream without error', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLogMetricsRequest(), ); @@ -953,7 +973,7 @@ describe('v2.MetricsServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.LogMetric()), generateSampleMessage(new protos.google.logging.v2.LogMetric()), @@ -992,10 +1012,10 @@ describe('v2.MetricsServiceV2Client', () => { it('invokes listLogMetricsStream with error', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLogMetricsRequest(), ); @@ -1004,7 +1024,7 @@ describe('v2.MetricsServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listLogMetrics.createStream = stubPageStreamingCall(undefined, expectedError); @@ -1038,10 +1058,10 @@ describe('v2.MetricsServiceV2Client', () => { it('uses async iteration with listLogMetrics without error', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLogMetricsRequest(), ); @@ -1050,7 +1070,7 @@ describe('v2.MetricsServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedResponse = [ generateSampleMessage(new protos.google.logging.v2.LogMetric()), generateSampleMessage(new protos.google.logging.v2.LogMetric()), @@ -1081,10 +1101,10 @@ describe('v2.MetricsServiceV2Client', () => { it('uses async iteration with listLogMetrics with error', async () => { const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); const request = generateSampleMessage( new protos.google.logging.v2.ListLogMetricsRequest(), ); @@ -1093,7 +1113,7 @@ describe('v2.MetricsServiceV2Client', () => { ['parent'], ); request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1}`; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; const expectedError = new Error('expected'); client.descriptors.page.listLogMetrics.asyncIterate = stubAsyncIterationCall(undefined, expectedError); @@ -1121,16 +1141,16 @@ describe('v2.MetricsServiceV2Client', () => { }); describe('Path templates', () => { - describe('billingAccountCmekSettings', () => { + describe('billingAccountCmekSettings', async () => { const fakePath = '/rendered/path/billingAccountCmekSettings'; const expectedParameters = { billing_account: 'billingAccountValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountCmekSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -1170,17 +1190,17 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('billingAccountExclusion', () => { + describe('billingAccountExclusion', async () => { const fakePath = '/rendered/path/billingAccountExclusion'; const expectedParameters = { billing_account: 'billingAccountValue', exclusion: 'exclusionValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountExclusionPathTemplate.render = sinon .stub() .returns(fakePath); @@ -1233,7 +1253,7 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('billingAccountLocationBucket', () => { + describe('billingAccountLocationBucket', async () => { const fakePath = '/rendered/path/billingAccountLocationBucket'; const expectedParameters = { billing_account: 'billingAccountValue', @@ -1241,10 +1261,10 @@ describe('v2.MetricsServiceV2Client', () => { bucket: 'bucketValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountLocationBucketPathTemplate.render = sinon.stub().returns(fakePath); client.pathTemplates.billingAccountLocationBucketPathTemplate.match = @@ -1312,7 +1332,7 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('billingAccountLocationBucketLink', () => { + describe('billingAccountLocationBucketLink', async () => { const fakePath = '/rendered/path/billingAccountLocationBucketLink'; const expectedParameters = { billing_account: 'billingAccountValue', @@ -1321,10 +1341,10 @@ describe('v2.MetricsServiceV2Client', () => { link: 'linkValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountLocationBucketLinkPathTemplate.render = sinon.stub().returns(fakePath); client.pathTemplates.billingAccountLocationBucketLinkPathTemplate.match = @@ -1409,7 +1429,7 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('billingAccountLocationBucketView', () => { + describe('billingAccountLocationBucketView', async () => { const fakePath = '/rendered/path/billingAccountLocationBucketView'; const expectedParameters = { billing_account: 'billingAccountValue', @@ -1418,10 +1438,10 @@ describe('v2.MetricsServiceV2Client', () => { view: 'viewValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountLocationBucketViewPathTemplate.render = sinon.stub().returns(fakePath); client.pathTemplates.billingAccountLocationBucketViewPathTemplate.match = @@ -1506,17 +1526,17 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('billingAccountLog', () => { + describe('billingAccountLog', async () => { const fakePath = '/rendered/path/billingAccountLog'; const expectedParameters = { billing_account: 'billingAccountValue', log: 'logValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountLogPathTemplate.render = sinon .stub() .returns(fakePath); @@ -1568,16 +1588,16 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('billingAccountSettings', () => { + describe('billingAccountSettings', async () => { const fakePath = '/rendered/path/billingAccountSettings'; const expectedParameters = { billing_account: 'billingAccountValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -1613,17 +1633,17 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('billingAccountSink', () => { + describe('billingAccountSink', async () => { const fakePath = '/rendered/path/billingAccountSink'; const expectedParameters = { billing_account: 'billingAccountValue', sink: 'sinkValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.billingAccountSinkPathTemplate.render = sinon .stub() .returns(fakePath); @@ -1675,16 +1695,16 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('folderCmekSettings', () => { + describe('folderCmekSettings', async () => { const fakePath = '/rendered/path/folderCmekSettings'; const expectedParameters = { folder: 'folderValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderCmekSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -1719,17 +1739,17 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('folderExclusion', () => { + describe('folderExclusion', async () => { const fakePath = '/rendered/path/folderExclusion'; const expectedParameters = { folder: 'folderValue', exclusion: 'exclusionValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderExclusionPathTemplate.render = sinon .stub() .returns(fakePath); @@ -1771,7 +1791,7 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('folderLocationBucket', () => { + describe('folderLocationBucket', async () => { const fakePath = '/rendered/path/folderLocationBucket'; const expectedParameters = { folder: 'folderValue', @@ -1779,10 +1799,10 @@ describe('v2.MetricsServiceV2Client', () => { bucket: 'bucketValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderLocationBucketPathTemplate.render = sinon .stub() .returns(fakePath); @@ -1848,7 +1868,7 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('folderLocationBucketLink', () => { + describe('folderLocationBucketLink', async () => { const fakePath = '/rendered/path/folderLocationBucketLink'; const expectedParameters = { folder: 'folderValue', @@ -1857,10 +1877,10 @@ describe('v2.MetricsServiceV2Client', () => { link: 'linkValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderLocationBucketLinkPathTemplate.render = sinon .stub() .returns(fakePath); @@ -1943,7 +1963,7 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('folderLocationBucketView', () => { + describe('folderLocationBucketView', async () => { const fakePath = '/rendered/path/folderLocationBucketView'; const expectedParameters = { folder: 'folderValue', @@ -1952,10 +1972,10 @@ describe('v2.MetricsServiceV2Client', () => { view: 'viewValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderLocationBucketViewPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2038,17 +2058,17 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('folderLog', () => { + describe('folderLog', async () => { const fakePath = '/rendered/path/folderLog'; const expectedParameters = { folder: 'folderValue', log: 'logValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderLogPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2087,16 +2107,16 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('folderSettings', () => { + describe('folderSettings', async () => { const fakePath = '/rendered/path/folderSettings'; const expectedParameters = { folder: 'folderValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2125,17 +2145,17 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('folderSink', () => { + describe('folderSink', async () => { const fakePath = '/rendered/path/folderSink'; const expectedParameters = { folder: 'folderValue', sink: 'sinkValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.folderSinkPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2174,17 +2194,17 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('logMetric', () => { + describe('logMetric', async () => { const fakePath = '/rendered/path/logMetric'; const expectedParameters = { project: 'projectValue', metric: 'metricValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.logMetricPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2223,16 +2243,16 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('organizationCmekSettings', () => { + describe('organizationCmekSettings', async () => { const fakePath = '/rendered/path/organizationCmekSettings'; const expectedParameters = { organization: 'organizationValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationCmekSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2268,17 +2288,17 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('organizationExclusion', () => { + describe('organizationExclusion', async () => { const fakePath = '/rendered/path/organizationExclusion'; const expectedParameters = { organization: 'organizationValue', exclusion: 'exclusionValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationExclusionPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2331,7 +2351,7 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('organizationLocationBucket', () => { + describe('organizationLocationBucket', async () => { const fakePath = '/rendered/path/organizationLocationBucket'; const expectedParameters = { organization: 'organizationValue', @@ -2339,10 +2359,10 @@ describe('v2.MetricsServiceV2Client', () => { bucket: 'bucketValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationLocationBucketPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2410,7 +2430,7 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('organizationLocationBucketLink', () => { + describe('organizationLocationBucketLink', async () => { const fakePath = '/rendered/path/organizationLocationBucketLink'; const expectedParameters = { organization: 'organizationValue', @@ -2419,10 +2439,10 @@ describe('v2.MetricsServiceV2Client', () => { link: 'linkValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationLocationBucketLinkPathTemplate.render = sinon.stub().returns(fakePath); client.pathTemplates.organizationLocationBucketLinkPathTemplate.match = @@ -2505,7 +2525,7 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('organizationLocationBucketView', () => { + describe('organizationLocationBucketView', async () => { const fakePath = '/rendered/path/organizationLocationBucketView'; const expectedParameters = { organization: 'organizationValue', @@ -2514,10 +2534,10 @@ describe('v2.MetricsServiceV2Client', () => { view: 'viewValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationLocationBucketViewPathTemplate.render = sinon.stub().returns(fakePath); client.pathTemplates.organizationLocationBucketViewPathTemplate.match = @@ -2600,17 +2620,17 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('organizationLog', () => { + describe('organizationLog', async () => { const fakePath = '/rendered/path/organizationLog'; const expectedParameters = { organization: 'organizationValue', log: 'logValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationLogPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2653,16 +2673,16 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('organizationSettings', () => { + describe('organizationSettings', async () => { const fakePath = '/rendered/path/organizationSettings'; const expectedParameters = { organization: 'organizationValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2698,17 +2718,17 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('organizationSink', () => { + describe('organizationSink', async () => { const fakePath = '/rendered/path/organizationSink'; const expectedParameters = { organization: 'organizationValue', sink: 'sinkValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.organizationSinkPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2754,16 +2774,16 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('project', () => { + describe('project', async () => { const fakePath = '/rendered/path/project'; const expectedParameters = { project: 'projectValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2792,16 +2812,16 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('projectCmekSettings', () => { + describe('projectCmekSettings', async () => { const fakePath = '/rendered/path/projectCmekSettings'; const expectedParameters = { project: 'projectValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectCmekSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2836,17 +2856,17 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('projectExclusion', () => { + describe('projectExclusion', async () => { const fakePath = '/rendered/path/projectExclusion'; const expectedParameters = { project: 'projectValue', exclusion: 'exclusionValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectExclusionPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2891,7 +2911,7 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('projectLocationBucket', () => { + describe('projectLocationBucket', async () => { const fakePath = '/rendered/path/projectLocationBucket'; const expectedParameters = { project: 'projectValue', @@ -2899,10 +2919,10 @@ describe('v2.MetricsServiceV2Client', () => { bucket: 'bucketValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectLocationBucketPathTemplate.render = sinon .stub() .returns(fakePath); @@ -2970,7 +2990,7 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('projectLocationBucketLink', () => { + describe('projectLocationBucketLink', async () => { const fakePath = '/rendered/path/projectLocationBucketLink'; const expectedParameters = { project: 'projectValue', @@ -2979,10 +2999,10 @@ describe('v2.MetricsServiceV2Client', () => { link: 'linkValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectLocationBucketLinkPathTemplate.render = sinon .stub() .returns(fakePath); @@ -3065,7 +3085,7 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('projectLocationBucketView', () => { + describe('projectLocationBucketView', async () => { const fakePath = '/rendered/path/projectLocationBucketView'; const expectedParameters = { project: 'projectValue', @@ -3074,10 +3094,10 @@ describe('v2.MetricsServiceV2Client', () => { view: 'viewValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectLocationBucketViewPathTemplate.render = sinon .stub() .returns(fakePath); @@ -3160,17 +3180,17 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('projectLog', () => { + describe('projectLog', async () => { const fakePath = '/rendered/path/projectLog'; const expectedParameters = { project: 'projectValue', log: 'logValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectLogPathTemplate.render = sinon .stub() .returns(fakePath); @@ -3209,16 +3229,16 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('projectSettings', () => { + describe('projectSettings', async () => { const fakePath = '/rendered/path/projectSettings'; const expectedParameters = { project: 'projectValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectSettingsPathTemplate.render = sinon .stub() .returns(fakePath); @@ -3247,17 +3267,17 @@ describe('v2.MetricsServiceV2Client', () => { }); }); - describe('projectSink', () => { + describe('projectSink', async () => { const fakePath = '/rendered/path/projectSink'; const expectedParameters = { project: 'projectValue', sink: 'sinkValue', }; const client = new metricsservicev2Module.v2.MetricsServiceV2Client({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, + credentials: { client_email: 'bogus', private_key: 'bogus' }, projectId: 'bogus', }); - client.initialize(); + await client.initialize(); client.pathTemplates.projectSinkPathTemplate.render = sinon .stub() .returns(fakePath); diff --git a/handwritten/logging/tsconfig.json b/handwritten/logging/tsconfig.json index c78f1c884ef6..ca73e7bfc824 100644 --- a/handwritten/logging/tsconfig.json +++ b/handwritten/logging/tsconfig.json @@ -5,7 +5,7 @@ "outDir": "build", "resolveJsonModule": true, "lib": [ - "es2018", + "es2023", "dom" ] }, @@ -14,6 +14,9 @@ "src/**/*.ts", "test/*.ts", "test/**/*.ts", - "system-test/*.ts" + "system-test/*.ts", + "src/**/*.json", + "samples/**/*.json", + "protos/protos.json" ] } diff --git a/handwritten/logging/webpack.config.js b/handwritten/logging/webpack.config.js index 1cc3b570dfd0..a37e80e57376 100644 --- a/handwritten/logging/webpack.config.js +++ b/handwritten/logging/webpack.config.js @@ -36,27 +36,27 @@ module.exports = { { test: /\.tsx?$/, use: 'ts-loader', - exclude: /node_modules/, + exclude: /node_modules/ }, { test: /node_modules[\\/]@grpc[\\/]grpc-js/, - use: 'null-loader', + use: 'null-loader' }, { test: /node_modules[\\/]grpc/, - use: 'null-loader', + use: 'null-loader' }, { test: /node_modules[\\/]retry-request/, - use: 'null-loader', + use: 'null-loader' }, { test: /node_modules[\\/]https?-proxy-agent/, - use: 'null-loader', + use: 'null-loader' }, { test: /node_modules[\\/]gtoken/, - use: 'null-loader', + use: 'null-loader' }, ], }, diff --git a/packages/google-ads-datamanager/.eslintignore b/packages/google-ads-datamanager/.eslintignore new file mode 100644 index 000000000000..cfc348ec4d11 --- /dev/null +++ b/packages/google-ads-datamanager/.eslintignore @@ -0,0 +1,7 @@ +**/node_modules +**/.coverage +build/ +docs/ +protos/ +system-test/ +samples/generated/ diff --git a/packages/google-ads-datamanager/.eslintrc.json b/packages/google-ads-datamanager/.eslintrc.json new file mode 100644 index 000000000000..3e8d97ccb390 --- /dev/null +++ b/packages/google-ads-datamanager/.eslintrc.json @@ -0,0 +1,4 @@ +{ + "extends": "./node_modules/gts", + "root": true +} diff --git a/packages/google-ads-datamanager/README.md b/packages/google-ads-datamanager/README.md index a1888aea2a6e..3dad6e62c326 100644 --- a/packages/google-ads-datamanager/README.md +++ b/packages/google-ads-datamanager/README.md @@ -113,7 +113,7 @@ More Information: [Google Cloud Platform Launch Stages][launch_stages] ## Contributing -Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/CONTRIBUTING.md). +Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/google-cloud-node/blob/main/CONTRIBUTING.md). Please note that this `README.md` and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`) @@ -123,7 +123,7 @@ are generated from a central template. Apache Version 2.0 -See [LICENSE](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ads-datamanager/LICENSE) +See [LICENSE](https://github.com/googleapis/google-cloud-node/blob/main/LICENSE) [shell_img]: https://gstatic.com/cloudssh/images/open-btn.png [projects]: https://console.cloud.google.com/project diff --git a/packages/google-ads-datamanager/protos/protos.d.ts b/packages/google-ads-datamanager/protos/protos.d.ts index c16044ba1522..27498fe81f29 100644 --- a/packages/google-ads-datamanager/protos/protos.d.ts +++ b/packages/google-ads-datamanager/protos/protos.d.ts @@ -12327,6 +12327,9 @@ export namespace google { /** CommonLanguageSettings destinations */ destinations?: (google.api.ClientLibraryDestination[]|null); + + /** CommonLanguageSettings selectiveGapicGeneration */ + selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); } /** Represents a CommonLanguageSettings. */ @@ -12344,6 +12347,9 @@ export namespace google { /** CommonLanguageSettings destinations. */ public destinations: google.api.ClientLibraryDestination[]; + /** CommonLanguageSettings selectiveGapicGeneration. */ + public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + /** * Creates a new CommonLanguageSettings instance using the specified properties. * @param [properties] Properties to set @@ -13044,6 +13050,9 @@ export namespace google { /** PythonSettings common */ common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures */ + experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); } /** Represents a PythonSettings. */ @@ -13058,6 +13067,9 @@ export namespace google { /** PythonSettings common. */ public common?: (google.api.ICommonLanguageSettings|null); + /** PythonSettings experimentalFeatures. */ + public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + /** * Creates a new PythonSettings instance using the specified properties. * @param [properties] Properties to set @@ -13136,6 +13148,118 @@ 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); + + /** ExperimentalFeatures unversionedPackageDisabled */ + unversionedPackageDisabled?: (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; + + /** ExperimentalFeatures unversionedPackageDisabled. */ + public unversionedPackageDisabled: boolean; + + /** + * Creates a new ExperimentalFeatures instance using the specified properties. + * @param [properties] Properties to set + * @returns ExperimentalFeatures instance + */ + public static create(properties?: google.api.PythonSettings.IExperimentalFeatures): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Encodes the specified ExperimentalFeatures message. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @param message ExperimentalFeatures message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.PythonSettings.IExperimentalFeatures, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExperimentalFeatures message, length delimited. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @param message ExperimentalFeatures message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.PythonSettings.IExperimentalFeatures, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Verifies an ExperimentalFeatures message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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 { @@ -13462,6 +13586,9 @@ export namespace google { /** GoSettings common */ common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); } /** Represents a GoSettings. */ @@ -13476,6 +13603,9 @@ export namespace google { /** GoSettings common. */ public common?: (google.api.ICommonLanguageSettings|null); + /** GoSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + /** * Creates a new GoSettings instance using the specified properties. * @param [properties] Properties to set @@ -13800,6 +13930,109 @@ export namespace google { PACKAGE_MANAGER = 20 } + /** 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 new SelectiveGapicGeneration instance using the specified properties. + * @param [properties] Properties to set + * @returns SelectiveGapicGeneration instance + */ + public static create(properties?: google.api.ISelectiveGapicGeneration): google.api.SelectiveGapicGeneration; + + /** + * Encodes the specified SelectiveGapicGeneration message. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @param message SelectiveGapicGeneration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.ISelectiveGapicGeneration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SelectiveGapicGeneration message, length delimited. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @param message SelectiveGapicGeneration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.ISelectiveGapicGeneration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.SelectiveGapicGeneration; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.SelectiveGapicGeneration; + + /** + * Verifies a SelectiveGapicGeneration message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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. */ enum LaunchStage { LAUNCH_STAGE_UNSPECIFIED = 0, @@ -13916,6 +14149,7 @@ export namespace google { /** Edition enum. */ enum Edition { EDITION_UNKNOWN = 0, + EDITION_LEGACY = 900, EDITION_PROTO2 = 998, EDITION_PROTO3 = 999, EDITION_2023 = 1000, @@ -13946,6 +14180,9 @@ export namespace google { /** FileDescriptorProto weakDependency */ weakDependency?: (number[]|null); + /** FileDescriptorProto optionDependency */ + optionDependency?: (string[]|null); + /** FileDescriptorProto messageType */ messageType?: (google.protobuf.IDescriptorProto[]|null); @@ -13995,6 +14232,9 @@ export namespace google { /** FileDescriptorProto weakDependency. */ public weakDependency: number[]; + /** FileDescriptorProto optionDependency. */ + public optionDependency: string[]; + /** FileDescriptorProto messageType. */ public messageType: google.protobuf.IDescriptorProto[]; @@ -14129,6 +14369,9 @@ export namespace google { /** DescriptorProto reservedName */ reservedName?: (string[]|null); + + /** DescriptorProto visibility */ + visibility?: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility|null); } /** Represents a DescriptorProto. */ @@ -14170,6 +14413,9 @@ export namespace google { /** DescriptorProto reservedName. */ public reservedName: string[]; + /** DescriptorProto visibility. */ + public visibility: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility); + /** * Creates a new DescriptorProto instance using the specified properties. * @param [properties] Properties to set @@ -15017,6 +15263,9 @@ export namespace google { /** EnumDescriptorProto reservedName */ reservedName?: (string[]|null); + + /** EnumDescriptorProto visibility */ + visibility?: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility|null); } /** Represents an EnumDescriptorProto. */ @@ -15043,6 +15292,9 @@ export namespace google { /** EnumDescriptorProto reservedName. */ public reservedName: string[]; + /** EnumDescriptorProto visibility. */ + public visibility: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility); + /** * Creates a new EnumDescriptorProto instance using the specified properties. * @param [properties] Properties to set @@ -15977,6 +16229,9 @@ 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); @@ -16032,6 +16287,9 @@ 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[]; @@ -16252,6 +16510,121 @@ export namespace google { */ public static getTypeUrl(typeUrlPrefix?: string): string; } + + /** Properties of a FeatureSupport. */ + interface IFeatureSupport { + + /** FeatureSupport editionIntroduced */ + editionIntroduced?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + + /** FeatureSupport editionDeprecated */ + editionDeprecated?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + + /** FeatureSupport deprecationWarning */ + deprecationWarning?: (string|null); + + /** FeatureSupport editionRemoved */ + editionRemoved?: (google.protobuf.Edition|keyof typeof 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|keyof typeof google.protobuf.Edition); + + /** FeatureSupport editionDeprecated. */ + public editionDeprecated: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** FeatureSupport deprecationWarning. */ + public deprecationWarning: string; + + /** FeatureSupport editionRemoved. */ + public editionRemoved: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** + * Creates a new FeatureSupport instance using the specified properties. + * @param [properties] Properties to set + * @returns FeatureSupport instance + */ + public static create(properties?: google.protobuf.FieldOptions.IFeatureSupport): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Encodes the specified FeatureSupport message. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @param message FeatureSupport message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.FieldOptions.IFeatureSupport, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FeatureSupport message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @param message FeatureSupport message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.FieldOptions.IFeatureSupport, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Verifies a FeatureSupport message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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. */ @@ -16490,6 +16863,9 @@ export namespace google { /** EnumValueOptions debugRedact */ debugRedact?: (boolean|null); + /** EnumValueOptions featureSupport */ + featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); + /** EnumValueOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } @@ -16512,6 +16888,9 @@ export namespace google { /** EnumValueOptions debugRedact. */ public debugRedact: boolean; + /** EnumValueOptions featureSupport. */ + public featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); + /** EnumValueOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -17101,6 +17480,12 @@ export namespace google { /** FeatureSet jsonFormat */ jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|keyof typeof google.protobuf.FeatureSet.JsonFormat|null); + + /** FeatureSet enforceNamingStyle */ + enforceNamingStyle?: (google.protobuf.FeatureSet.EnforceNamingStyle|keyof typeof google.protobuf.FeatureSet.EnforceNamingStyle|null); + + /** FeatureSet defaultSymbolVisibility */ + defaultSymbolVisibility?: (google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|keyof typeof google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|null); } /** Represents a FeatureSet. */ @@ -17130,6 +17515,12 @@ export namespace google { /** FeatureSet jsonFormat. */ public jsonFormat: (google.protobuf.FeatureSet.JsonFormat|keyof typeof google.protobuf.FeatureSet.JsonFormat); + /** FeatureSet enforceNamingStyle. */ + public enforceNamingStyle: (google.protobuf.FeatureSet.EnforceNamingStyle|keyof typeof google.protobuf.FeatureSet.EnforceNamingStyle); + + /** FeatureSet defaultSymbolVisibility. */ + public defaultSymbolVisibility: (google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|keyof typeof google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility); + /** * Creates a new FeatureSet instance using the specified properties. * @param [properties] Properties to set @@ -17252,6 +17643,116 @@ export namespace google { ALLOW = 1, LEGACY_BEST_EFFORT = 2 } + + /** EnforceNamingStyle enum. */ + enum EnforceNamingStyle { + ENFORCE_NAMING_STYLE_UNKNOWN = 0, + STYLE2024 = 1, + STYLE_LEGACY = 2 + } + + /** Properties of a VisibilityFeature. */ + interface IVisibilityFeature { + } + + /** Represents a VisibilityFeature. */ + class VisibilityFeature implements IVisibilityFeature { + + /** + * Constructs a new VisibilityFeature. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FeatureSet.IVisibilityFeature); + + /** + * Creates a new VisibilityFeature instance using the specified properties. + * @param [properties] Properties to set + * @returns VisibilityFeature instance + */ + public static create(properties?: google.protobuf.FeatureSet.IVisibilityFeature): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Encodes the specified VisibilityFeature message. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @param message VisibilityFeature message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.FeatureSet.IVisibilityFeature, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified VisibilityFeature message, length delimited. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @param message VisibilityFeature message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.FeatureSet.IVisibilityFeature, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Verifies a VisibilityFeature message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a VisibilityFeature message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns VisibilityFeature + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Creates a plain object from a VisibilityFeature message. Also converts values to other types if specified. + * @param message VisibilityFeature + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet.VisibilityFeature, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this VisibilityFeature to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for VisibilityFeature + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace VisibilityFeature { + + /** DefaultSymbolVisibility enum. */ + enum DefaultSymbolVisibility { + DEFAULT_SYMBOL_VISIBILITY_UNKNOWN = 0, + EXPORT_ALL = 1, + EXPORT_TOP_LEVEL = 2, + LOCAL_ALL = 3, + STRICT = 4 + } + } } /** Properties of a FeatureSetDefaults. */ @@ -17371,8 +17872,11 @@ export namespace google { /** FeatureSetEditionDefault edition */ edition?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); - /** FeatureSetEditionDefault features */ - features?: (google.protobuf.IFeatureSet|null); + /** FeatureSetEditionDefault overridableFeatures */ + overridableFeatures?: (google.protobuf.IFeatureSet|null); + + /** FeatureSetEditionDefault fixedFeatures */ + fixedFeatures?: (google.protobuf.IFeatureSet|null); } /** Represents a FeatureSetEditionDefault. */ @@ -17387,8 +17891,11 @@ export namespace google { /** FeatureSetEditionDefault edition. */ public edition: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); - /** FeatureSetEditionDefault features. */ - public features?: (google.protobuf.IFeatureSet|null); + /** FeatureSetEditionDefault overridableFeatures. */ + public overridableFeatures?: (google.protobuf.IFeatureSet|null); + + /** FeatureSetEditionDefault fixedFeatures. */ + public fixedFeatures?: (google.protobuf.IFeatureSet|null); /** * Creates a new FeatureSetEditionDefault instance using the specified properties. @@ -17921,6 +18428,13 @@ export namespace google { } } + /** SymbolVisibility enum. */ + enum SymbolVisibility { + VISIBILITY_UNSET = 0, + VISIBILITY_LOCAL = 1, + VISIBILITY_EXPORT = 2 + } + /** Properties of a Timestamp. */ interface ITimestamp { diff --git a/packages/google-ads-datamanager/protos/protos.js b/packages/google-ads-datamanager/protos/protos.js index ef327392a2e7..8f273bdf612d 100644 --- a/packages/google-ads-datamanager/protos/protos.js +++ b/packages/google-ads-datamanager/protos/protos.js @@ -31944,6 +31944,7 @@ * @interface ICommonLanguageSettings * @property {string|null} [referenceDocsUri] CommonLanguageSettings referenceDocsUri * @property {Array.|null} [destinations] CommonLanguageSettings destinations + * @property {google.api.ISelectiveGapicGeneration|null} [selectiveGapicGeneration] CommonLanguageSettings selectiveGapicGeneration */ /** @@ -31978,6 +31979,14 @@ */ 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 new CommonLanguageSettings instance using the specified properties. * @function create @@ -32010,6 +32019,8 @@ writer.int32(message.destinations[i]); writer.ldelim(); } + if (message.selectiveGapicGeneration != null && Object.hasOwnProperty.call(message, "selectiveGapicGeneration")) + $root.google.api.SelectiveGapicGeneration.encode(message.selectiveGapicGeneration, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); return writer; }; @@ -32061,6 +32072,10 @@ message.destinations.push(reader.int32()); break; } + case 3: { + message.selectiveGapicGeneration = $root.google.api.SelectiveGapicGeneration.decode(reader, reader.uint32()); + break; + } default: reader.skipType(tag & 7); break; @@ -32112,6 +32127,11 @@ break; } } + if (message.selectiveGapicGeneration != null && message.hasOwnProperty("selectiveGapicGeneration")) { + var error = $root.google.api.SelectiveGapicGeneration.verify(message.selectiveGapicGeneration); + if (error) + return "selectiveGapicGeneration." + error; + } return null; }; @@ -32154,6 +32174,11 @@ 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; }; @@ -32172,8 +32197,10 @@ 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) { @@ -32181,6 +32208,8 @@ 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; }; @@ -34003,6 +34032,7 @@ * @memberof google.api * @interface IPythonSettings * @property {google.api.ICommonLanguageSettings|null} [common] PythonSettings common + * @property {google.api.PythonSettings.IExperimentalFeatures|null} [experimentalFeatures] PythonSettings experimentalFeatures */ /** @@ -34028,6 +34058,14 @@ */ 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 new PythonSettings instance using the specified properties. * @function create @@ -34054,6 +34092,8 @@ writer = $Writer.create(); if (message.common != null && Object.hasOwnProperty.call(message, "common")) $root.google.api.CommonLanguageSettings.encode(message.common, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.experimentalFeatures != null && Object.hasOwnProperty.call(message, "experimentalFeatures")) + $root.google.api.PythonSettings.ExperimentalFeatures.encode(message.experimentalFeatures, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); return writer; }; @@ -34094,6 +34134,10 @@ message.common = $root.google.api.CommonLanguageSettings.decode(reader, reader.uint32()); break; } + case 2: { + message.experimentalFeatures = $root.google.api.PythonSettings.ExperimentalFeatures.decode(reader, reader.uint32()); + break; + } default: reader.skipType(tag & 7); break; @@ -34134,6 +34178,11 @@ if (error) return "common." + error; } + if (message.experimentalFeatures != null && message.hasOwnProperty("experimentalFeatures")) { + var error = $root.google.api.PythonSettings.ExperimentalFeatures.verify(message.experimentalFeatures); + if (error) + return "experimentalFeatures." + error; + } return null; }; @@ -34154,6 +34203,11 @@ 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; }; @@ -34170,10 +34224,14 @@ 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; }; @@ -34203,6 +34261,258 @@ 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 + * @property {boolean|null} [unversionedPackageDisabled] ExperimentalFeatures unversionedPackageDisabled + */ + + /** + * 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; + + /** + * ExperimentalFeatures unversionedPackageDisabled. + * @member {boolean} unversionedPackageDisabled + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @instance + */ + ExperimentalFeatures.prototype.unversionedPackageDisabled = false; + + /** + * Creates a new ExperimentalFeatures instance using the specified properties. + * @function create + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures=} [properties] Properties to set + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures instance + */ + ExperimentalFeatures.create = function create(properties) { + return new ExperimentalFeatures(properties); + }; + + /** + * Encodes the specified ExperimentalFeatures message. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @function encode + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures} message ExperimentalFeatures message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExperimentalFeatures.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.restAsyncIoEnabled != null && Object.hasOwnProperty.call(message, "restAsyncIoEnabled")) + writer.uint32(/* id 1, wireType 0 =*/8).bool(message.restAsyncIoEnabled); + if (message.protobufPythonicTypesEnabled != null && Object.hasOwnProperty.call(message, "protobufPythonicTypesEnabled")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.protobufPythonicTypesEnabled); + if (message.unversionedPackageDisabled != null && Object.hasOwnProperty.call(message, "unversionedPackageDisabled")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.unversionedPackageDisabled); + return writer; + }; + + /** + * Encodes the specified ExperimentalFeatures message, length delimited. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures} message ExperimentalFeatures message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExperimentalFeatures.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer. + * @function decode + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExperimentalFeatures.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.PythonSettings.ExperimentalFeatures(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.restAsyncIoEnabled = reader.bool(); + break; + } + case 2: { + message.protobufPythonicTypesEnabled = reader.bool(); + break; + } + case 3: { + message.unversionedPackageDisabled = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExperimentalFeatures.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ExperimentalFeatures message. + * @function verify + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExperimentalFeatures.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.restAsyncIoEnabled != null && message.hasOwnProperty("restAsyncIoEnabled")) + if (typeof message.restAsyncIoEnabled !== "boolean") + return "restAsyncIoEnabled: boolean expected"; + if (message.protobufPythonicTypesEnabled != null && message.hasOwnProperty("protobufPythonicTypesEnabled")) + if (typeof message.protobufPythonicTypesEnabled !== "boolean") + return "protobufPythonicTypesEnabled: boolean expected"; + if (message.unversionedPackageDisabled != null && message.hasOwnProperty("unversionedPackageDisabled")) + if (typeof message.unversionedPackageDisabled !== "boolean") + return "unversionedPackageDisabled: boolean expected"; + return null; + }; + + /** + * 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); + if (object.unversionedPackageDisabled != null) + message.unversionedPackageDisabled = Boolean(object.unversionedPackageDisabled); + 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; + object.unversionedPackageDisabled = false; + } + if (message.restAsyncIoEnabled != null && message.hasOwnProperty("restAsyncIoEnabled")) + object.restAsyncIoEnabled = message.restAsyncIoEnabled; + if (message.protobufPythonicTypesEnabled != null && message.hasOwnProperty("protobufPythonicTypesEnabled")) + object.protobufPythonicTypesEnabled = message.protobufPythonicTypesEnabled; + if (message.unversionedPackageDisabled != null && message.hasOwnProperty("unversionedPackageDisabled")) + object.unversionedPackageDisabled = message.unversionedPackageDisabled; + 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; })(); @@ -35079,6 +35389,7 @@ * @memberof google.api * @interface IGoSettings * @property {google.api.ICommonLanguageSettings|null} [common] GoSettings common + * @property {Object.|null} [renamedServices] GoSettings renamedServices */ /** @@ -35090,6 +35401,7 @@ * @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) @@ -35104,6 +35416,14 @@ */ GoSettings.prototype.common = null; + /** + * GoSettings renamedServices. + * @member {Object.} renamedServices + * @memberof google.api.GoSettings + * @instance + */ + GoSettings.prototype.renamedServices = $util.emptyObject; + /** * Creates a new GoSettings instance using the specified properties. * @function create @@ -35130,6 +35450,9 @@ writer = $Writer.create(); if (message.common != null && Object.hasOwnProperty.call(message, "common")) $root.google.api.CommonLanguageSettings.encode(message.common, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.renamedServices != null && Object.hasOwnProperty.call(message, "renamedServices")) + for (var keys = Object.keys(message.renamedServices), i = 0; i < keys.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.renamedServices[keys[i]]).ldelim(); return writer; }; @@ -35160,7 +35483,7 @@ GoSettings.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.GoSettings(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.GoSettings(), key, value; while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -35170,6 +35493,29 @@ message.common = $root.google.api.CommonLanguageSettings.decode(reader, reader.uint32()); break; } + case 2: { + if (message.renamedServices === $util.emptyObject) + message.renamedServices = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.renamedServices[key] = value; + break; + } default: reader.skipType(tag & 7); break; @@ -35210,6 +35556,14 @@ if (error) return "common." + error; } + if (message.renamedServices != null && message.hasOwnProperty("renamedServices")) { + if (!$util.isObject(message.renamedServices)) + return "renamedServices: object expected"; + var key = Object.keys(message.renamedServices); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.renamedServices[key[i]])) + return "renamedServices: string{k:string} expected"; + } return null; }; @@ -35230,6 +35584,13 @@ 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; }; @@ -35246,10 +35607,18 @@ 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; }; @@ -35888,30 +36257,275 @@ return values; })(); - /** - * LaunchStage enum. - * @name google.api.LaunchStage - * @enum {number} - * @property {number} LAUNCH_STAGE_UNSPECIFIED=0 LAUNCH_STAGE_UNSPECIFIED value - * @property {number} UNIMPLEMENTED=6 UNIMPLEMENTED value - * @property {number} PRELAUNCH=7 PRELAUNCH value - * @property {number} EARLY_ACCESS=1 EARLY_ACCESS value - * @property {number} ALPHA=2 ALPHA value - * @property {number} BETA=3 BETA value - * @property {number} GA=4 GA value - * @property {number} DEPRECATED=5 DEPRECATED value - */ - api.LaunchStage = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "LAUNCH_STAGE_UNSPECIFIED"] = 0; - values[valuesById[6] = "UNIMPLEMENTED"] = 6; - values[valuesById[7] = "PRELAUNCH"] = 7; - values[valuesById[1] = "EARLY_ACCESS"] = 1; - values[valuesById[2] = "ALPHA"] = 2; - values[valuesById[3] = "BETA"] = 3; - values[valuesById[4] = "GA"] = 4; - values[valuesById[5] = "DEPRECATED"] = 5; - 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 new SelectiveGapicGeneration instance using the specified properties. + * @function create + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration=} [properties] Properties to set + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration instance + */ + SelectiveGapicGeneration.create = function create(properties) { + return new SelectiveGapicGeneration(properties); + }; + + /** + * Encodes the specified SelectiveGapicGeneration message. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @function encode + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration} message SelectiveGapicGeneration message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SelectiveGapicGeneration.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.methods != null && message.methods.length) + for (var i = 0; i < message.methods.length; ++i) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.methods[i]); + if (message.generateOmittedAsInternal != null && Object.hasOwnProperty.call(message, "generateOmittedAsInternal")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.generateOmittedAsInternal); + return writer; + }; + + /** + * Encodes the specified SelectiveGapicGeneration message, length delimited. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration} message SelectiveGapicGeneration message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SelectiveGapicGeneration.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer. + * @function decode + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SelectiveGapicGeneration.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.SelectiveGapicGeneration(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.methods && message.methods.length)) + message.methods = []; + message.methods.push(reader.string()); + break; + } + case 2: { + message.generateOmittedAsInternal = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SelectiveGapicGeneration.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SelectiveGapicGeneration message. + * @function verify + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SelectiveGapicGeneration.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.methods != null && message.hasOwnProperty("methods")) { + if (!Array.isArray(message.methods)) + return "methods: array expected"; + for (var i = 0; i < message.methods.length; ++i) + if (!$util.isString(message.methods[i])) + return "methods: string[] expected"; + } + if (message.generateOmittedAsInternal != null && message.hasOwnProperty("generateOmittedAsInternal")) + if (typeof message.generateOmittedAsInternal !== "boolean") + return "generateOmittedAsInternal: boolean expected"; + return null; + }; + + /** + * 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 + * @enum {number} + * @property {number} LAUNCH_STAGE_UNSPECIFIED=0 LAUNCH_STAGE_UNSPECIFIED value + * @property {number} UNIMPLEMENTED=6 UNIMPLEMENTED value + * @property {number} PRELAUNCH=7 PRELAUNCH value + * @property {number} EARLY_ACCESS=1 EARLY_ACCESS value + * @property {number} ALPHA=2 ALPHA value + * @property {number} BETA=3 BETA value + * @property {number} GA=4 GA value + * @property {number} DEPRECATED=5 DEPRECATED value + */ + api.LaunchStage = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "LAUNCH_STAGE_UNSPECIFIED"] = 0; + values[valuesById[6] = "UNIMPLEMENTED"] = 6; + values[valuesById[7] = "PRELAUNCH"] = 7; + values[valuesById[1] = "EARLY_ACCESS"] = 1; + values[valuesById[2] = "ALPHA"] = 2; + values[valuesById[3] = "BETA"] = 3; + values[valuesById[4] = "GA"] = 4; + values[valuesById[5] = "DEPRECATED"] = 5; + return values; })(); return api; @@ -36157,6 +36771,7 @@ * @name google.protobuf.Edition * @enum {number} * @property {number} EDITION_UNKNOWN=0 EDITION_UNKNOWN value + * @property {number} EDITION_LEGACY=900 EDITION_LEGACY value * @property {number} EDITION_PROTO2=998 EDITION_PROTO2 value * @property {number} EDITION_PROTO3=999 EDITION_PROTO3 value * @property {number} EDITION_2023=1000 EDITION_2023 value @@ -36171,6 +36786,7 @@ protobuf.Edition = (function() { var valuesById = {}, values = Object.create(valuesById); values[valuesById[0] = "EDITION_UNKNOWN"] = 0; + values[valuesById[900] = "EDITION_LEGACY"] = 900; values[valuesById[998] = "EDITION_PROTO2"] = 998; values[valuesById[999] = "EDITION_PROTO3"] = 999; values[valuesById[1000] = "EDITION_2023"] = 1000; @@ -36195,6 +36811,7 @@ * @property {Array.|null} [dependency] FileDescriptorProto dependency * @property {Array.|null} [publicDependency] FileDescriptorProto publicDependency * @property {Array.|null} [weakDependency] FileDescriptorProto weakDependency + * @property {Array.|null} [optionDependency] FileDescriptorProto optionDependency * @property {Array.|null} [messageType] FileDescriptorProto messageType * @property {Array.|null} [enumType] FileDescriptorProto enumType * @property {Array.|null} [service] FileDescriptorProto service @@ -36217,6 +36834,7 @@ this.dependency = []; this.publicDependency = []; this.weakDependency = []; + this.optionDependency = []; this.messageType = []; this.enumType = []; this.service = []; @@ -36267,6 +36885,14 @@ */ FileDescriptorProto.prototype.weakDependency = $util.emptyArray; + /** + * FileDescriptorProto optionDependency. + * @member {Array.} optionDependency + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.optionDependency = $util.emptyArray; + /** * FileDescriptorProto messageType. * @member {Array.} messageType @@ -36388,6 +37014,9 @@ writer.uint32(/* id 12, wireType 2 =*/98).string(message.syntax); if (message.edition != null && Object.hasOwnProperty.call(message, "edition")) writer.uint32(/* id 14, wireType 0 =*/112).int32(message.edition); + if (message.optionDependency != null && message.optionDependency.length) + for (var i = 0; i < message.optionDependency.length; ++i) + writer.uint32(/* id 15, wireType 2 =*/122).string(message.optionDependency[i]); return writer; }; @@ -36460,6 +37089,12 @@ message.weakDependency.push(reader.int32()); break; } + case 15: { + if (!(message.optionDependency && message.optionDependency.length)) + message.optionDependency = []; + message.optionDependency.push(reader.string()); + break; + } case 4: { if (!(message.messageType && message.messageType.length)) message.messageType = []; @@ -36562,6 +37197,13 @@ if (!$util.isInteger(message.weakDependency[i])) return "weakDependency: integer[] expected"; } + if (message.optionDependency != null && message.hasOwnProperty("optionDependency")) { + if (!Array.isArray(message.optionDependency)) + return "optionDependency: array expected"; + for (var i = 0; i < message.optionDependency.length; ++i) + if (!$util.isString(message.optionDependency[i])) + return "optionDependency: string[] expected"; + } if (message.messageType != null && message.hasOwnProperty("messageType")) { if (!Array.isArray(message.messageType)) return "messageType: array expected"; @@ -36616,6 +37258,7 @@ default: return "edition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -36668,6 +37311,13 @@ for (var i = 0; i < object.weakDependency.length; ++i) message.weakDependency[i] = object.weakDependency[i] | 0; } + if (object.optionDependency) { + if (!Array.isArray(object.optionDependency)) + throw TypeError(".google.protobuf.FileDescriptorProto.optionDependency: array expected"); + message.optionDependency = []; + for (var i = 0; i < object.optionDependency.length; ++i) + message.optionDependency[i] = String(object.optionDependency[i]); + } if (object.messageType) { if (!Array.isArray(object.messageType)) throw TypeError(".google.protobuf.FileDescriptorProto.messageType: array expected"); @@ -36731,6 +37381,10 @@ case 0: message.edition = 0; break; + case "EDITION_LEGACY": + case 900: + message.edition = 900; + break; case "EDITION_PROTO2": case 998: message.edition = 998; @@ -36796,6 +37450,7 @@ object.extension = []; object.publicDependency = []; object.weakDependency = []; + object.optionDependency = []; } if (options.defaults) { object.name = ""; @@ -36852,6 +37507,11 @@ 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; + if (message.optionDependency && message.optionDependency.length) { + object.optionDependency = []; + for (var j = 0; j < message.optionDependency.length; ++j) + object.optionDependency[j] = message.optionDependency[j]; + } return object; }; @@ -36900,6 +37560,7 @@ * @property {google.protobuf.IMessageOptions|null} [options] DescriptorProto options * @property {Array.|null} [reservedRange] DescriptorProto reservedRange * @property {Array.|null} [reservedName] DescriptorProto reservedName + * @property {google.protobuf.SymbolVisibility|null} [visibility] DescriptorProto visibility */ /** @@ -37005,6 +37666,14 @@ */ DescriptorProto.prototype.reservedName = $util.emptyArray; + /** + * DescriptorProto visibility. + * @member {google.protobuf.SymbolVisibility} visibility + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.visibility = 0; + /** * Creates a new DescriptorProto instance using the specified properties. * @function create @@ -37057,6 +37726,8 @@ if (message.reservedName != null && message.reservedName.length) for (var i = 0; i < message.reservedName.length; ++i) writer.uint32(/* id 10, wireType 2 =*/82).string(message.reservedName[i]); + if (message.visibility != null && Object.hasOwnProperty.call(message, "visibility")) + writer.uint32(/* id 11, wireType 0 =*/88).int32(message.visibility); return writer; }; @@ -37149,6 +37820,10 @@ message.reservedName.push(reader.string()); break; } + case 11: { + message.visibility = reader.int32(); + break; + } default: reader.skipType(tag & 7); break; @@ -37262,6 +37937,15 @@ if (!$util.isString(message.reservedName[i])) return "reservedName: string[] expected"; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + switch (message.visibility) { + default: + return "visibility: enum value expected"; + case 0: + case 1: + case 2: + break; + } return null; }; @@ -37361,6 +38045,26 @@ for (var i = 0; i < object.reservedName.length; ++i) message.reservedName[i] = String(object.reservedName[i]); } + switch (object.visibility) { + default: + if (typeof object.visibility === "number") { + message.visibility = object.visibility; + break; + } + break; + case "VISIBILITY_UNSET": + case 0: + message.visibility = 0; + break; + case "VISIBILITY_LOCAL": + case 1: + message.visibility = 1; + break; + case "VISIBILITY_EXPORT": + case 2: + message.visibility = 2; + break; + } return message; }; @@ -37390,6 +38094,7 @@ if (options.defaults) { object.name = ""; object.options = null; + object.visibility = options.enums === String ? "VISIBILITY_UNSET" : 0; } if (message.name != null && message.hasOwnProperty("name")) object.name = message.name; @@ -37435,6 +38140,8 @@ for (var j = 0; j < message.reservedName.length; ++j) object.reservedName[j] = message.reservedName[j]; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + object.visibility = options.enums === String ? $root.google.protobuf.SymbolVisibility[message.visibility] === undefined ? message.visibility : $root.google.protobuf.SymbolVisibility[message.visibility] : message.visibility; return object; }; @@ -39479,6 +40186,7 @@ * @property {google.protobuf.IEnumOptions|null} [options] EnumDescriptorProto options * @property {Array.|null} [reservedRange] EnumDescriptorProto reservedRange * @property {Array.|null} [reservedName] EnumDescriptorProto reservedName + * @property {google.protobuf.SymbolVisibility|null} [visibility] EnumDescriptorProto visibility */ /** @@ -39539,6 +40247,14 @@ */ EnumDescriptorProto.prototype.reservedName = $util.emptyArray; + /** + * EnumDescriptorProto visibility. + * @member {google.protobuf.SymbolVisibility} visibility + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.visibility = 0; + /** * Creates a new EnumDescriptorProto instance using the specified properties. * @function create @@ -39576,6 +40292,8 @@ if (message.reservedName != null && message.reservedName.length) for (var i = 0; i < message.reservedName.length; ++i) writer.uint32(/* id 5, wireType 2 =*/42).string(message.reservedName[i]); + if (message.visibility != null && Object.hasOwnProperty.call(message, "visibility")) + writer.uint32(/* id 6, wireType 0 =*/48).int32(message.visibility); return writer; }; @@ -39638,6 +40356,10 @@ message.reservedName.push(reader.string()); break; } + case 6: { + message.visibility = reader.int32(); + break; + } default: reader.skipType(tag & 7); break; @@ -39706,6 +40428,15 @@ if (!$util.isString(message.reservedName[i])) return "reservedName: string[] expected"; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + switch (message.visibility) { + default: + return "visibility: enum value expected"; + case 0: + case 1: + case 2: + break; + } return null; }; @@ -39755,6 +40486,26 @@ for (var i = 0; i < object.reservedName.length; ++i) message.reservedName[i] = String(object.reservedName[i]); } + switch (object.visibility) { + default: + if (typeof object.visibility === "number") { + message.visibility = object.visibility; + break; + } + break; + case "VISIBILITY_UNSET": + case 0: + message.visibility = 0; + break; + case "VISIBILITY_LOCAL": + case 1: + message.visibility = 1; + break; + case "VISIBILITY_EXPORT": + case 2: + message.visibility = 2; + break; + } return message; }; @@ -39779,6 +40530,7 @@ if (options.defaults) { object.name = ""; object.options = null; + object.visibility = options.enums === String ? "VISIBILITY_UNSET" : 0; } if (message.name != null && message.hasOwnProperty("name")) object.name = message.name; @@ -39799,6 +40551,8 @@ for (var j = 0; j < message.reservedName.length; ++j) object.reservedName[j] = message.reservedName[j]; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + object.visibility = options.enums === String ? $root.google.protobuf.SymbolVisibility[message.visibility] === undefined ? message.visibility : $root.google.protobuf.SymbolVisibility[message.visibility] : message.visibility; return object; }; @@ -42117,6 +42871,7 @@ * @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 @@ -42237,6 +42992,14 @@ */ 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 @@ -42311,6 +43074,8 @@ $root.google.protobuf.FieldOptions.EditionDefault.encode(message.editionDefaults[i], writer.uint32(/* id 20, wireType 2 =*/162).fork()).ldelim(); if (message.features != null && Object.hasOwnProperty.call(message, "features")) $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 21, wireType 2 =*/170).fork()).ldelim(); + if (message.featureSupport != null && Object.hasOwnProperty.call(message, "featureSupport")) + $root.google.protobuf.FieldOptions.FeatureSupport.encode(message.featureSupport, writer.uint32(/* id 22, wireType 2 =*/178).fork()).ldelim(); if (message.uninterpretedOption != null && message.uninterpretedOption.length) for (var i = 0; i < message.uninterpretedOption.length; ++i) $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); @@ -42412,6 +43177,10 @@ message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); break; } + case 22: { + message.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.decode(reader, reader.uint32()); + break; + } case 999: { if (!(message.uninterpretedOption && message.uninterpretedOption.length)) message.uninterpretedOption = []; @@ -42547,6 +43316,11 @@ if (error) return "features." + error; } + if (message.featureSupport != null && message.hasOwnProperty("featureSupport")) { + var error = $root.google.protobuf.FieldOptions.FeatureSupport.verify(message.featureSupport); + if (error) + return "featureSupport." + error; + } if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { if (!Array.isArray(message.uninterpretedOption)) return "uninterpretedOption: array expected"; @@ -42735,6 +43509,11 @@ 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"); @@ -42832,6 +43611,7 @@ 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")) @@ -42864,6 +43644,8 @@ } 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) @@ -43136,6 +43918,7 @@ default: return "edition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -43177,103 +43960,589 @@ 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; + 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 EditionDefault message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {google.protobuf.FieldOptions.EditionDefault} message EditionDefault + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EditionDefault.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.value = ""; + object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; + } + 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 EditionDefault to JSON. + * @function toJSON + * @memberof google.protobuf.FieldOptions.EditionDefault + * @instance + * @returns {Object.} JSON object + */ + EditionDefault.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * 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; + })(); + + 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 new FeatureSupport instance using the specified properties. + * @function create + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport=} [properties] Properties to set + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport instance + */ + FeatureSupport.create = function create(properties) { + return new FeatureSupport(properties); + }; + + /** + * Encodes the specified FeatureSupport message. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport} message FeatureSupport message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FeatureSupport.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.editionIntroduced != null && Object.hasOwnProperty.call(message, "editionIntroduced")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.editionIntroduced); + if (message.editionDeprecated != null && Object.hasOwnProperty.call(message, "editionDeprecated")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.editionDeprecated); + if (message.deprecationWarning != null && Object.hasOwnProperty.call(message, "deprecationWarning")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.deprecationWarning); + if (message.editionRemoved != null && Object.hasOwnProperty.call(message, "editionRemoved")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.editionRemoved); + return writer; + }; + + /** + * Encodes the specified FeatureSupport message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport} message FeatureSupport message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FeatureSupport.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FeatureSupport.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FieldOptions.FeatureSupport(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.editionIntroduced = reader.int32(); + break; + } + case 2: { + message.editionDeprecated = reader.int32(); + break; + } + case 3: { + message.deprecationWarning = reader.string(); + break; + } + case 4: { + message.editionRemoved = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FeatureSupport.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FeatureSupport message. + * @function verify + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FeatureSupport.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.editionIntroduced != null && message.hasOwnProperty("editionIntroduced")) + switch (message.editionIntroduced) { + default: + return "editionIntroduced: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + if (message.editionDeprecated != null && message.hasOwnProperty("editionDeprecated")) + switch (message.editionDeprecated) { + default: + return "editionDeprecated: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + if (message.deprecationWarning != null && message.hasOwnProperty("deprecationWarning")) + if (!$util.isString(message.deprecationWarning)) + return "deprecationWarning: string expected"; + if (message.editionRemoved != null && message.hasOwnProperty("editionRemoved")) + switch (message.editionRemoved) { + default: + return "editionRemoved: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + return null; + }; + + /** + * 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.edition = 1000; + message.editionRemoved = 1000; break; case "EDITION_2024": case 1001: - message.edition = 1001; + message.editionRemoved = 1001; break; case "EDITION_1_TEST_ONLY": case 1: - message.edition = 1; + message.editionRemoved = 1; break; case "EDITION_2_TEST_ONLY": case 2: - message.edition = 2; + message.editionRemoved = 2; break; case "EDITION_99997_TEST_ONLY": case 99997: - message.edition = 99997; + message.editionRemoved = 99997; break; case "EDITION_99998_TEST_ONLY": case 99998: - message.edition = 99998; + message.editionRemoved = 99998; break; case "EDITION_99999_TEST_ONLY": case 99999: - message.edition = 99999; + message.editionRemoved = 99999; break; case "EDITION_MAX": case 2147483647: - message.edition = 2147483647; + message.editionRemoved = 2147483647; break; } - 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 FeatureSupport message. Also converts values to other types if specified. * @function toObject - * @memberof google.protobuf.FieldOptions.EditionDefault + * @memberof google.protobuf.FieldOptions.FeatureSupport * @static - * @param {google.protobuf.FieldOptions.EditionDefault} message EditionDefault + * @param {google.protobuf.FieldOptions.FeatureSupport} message FeatureSupport * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - EditionDefault.toObject = function toObject(message, options) { + FeatureSupport.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { - object.value = ""; - object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; - } - 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; + 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 EditionDefault to JSON. + * Converts this FeatureSupport to JSON. * @function toJSON - * @memberof google.protobuf.FieldOptions.EditionDefault + * @memberof google.protobuf.FieldOptions.FeatureSupport * @instance * @returns {Object.} JSON object */ - EditionDefault.prototype.toJSON = function toJSON() { + FeatureSupport.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 FeatureSupport * @function getTypeUrl - * @memberof google.protobuf.FieldOptions.EditionDefault + * @memberof google.protobuf.FieldOptions.FeatureSupport * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - EditionDefault.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + FeatureSupport.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.protobuf.FieldOptions.EditionDefault"; + return typeUrlPrefix + "/google.protobuf.FieldOptions.FeatureSupport"; }; - return EditionDefault; + return FeatureSupport; })(); return FieldOptions; @@ -43868,6 +45137,7 @@ * @property {boolean|null} [deprecated] EnumValueOptions deprecated * @property {google.protobuf.IFeatureSet|null} [features] EnumValueOptions features * @property {boolean|null} [debugRedact] EnumValueOptions debugRedact + * @property {google.protobuf.FieldOptions.IFeatureSupport|null} [featureSupport] EnumValueOptions featureSupport * @property {Array.|null} [uninterpretedOption] EnumValueOptions uninterpretedOption */ @@ -43911,6 +45181,14 @@ */ EnumValueOptions.prototype.debugRedact = false; + /** + * EnumValueOptions featureSupport. + * @member {google.protobuf.FieldOptions.IFeatureSupport|null|undefined} featureSupport + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.featureSupport = null; + /** * EnumValueOptions uninterpretedOption. * @member {Array.} uninterpretedOption @@ -43949,6 +45227,8 @@ $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); if (message.debugRedact != null && Object.hasOwnProperty.call(message, "debugRedact")) writer.uint32(/* id 3, wireType 0 =*/24).bool(message.debugRedact); + if (message.featureSupport != null && Object.hasOwnProperty.call(message, "featureSupport")) + $root.google.protobuf.FieldOptions.FeatureSupport.encode(message.featureSupport, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); if (message.uninterpretedOption != null && message.uninterpretedOption.length) for (var i = 0; i < message.uninterpretedOption.length; ++i) $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); @@ -44000,6 +45280,10 @@ message.debugRedact = reader.bool(); break; } + case 4: { + message.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.decode(reader, reader.uint32()); + break; + } case 999: { if (!(message.uninterpretedOption && message.uninterpretedOption.length)) message.uninterpretedOption = []; @@ -44052,6 +45336,11 @@ if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) if (typeof message.debugRedact !== "boolean") return "debugRedact: boolean expected"; + if (message.featureSupport != null && message.hasOwnProperty("featureSupport")) { + var error = $root.google.protobuf.FieldOptions.FeatureSupport.verify(message.featureSupport); + if (error) + return "featureSupport." + error; + } if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { if (!Array.isArray(message.uninterpretedOption)) return "uninterpretedOption: array expected"; @@ -44085,6 +45374,11 @@ } if (object.debugRedact != null) message.debugRedact = Boolean(object.debugRedact); + if (object.featureSupport != null) { + if (typeof object.featureSupport !== "object") + throw TypeError(".google.protobuf.EnumValueOptions.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.EnumValueOptions.uninterpretedOption: array expected"); @@ -44117,6 +45411,7 @@ object.deprecated = false; object.features = null; object.debugRedact = false; + object.featureSupport = null; } if (message.deprecated != null && message.hasOwnProperty("deprecated")) object.deprecated = message.deprecated; @@ -44124,6 +45419,8 @@ object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) object.debugRedact = message.debugRedact; + 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) @@ -45563,6 +46860,8 @@ * @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 + * @property {google.protobuf.FeatureSet.EnforceNamingStyle|null} [enforceNamingStyle] FeatureSet enforceNamingStyle + * @property {google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|null} [defaultSymbolVisibility] FeatureSet defaultSymbolVisibility */ /** @@ -45628,6 +46927,22 @@ */ FeatureSet.prototype.jsonFormat = 0; + /** + * FeatureSet enforceNamingStyle. + * @member {google.protobuf.FeatureSet.EnforceNamingStyle} enforceNamingStyle + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.enforceNamingStyle = 0; + + /** + * FeatureSet defaultSymbolVisibility. + * @member {google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility} defaultSymbolVisibility + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.defaultSymbolVisibility = 0; + /** * Creates a new FeatureSet instance using the specified properties. * @function create @@ -45664,6 +46979,10 @@ writer.uint32(/* id 5, wireType 0 =*/40).int32(message.messageEncoding); if (message.jsonFormat != null && Object.hasOwnProperty.call(message, "jsonFormat")) writer.uint32(/* id 6, wireType 0 =*/48).int32(message.jsonFormat); + if (message.enforceNamingStyle != null && Object.hasOwnProperty.call(message, "enforceNamingStyle")) + writer.uint32(/* id 7, wireType 0 =*/56).int32(message.enforceNamingStyle); + if (message.defaultSymbolVisibility != null && Object.hasOwnProperty.call(message, "defaultSymbolVisibility")) + writer.uint32(/* id 8, wireType 0 =*/64).int32(message.defaultSymbolVisibility); return writer; }; @@ -45724,6 +47043,14 @@ message.jsonFormat = reader.int32(); break; } + case 7: { + message.enforceNamingStyle = reader.int32(); + break; + } + case 8: { + message.defaultSymbolVisibility = reader.int32(); + break; + } default: reader.skipType(tag & 7); break; @@ -45814,6 +47141,26 @@ case 2: break; } + if (message.enforceNamingStyle != null && message.hasOwnProperty("enforceNamingStyle")) + switch (message.enforceNamingStyle) { + default: + return "enforceNamingStyle: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.defaultSymbolVisibility != null && message.hasOwnProperty("defaultSymbolVisibility")) + switch (message.defaultSymbolVisibility) { + default: + return "defaultSymbolVisibility: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + break; + } return null; }; @@ -45953,6 +47300,54 @@ message.jsonFormat = 2; break; } + switch (object.enforceNamingStyle) { + default: + if (typeof object.enforceNamingStyle === "number") { + message.enforceNamingStyle = object.enforceNamingStyle; + break; + } + break; + case "ENFORCE_NAMING_STYLE_UNKNOWN": + case 0: + message.enforceNamingStyle = 0; + break; + case "STYLE2024": + case 1: + message.enforceNamingStyle = 1; + break; + case "STYLE_LEGACY": + case 2: + message.enforceNamingStyle = 2; + break; + } + switch (object.defaultSymbolVisibility) { + default: + if (typeof object.defaultSymbolVisibility === "number") { + message.defaultSymbolVisibility = object.defaultSymbolVisibility; + break; + } + break; + case "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN": + case 0: + message.defaultSymbolVisibility = 0; + break; + case "EXPORT_ALL": + case 1: + message.defaultSymbolVisibility = 1; + break; + case "EXPORT_TOP_LEVEL": + case 2: + message.defaultSymbolVisibility = 2; + break; + case "LOCAL_ALL": + case 3: + message.defaultSymbolVisibility = 3; + break; + case "STRICT": + case 4: + message.defaultSymbolVisibility = 4; + break; + } return message; }; @@ -45976,6 +47371,8 @@ 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; + object.enforceNamingStyle = options.enums === String ? "ENFORCE_NAMING_STYLE_UNKNOWN" : 0; + object.defaultSymbolVisibility = options.enums === String ? "DEFAULT_SYMBOL_VISIBILITY_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; @@ -45989,6 +47386,10 @@ 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; + if (message.enforceNamingStyle != null && message.hasOwnProperty("enforceNamingStyle")) + object.enforceNamingStyle = options.enums === String ? $root.google.protobuf.FeatureSet.EnforceNamingStyle[message.enforceNamingStyle] === undefined ? message.enforceNamingStyle : $root.google.protobuf.FeatureSet.EnforceNamingStyle[message.enforceNamingStyle] : message.enforceNamingStyle; + if (message.defaultSymbolVisibility != null && message.hasOwnProperty("defaultSymbolVisibility")) + object.defaultSymbolVisibility = options.enums === String ? $root.google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility[message.defaultSymbolVisibility] === undefined ? message.defaultSymbolVisibility : $root.google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility[message.defaultSymbolVisibility] : message.defaultSymbolVisibility; return object; }; @@ -46116,6 +47517,219 @@ return values; })(); + /** + * EnforceNamingStyle enum. + * @name google.protobuf.FeatureSet.EnforceNamingStyle + * @enum {number} + * @property {number} ENFORCE_NAMING_STYLE_UNKNOWN=0 ENFORCE_NAMING_STYLE_UNKNOWN value + * @property {number} STYLE2024=1 STYLE2024 value + * @property {number} STYLE_LEGACY=2 STYLE_LEGACY value + */ + FeatureSet.EnforceNamingStyle = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ENFORCE_NAMING_STYLE_UNKNOWN"] = 0; + values[valuesById[1] = "STYLE2024"] = 1; + values[valuesById[2] = "STYLE_LEGACY"] = 2; + return values; + })(); + + FeatureSet.VisibilityFeature = (function() { + + /** + * Properties of a VisibilityFeature. + * @memberof google.protobuf.FeatureSet + * @interface IVisibilityFeature + */ + + /** + * Constructs a new VisibilityFeature. + * @memberof google.protobuf.FeatureSet + * @classdesc Represents a VisibilityFeature. + * @implements IVisibilityFeature + * @constructor + * @param {google.protobuf.FeatureSet.IVisibilityFeature=} [properties] Properties to set + */ + function VisibilityFeature(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 new VisibilityFeature instance using the specified properties. + * @function create + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature=} [properties] Properties to set + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature instance + */ + VisibilityFeature.create = function create(properties) { + return new VisibilityFeature(properties); + }; + + /** + * Encodes the specified VisibilityFeature message. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature} message VisibilityFeature message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + VisibilityFeature.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + return writer; + }; + + /** + * Encodes the specified VisibilityFeature message, length delimited. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature} message VisibilityFeature message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + VisibilityFeature.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + VisibilityFeature.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FeatureSet.VisibilityFeature(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + VisibilityFeature.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a VisibilityFeature message. + * @function verify + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + VisibilityFeature.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + return null; + }; + + /** + * Creates a VisibilityFeature message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + */ + VisibilityFeature.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FeatureSet.VisibilityFeature) + return object; + return new $root.google.protobuf.FeatureSet.VisibilityFeature(); + }; + + /** + * Creates a plain object from a VisibilityFeature message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.VisibilityFeature} message VisibilityFeature + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + VisibilityFeature.toObject = function toObject() { + return {}; + }; + + /** + * Converts this VisibilityFeature to JSON. + * @function toJSON + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @instance + * @returns {Object.} JSON object + */ + VisibilityFeature.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for VisibilityFeature + * @function getTypeUrl + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + VisibilityFeature.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FeatureSet.VisibilityFeature"; + }; + + /** + * DefaultSymbolVisibility enum. + * @name google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility + * @enum {number} + * @property {number} DEFAULT_SYMBOL_VISIBILITY_UNKNOWN=0 DEFAULT_SYMBOL_VISIBILITY_UNKNOWN value + * @property {number} EXPORT_ALL=1 EXPORT_ALL value + * @property {number} EXPORT_TOP_LEVEL=2 EXPORT_TOP_LEVEL value + * @property {number} LOCAL_ALL=3 LOCAL_ALL value + * @property {number} STRICT=4 STRICT value + */ + VisibilityFeature.DefaultSymbolVisibility = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN"] = 0; + values[valuesById[1] = "EXPORT_ALL"] = 1; + values[valuesById[2] = "EXPORT_TOP_LEVEL"] = 2; + values[valuesById[3] = "LOCAL_ALL"] = 3; + values[valuesById[4] = "STRICT"] = 4; + return values; + })(); + + return VisibilityFeature; + })(); + return FeatureSet; })(); @@ -46300,6 +47914,7 @@ default: return "minimumEdition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -46317,6 +47932,7 @@ default: return "maximumEdition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -46365,6 +47981,10 @@ case 0: message.minimumEdition = 0; break; + case "EDITION_LEGACY": + case 900: + message.minimumEdition = 900; + break; case "EDITION_PROTO2": case 998: message.minimumEdition = 998; @@ -46417,6 +48037,10 @@ case 0: message.maximumEdition = 0; break; + case "EDITION_LEGACY": + case 900: + message.maximumEdition = 900; + break; case "EDITION_PROTO2": case 998: message.maximumEdition = 998; @@ -46525,7 +48149,8 @@ * @memberof google.protobuf.FeatureSetDefaults * @interface IFeatureSetEditionDefault * @property {google.protobuf.Edition|null} [edition] FeatureSetEditionDefault edition - * @property {google.protobuf.IFeatureSet|null} [features] FeatureSetEditionDefault features + * @property {google.protobuf.IFeatureSet|null} [overridableFeatures] FeatureSetEditionDefault overridableFeatures + * @property {google.protobuf.IFeatureSet|null} [fixedFeatures] FeatureSetEditionDefault fixedFeatures */ /** @@ -46552,12 +48177,20 @@ FeatureSetEditionDefault.prototype.edition = 0; /** - * FeatureSetEditionDefault features. - * @member {google.protobuf.IFeatureSet|null|undefined} features + * 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 * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault * @instance */ - FeatureSetEditionDefault.prototype.features = null; + FeatureSetEditionDefault.prototype.fixedFeatures = null; /** * Creates a new FeatureSetEditionDefault instance using the specified properties. @@ -46583,10 +48216,12 @@ FeatureSetEditionDefault.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); - if (message.features != null && Object.hasOwnProperty.call(message, "features")) - $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); if (message.edition != null && Object.hasOwnProperty.call(message, "edition")) writer.uint32(/* id 3, wireType 0 =*/24).int32(message.edition); + if (message.overridableFeatures != null && Object.hasOwnProperty.call(message, "overridableFeatures")) + $root.google.protobuf.FeatureSet.encode(message.overridableFeatures, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.fixedFeatures != null && Object.hasOwnProperty.call(message, "fixedFeatures")) + $root.google.protobuf.FeatureSet.encode(message.fixedFeatures, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); return writer; }; @@ -46627,8 +48262,12 @@ message.edition = reader.int32(); break; } - case 2: { - message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + case 4: { + message.overridableFeatures = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + break; + } + case 5: { + message.fixedFeatures = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); break; } default: @@ -46671,6 +48310,7 @@ default: return "edition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -46683,10 +48323,15 @@ case 2147483647: break; } - if (message.features != null && message.hasOwnProperty("features")) { - var error = $root.google.protobuf.FeatureSet.verify(message.features); + if (message.overridableFeatures != null && message.hasOwnProperty("overridableFeatures")) { + var error = $root.google.protobuf.FeatureSet.verify(message.overridableFeatures); + if (error) + return "overridableFeatures." + error; + } + if (message.fixedFeatures != null && message.hasOwnProperty("fixedFeatures")) { + var error = $root.google.protobuf.FeatureSet.verify(message.fixedFeatures); if (error) - return "features." + error; + return "fixedFeatures." + error; } return null; }; @@ -46714,6 +48359,10 @@ case 0: message.edition = 0; break; + case "EDITION_LEGACY": + case 900: + message.edition = 900; + break; case "EDITION_PROTO2": case 998: message.edition = 998; @@ -46755,10 +48404,15 @@ message.edition = 2147483647; break; } - 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); + 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); } return message; }; @@ -46777,13 +48431,16 @@ 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; }; @@ -47998,6 +49655,22 @@ return GeneratedCodeInfo; })(); + /** + * SymbolVisibility enum. + * @name google.protobuf.SymbolVisibility + * @enum {number} + * @property {number} VISIBILITY_UNSET=0 VISIBILITY_UNSET value + * @property {number} VISIBILITY_LOCAL=1 VISIBILITY_LOCAL value + * @property {number} VISIBILITY_EXPORT=2 VISIBILITY_EXPORT value + */ + protobuf.SymbolVisibility = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "VISIBILITY_UNSET"] = 0; + values[valuesById[1] = "VISIBILITY_LOCAL"] = 1; + values[valuesById[2] = "VISIBILITY_EXPORT"] = 2; + return values; + })(); + protobuf.Timestamp = (function() { /** diff --git a/packages/google-ads-datamanager/protos/protos.json b/packages/google-ads-datamanager/protos/protos.json index d990a67211ea..6957010be06d 100644 --- a/packages/google-ads-datamanager/protos/protos.json +++ b/packages/google-ads-datamanager/protos/protos.json @@ -3625,8 +3625,7 @@ "java_multiple_files": true, "java_outer_classname": "LaunchStageProto", "java_package": "com.google.api", - "objc_class_prefix": "GAPI", - "cc_enable_arenas": true + "objc_class_prefix": "GAPI" }, "nested": { "fieldBehavior": { @@ -3849,6 +3848,10 @@ "rule": "repeated", "type": "ClientLibraryDestination", "id": 2 + }, + "selectiveGapicGeneration": { + "type": "SelectiveGapicGeneration", + "id": 3 } } }, @@ -3989,6 +3992,28 @@ "common": { "type": "CommonLanguageSettings", "id": 1 + }, + "experimentalFeatures": { + "type": "ExperimentalFeatures", + "id": 2 + } + }, + "nested": { + "ExperimentalFeatures": { + "fields": { + "restAsyncIoEnabled": { + "type": "bool", + "id": 1 + }, + "protobufPythonicTypesEnabled": { + "type": "bool", + "id": 2 + }, + "unversionedPackageDisabled": { + "type": "bool", + "id": 3 + } + } } } }, @@ -4046,6 +4071,11 @@ "common": { "type": "CommonLanguageSettings", "id": 1 + }, + "renamedServices": { + "keyType": "string", + "type": "string", + "id": 2 } } }, @@ -4107,6 +4137,19 @@ "PACKAGE_MANAGER": 20 } }, + "SelectiveGapicGeneration": { + "fields": { + "methods": { + "rule": "repeated", + "type": "string", + "id": 1 + }, + "generateOmittedAsInternal": { + "type": "bool", + "id": 2 + } + } + }, "LaunchStage": { "values": { "LAUNCH_STAGE_UNSPECIFIED": 0, @@ -4140,12 +4183,19 @@ "type": "FileDescriptorProto", "id": 1 } - } + }, + "extensions": [ + [ + 536000000, + 536000000 + ] + ] }, "Edition": { "edition": "proto2", "values": { "EDITION_UNKNOWN": 0, + "EDITION_LEGACY": 900, "EDITION_PROTO2": 998, "EDITION_PROTO3": 999, "EDITION_2023": 1000, @@ -4184,6 +4234,11 @@ "type": "int32", "id": 11 }, + "optionDependency": { + "rule": "repeated", + "type": "string", + "id": 15 + }, "messageType": { "rule": "repeated", "type": "DescriptorProto", @@ -4272,6 +4327,10 @@ "rule": "repeated", "type": "string", "id": 10 + }, + "visibility": { + "type": "SymbolVisibility", + "id": 11 } }, "nested": { @@ -4497,6 +4556,10 @@ "rule": "repeated", "type": "string", "id": 5 + }, + "visibility": { + "type": "SymbolVisibility", + "id": 6 } }, "nested": { @@ -4547,7 +4610,14 @@ "type": "ServiceOptions", "id": 3 } - } + }, + "reserved": [ + [ + 4, + 4 + ], + "stream" + ] }, "MethodDescriptorProto": { "edition": "proto2", @@ -4711,6 +4781,7 @@ 42, 42 ], + "php_generic_services", [ 38, 38 @@ -4846,7 +4917,8 @@ "type": "bool", "id": 10, "options": { - "default": false + "default": false, + "deprecated": true } }, "debugRedact": { @@ -4874,6 +4946,10 @@ "type": "FeatureSet", "id": 21 }, + "featureSupport": { + "type": "FeatureSupport", + "id": 22 + }, "uninterpretedOption": { "rule": "repeated", "type": "UninterpretedOption", @@ -4943,6 +5019,26 @@ "id": 2 } } + }, + "FeatureSupport": { + "fields": { + "editionIntroduced": { + "type": "Edition", + "id": 1 + }, + "editionDeprecated": { + "type": "Edition", + "id": 2 + }, + "deprecationWarning": { + "type": "string", + "id": 3 + }, + "editionRemoved": { + "type": "Edition", + "id": 4 + } + } } } }, @@ -5031,6 +5127,10 @@ "default": false } }, + "featureSupport": { + "type": "FieldOptions.FeatureSupport", + "id": 4 + }, "uninterpretedOption": { "rule": "repeated", "type": "UninterpretedOption", @@ -5173,6 +5273,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_2023", "edition_defaults.value": "EXPLICIT" } @@ -5183,6 +5284,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "OPEN" } @@ -5193,6 +5295,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "PACKED" } @@ -5203,6 +5306,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "VERIFY" } @@ -5213,7 +5317,8 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", - "edition_defaults.edition": "EDITION_PROTO2", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_LEGACY", "edition_defaults.value": "LENGTH_PREFIXED" } }, @@ -5223,27 +5328,38 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "ALLOW" } + }, + "enforceNamingStyle": { + "type": "EnforceNamingStyle", + "id": 7, + "options": { + "retention": "RETENTION_SOURCE", + "targets": "TARGET_TYPE_METHOD", + "feature_support.edition_introduced": "EDITION_2024", + "edition_defaults.edition": "EDITION_2024", + "edition_defaults.value": "STYLE2024" + } + }, + "defaultSymbolVisibility": { + "type": "VisibilityFeature.DefaultSymbolVisibility", + "id": 8, + "options": { + "retention": "RETENTION_SOURCE", + "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2024", + "edition_defaults.edition": "EDITION_2024", + "edition_defaults.value": "EXPORT_TOP_LEVEL" + } } }, "extensions": [ [ 1000, - 1000 - ], - [ - 1001, - 1001 - ], - [ - 1002, - 1002 - ], - [ - 9990, - 9990 + 9994 ], [ 9995, @@ -5288,7 +5404,13 @@ "UTF8_VALIDATION_UNKNOWN": 0, "VERIFY": 2, "NONE": 3 - } + }, + "reserved": [ + [ + 1, + 1 + ] + ] }, "MessageEncoding": { "values": { @@ -5303,6 +5425,33 @@ "ALLOW": 1, "LEGACY_BEST_EFFORT": 2 } + }, + "EnforceNamingStyle": { + "values": { + "ENFORCE_NAMING_STYLE_UNKNOWN": 0, + "STYLE2024": 1, + "STYLE_LEGACY": 2 + } + }, + "VisibilityFeature": { + "fields": {}, + "reserved": [ + [ + 1, + 536870911 + ] + ], + "nested": { + "DefaultSymbolVisibility": { + "values": { + "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN": 0, + "EXPORT_ALL": 1, + "EXPORT_TOP_LEVEL": 2, + "LOCAL_ALL": 3, + "STRICT": 4 + } + } + } } } }, @@ -5330,11 +5479,26 @@ "type": "Edition", "id": 3 }, - "features": { + "overridableFeatures": { "type": "FeatureSet", - "id": 2 + "id": 4 + }, + "fixedFeatures": { + "type": "FeatureSet", + "id": 5 } - } + }, + "reserved": [ + [ + 1, + 1 + ], + [ + 2, + 2 + ], + "features" + ] } } }, @@ -5347,6 +5511,12 @@ "id": 1 } }, + "extensions": [ + [ + 536000000, + 536000000 + ] + ], "nested": { "Location": { "fields": { @@ -5432,6 +5602,14 @@ } } }, + "SymbolVisibility": { + "edition": "proto2", + "values": { + "VISIBILITY_UNSET": 0, + "VISIBILITY_LOCAL": 1, + "VISIBILITY_EXPORT": 2 + } + }, "Timestamp": { "fields": { "seconds": { diff --git a/packages/google-ads-datamanager/samples/generated/v1/snippet_metadata_google.ads.datamanager.v1.json b/packages/google-ads-datamanager/samples/generated/v1/snippet_metadata_google.ads.datamanager.v1.json index 367a12de2569..64f8cb59a961 100644 --- a/packages/google-ads-datamanager/samples/generated/v1/snippet_metadata_google.ads.datamanager.v1.json +++ b/packages/google-ads-datamanager/samples/generated/v1/snippet_metadata_google.ads.datamanager.v1.json @@ -1,7 +1,7 @@ { "clientLibrary": { "name": "nodejs-datamanager", - "version": "0.2.0", + "version": "0.1.0", "language": "TYPESCRIPT", "apis": [ { diff --git a/packages/google-ads-datamanager/src/v1/index.ts b/packages/google-ads-datamanager/src/v1/index.ts index b7d57ada5bc3..1f8e5611a535 100644 --- a/packages/google-ads-datamanager/src/v1/index.ts +++ b/packages/google-ads-datamanager/src/v1/index.ts @@ -16,9 +16,9 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {IngestionServiceClient} from './ingestion_service_client'; -export {MarketingDataInsightsServiceClient} from './marketing_data_insights_service_client'; -export {PartnerLinkServiceClient} from './partner_link_service_client'; -export {UserListDirectLicenseServiceClient} from './user_list_direct_license_service_client'; -export {UserListGlobalLicenseServiceClient} from './user_list_global_license_service_client'; -export {UserListServiceClient} from './user_list_service_client'; +export { IngestionServiceClient } from './ingestion_service_client'; +export { MarketingDataInsightsServiceClient } from './marketing_data_insights_service_client'; +export { PartnerLinkServiceClient } from './partner_link_service_client'; +export { UserListDirectLicenseServiceClient } from './user_list_direct_license_service_client'; +export { UserListGlobalLicenseServiceClient } from './user_list_global_license_service_client'; +export { UserListServiceClient } from './user_list_service_client'; diff --git a/packages/google-ads-datamanager/src/v1/ingestion_service_client.ts b/packages/google-ads-datamanager/src/v1/ingestion_service_client.ts index 30ad66231cf6..68bb54b791d5 100644 --- a/packages/google-ads-datamanager/src/v1/ingestion_service_client.ts +++ b/packages/google-ads-datamanager/src/v1/ingestion_service_client.ts @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +49,7 @@ export class IngestionServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('datamanager'); @@ -57,9 +62,9 @@ export class IngestionServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - ingestionServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + ingestionServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of IngestionServiceClient. @@ -100,21 +105,42 @@ export class IngestionServiceClient { * const client = new IngestionServiceClient({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 IngestionServiceClient; - 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 = 'datamanager.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -139,7 +165,7 @@ export class IngestionServiceClient { 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; @@ -153,10 +179,7 @@ export class IngestionServiceClient { } // 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 { @@ -178,26 +201,30 @@ export class IngestionServiceClient { // Create useful helper objects for these. this.pathTemplates = { partnerLinkPathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link}' + 'accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link}', ), userListPathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userLists/{user_list}' + 'accountTypes/{account_type}/accounts/{account}/userLists/{user_list}', ), userListDirectLicensePathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userListDirectLicenses/{user_list_direct_license}' + 'accountTypes/{account_type}/accounts/{account}/userListDirectLicenses/{user_list_direct_license}', ), userListGlobalLicensePathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}' - ), - userListGlobalLicenseCustomerInfoPathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}/customerInfos/{license_customer_info}' + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}', ), + userListGlobalLicenseCustomerInfoPathTemplate: + new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}/customerInfos/{license_customer_info}', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ads.datamanager.v1.IngestionService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ads.datamanager.v1.IngestionService', + 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 @@ -228,36 +255,45 @@ export class IngestionServiceClient { // Put together the "service stub" for // google.ads.datamanager.v1.IngestionService. this.ingestionServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ads.datamanager.v1.IngestionService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ads.datamanager.v1.IngestionService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.ads.datamanager.v1.IngestionService, - 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 ingestionServiceStubMethods = - ['ingestAudienceMembers', 'removeAudienceMembers', 'ingestEvents', 'retrieveRequestStatus']; + const ingestionServiceStubMethods = [ + 'ingestAudienceMembers', + 'removeAudienceMembers', + 'ingestEvents', + 'retrieveRequestStatus', + ]; for (const methodName of ingestionServiceStubMethods) { const callPromise = this.ingestionServiceStub.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 = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -272,8 +308,14 @@ export class IngestionServiceClient { * @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 'datamanager.googleapis.com'; } @@ -284,8 +326,14 @@ export class IngestionServiceClient { * @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 'datamanager.googleapis.com'; } @@ -316,9 +364,7 @@ export class IngestionServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/datamanager' - ]; + return ['https://www.googleapis.com/auth/datamanager']; } getProjectId(): Promise; @@ -327,8 +373,9 @@ export class IngestionServiceClient { * 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; @@ -339,429 +386,614 @@ export class IngestionServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Uploads a list of - * {@link protos.google.ads.datamanager.v1.AudienceMember|AudienceMember} resources to the - * provided {@link protos.google.ads.datamanager.v1.Destination|Destination}. - * - * @param {Object} request - * The request object that will be sent. - * @param {number[]} request.destinations - * Required. The list of destinations to send the audience members to. - * @param {number[]} request.audienceMembers - * Required. The list of users to send to the specified destinations. At most - * 10000 {@link protos.google.ads.datamanager.v1.AudienceMember|AudienceMember} resources - * can be sent in a single request. - * @param {google.ads.datamanager.v1.Consent} [request.consent] - * Optional. Request-level consent to apply to all users in the request. - * User-level consent overrides request-level consent, and can be specified in - * each {@link protos.google.ads.datamanager.v1.AudienceMember|AudienceMember}. - * @param {boolean} [request.validateOnly] - * Optional. For testing purposes. If `true`, the request is validated but not - * executed. Only errors are returned, not results. - * @param {google.ads.datamanager.v1.Encoding} [request.encoding] - * Optional. Required for {@link protos.google.ads.datamanager.v1.UserData|UserData} - * uploads. The encoding type of the user identifiers. For hashed user - * identifiers, this is the encoding type of the hashed string. For encrypted - * hashed user identifiers, this is the encoding type of the outer encrypted - * string, but not necessarily the inner hashed string, meaning the inner - * hashed string could be encoded in a different way than the outer encrypted - * string. For non `UserData` uploads, this field is ignored. - * @param {google.ads.datamanager.v1.EncryptionInfo} [request.encryptionInfo] - * Optional. Encryption information for - * {@link protos.google.ads.datamanager.v1.UserData|UserData} uploads. If not set, it's - * assumed that uploaded identifying information is hashed but not encrypted. - * For non `UserData` uploads, this field is ignored. - * @param {google.ads.datamanager.v1.TermsOfService} [request.termsOfService] - * Optional. The terms of service that the user has accepted/rejected. - * @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.ads.datamanager.v1.IngestAudienceMembersResponse|IngestAudienceMembersResponse}. - * 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/ingestion_service.ingest_audience_members.js - * region_tag:datamanager_v1_generated_IngestionService_IngestAudienceMembers_async - */ + /** + * Uploads a list of + * {@link protos.google.ads.datamanager.v1.AudienceMember|AudienceMember} resources to the + * provided {@link protos.google.ads.datamanager.v1.Destination|Destination}. + * + * @param {Object} request + * The request object that will be sent. + * @param {number[]} request.destinations + * Required. The list of destinations to send the audience members to. + * @param {number[]} request.audienceMembers + * Required. The list of users to send to the specified destinations. At most + * 10000 {@link protos.google.ads.datamanager.v1.AudienceMember|AudienceMember} resources + * can be sent in a single request. + * @param {google.ads.datamanager.v1.Consent} [request.consent] + * Optional. Request-level consent to apply to all users in the request. + * User-level consent overrides request-level consent, and can be specified in + * each {@link protos.google.ads.datamanager.v1.AudienceMember|AudienceMember}. + * @param {boolean} [request.validateOnly] + * Optional. For testing purposes. If `true`, the request is validated but not + * executed. Only errors are returned, not results. + * @param {google.ads.datamanager.v1.Encoding} [request.encoding] + * Optional. Required for {@link protos.google.ads.datamanager.v1.UserData|UserData} + * uploads. The encoding type of the user identifiers. For hashed user + * identifiers, this is the encoding type of the hashed string. For encrypted + * hashed user identifiers, this is the encoding type of the outer encrypted + * string, but not necessarily the inner hashed string, meaning the inner + * hashed string could be encoded in a different way than the outer encrypted + * string. For non `UserData` uploads, this field is ignored. + * @param {google.ads.datamanager.v1.EncryptionInfo} [request.encryptionInfo] + * Optional. Encryption information for + * {@link protos.google.ads.datamanager.v1.UserData|UserData} uploads. If not set, it's + * assumed that uploaded identifying information is hashed but not encrypted. + * For non `UserData` uploads, this field is ignored. + * @param {google.ads.datamanager.v1.TermsOfService} [request.termsOfService] + * Optional. The terms of service that the user has accepted/rejected. + * @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.ads.datamanager.v1.IngestAudienceMembersResponse|IngestAudienceMembersResponse}. + * 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/ingestion_service.ingest_audience_members.js + * region_tag:datamanager_v1_generated_IngestionService_IngestAudienceMembers_async + */ ingestAudienceMembers( - request?: protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest, - options?: CallOptions): - Promise<[ - protos.google.ads.datamanager.v1.IIngestAudienceMembersResponse, - protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest|undefined, {}|undefined - ]>; + request?: protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ads.datamanager.v1.IIngestAudienceMembersResponse, + ( + | protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest + | undefined + ), + {} | undefined, + ] + >; ingestAudienceMembers( - request: protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest, - options: CallOptions, - callback: Callback< - protos.google.ads.datamanager.v1.IIngestAudienceMembersResponse, - protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IIngestAudienceMembersResponse, + | protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest + | null + | undefined, + {} | null | undefined + >, + ): void; ingestAudienceMembers( - request: protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest, - callback: Callback< - protos.google.ads.datamanager.v1.IIngestAudienceMembersResponse, - protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IIngestAudienceMembersResponse, + | protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest + | null + | undefined, + {} | null | undefined + >, + ): void; ingestAudienceMembers( - request?: protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ads.datamanager.v1.IIngestAudienceMembersResponse, - protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ads.datamanager.v1.IIngestAudienceMembersResponse, - protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ads.datamanager.v1.IIngestAudienceMembersResponse, - protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest|undefined, {}|undefined - ]>|void { + | protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ads.datamanager.v1.IIngestAudienceMembersResponse, + | protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ads.datamanager.v1.IIngestAudienceMembersResponse, + ( + | protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest + | 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 || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('ingestAudienceMembers request %j', request); - const wrappedCallback: Callback< - protos.google.ads.datamanager.v1.IIngestAudienceMembersResponse, - protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ads.datamanager.v1.IIngestAudienceMembersResponse, + | protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('ingestAudienceMembers response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.ingestAudienceMembers(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ads.datamanager.v1.IIngestAudienceMembersResponse, - protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest|undefined, - {}|undefined - ]) => { - this._log.info('ingestAudienceMembers response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .ingestAudienceMembers(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IIngestAudienceMembersResponse, + ( + | protos.google.ads.datamanager.v1.IIngestAudienceMembersRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('ingestAudienceMembers response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Removes a list of - * {@link protos.google.ads.datamanager.v1.AudienceMember|AudienceMember} resources from - * the provided {@link protos.google.ads.datamanager.v1.Destination|Destination}. - * - * @param {Object} request - * The request object that will be sent. - * @param {number[]} request.destinations - * Required. The list of destinations to remove the users from. - * @param {number[]} request.audienceMembers - * Required. The list of users to remove. - * @param {boolean} [request.validateOnly] - * Optional. For testing purposes. If `true`, the request is validated but not - * executed. Only errors are returned, not results. - * @param {google.ads.datamanager.v1.Encoding} [request.encoding] - * Optional. Required for {@link protos.google.ads.datamanager.v1.UserData|UserData} - * uploads. The encoding type of the user identifiers. Applies to only the - * outer encoding for encrypted user identifiers. For non `UserData` uploads, - * this field is ignored. - * @param {google.ads.datamanager.v1.EncryptionInfo} [request.encryptionInfo] - * Optional. Encryption information for - * {@link protos.google.ads.datamanager.v1.UserData|UserData} uploads. If not set, it's - * assumed that uploaded identifying information is hashed but not encrypted. - * For non `UserData` uploads, this field is ignored. - * @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.ads.datamanager.v1.RemoveAudienceMembersResponse|RemoveAudienceMembersResponse}. - * 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/ingestion_service.remove_audience_members.js - * region_tag:datamanager_v1_generated_IngestionService_RemoveAudienceMembers_async - */ + /** + * Removes a list of + * {@link protos.google.ads.datamanager.v1.AudienceMember|AudienceMember} resources from + * the provided {@link protos.google.ads.datamanager.v1.Destination|Destination}. + * + * @param {Object} request + * The request object that will be sent. + * @param {number[]} request.destinations + * Required. The list of destinations to remove the users from. + * @param {number[]} request.audienceMembers + * Required. The list of users to remove. + * @param {boolean} [request.validateOnly] + * Optional. For testing purposes. If `true`, the request is validated but not + * executed. Only errors are returned, not results. + * @param {google.ads.datamanager.v1.Encoding} [request.encoding] + * Optional. Required for {@link protos.google.ads.datamanager.v1.UserData|UserData} + * uploads. The encoding type of the user identifiers. Applies to only the + * outer encoding for encrypted user identifiers. For non `UserData` uploads, + * this field is ignored. + * @param {google.ads.datamanager.v1.EncryptionInfo} [request.encryptionInfo] + * Optional. Encryption information for + * {@link protos.google.ads.datamanager.v1.UserData|UserData} uploads. If not set, it's + * assumed that uploaded identifying information is hashed but not encrypted. + * For non `UserData` uploads, this field is ignored. + * @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.ads.datamanager.v1.RemoveAudienceMembersResponse|RemoveAudienceMembersResponse}. + * 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/ingestion_service.remove_audience_members.js + * region_tag:datamanager_v1_generated_IngestionService_RemoveAudienceMembers_async + */ removeAudienceMembers( - request?: protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest, - options?: CallOptions): - Promise<[ - protos.google.ads.datamanager.v1.IRemoveAudienceMembersResponse, - protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest|undefined, {}|undefined - ]>; + request?: protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ads.datamanager.v1.IRemoveAudienceMembersResponse, + ( + | protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest + | undefined + ), + {} | undefined, + ] + >; removeAudienceMembers( - request: protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest, - options: CallOptions, - callback: Callback< - protos.google.ads.datamanager.v1.IRemoveAudienceMembersResponse, - protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IRemoveAudienceMembersResponse, + | protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest + | null + | undefined, + {} | null | undefined + >, + ): void; removeAudienceMembers( - request: protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest, - callback: Callback< - protos.google.ads.datamanager.v1.IRemoveAudienceMembersResponse, - protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IRemoveAudienceMembersResponse, + | protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest + | null + | undefined, + {} | null | undefined + >, + ): void; removeAudienceMembers( - request?: protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ads.datamanager.v1.IRemoveAudienceMembersResponse, - protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ads.datamanager.v1.IRemoveAudienceMembersResponse, - protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ads.datamanager.v1.IRemoveAudienceMembersResponse, - protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest|undefined, {}|undefined - ]>|void { + | protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ads.datamanager.v1.IRemoveAudienceMembersResponse, + | protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ads.datamanager.v1.IRemoveAudienceMembersResponse, + ( + | protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest + | 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 || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('removeAudienceMembers request %j', request); - const wrappedCallback: Callback< - protos.google.ads.datamanager.v1.IRemoveAudienceMembersResponse, - protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ads.datamanager.v1.IRemoveAudienceMembersResponse, + | protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('removeAudienceMembers response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.removeAudienceMembers(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ads.datamanager.v1.IRemoveAudienceMembersResponse, - protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest|undefined, - {}|undefined - ]) => { - this._log.info('removeAudienceMembers response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .removeAudienceMembers(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IRemoveAudienceMembersResponse, + ( + | protos.google.ads.datamanager.v1.IRemoveAudienceMembersRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('removeAudienceMembers response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Uploads a list of - * {@link protos.google.ads.datamanager.v1.Event|Event} resources from - * the provided {@link protos.google.ads.datamanager.v1.Destination|Destination}. - * - * @param {Object} request - * The request object that will be sent. - * @param {number[]} request.destinations - * Required. The list of destinations to send the events to. - * @param {number[]} request.events - * Required. The list of events to send to the specified destinations. At most - * 2000 {@link protos.google.ads.datamanager.v1.Event|Event} resources - * can be sent in a single request. - * @param {google.ads.datamanager.v1.Consent} [request.consent] - * Optional. Request-level consent to apply to all users in the request. - * User-level consent overrides request-level consent, and can be specified in - * each {@link protos.google.ads.datamanager.v1.Event|Event}. - * @param {boolean} [request.validateOnly] - * Optional. For testing purposes. If `true`, the request is validated but not - * executed. Only errors are returned, not results. - * @param {google.ads.datamanager.v1.Encoding} [request.encoding] - * Optional. Required for {@link protos.google.ads.datamanager.v1.UserData|UserData} - * uploads. The encoding type of the user identifiers. For hashed user - * identifiers, this is the encoding type of the hashed string. For encrypted - * hashed user identifiers, this is the encoding type of the outer encrypted - * string, but not necessarily the inner hashed string, meaning the inner - * hashed string could be encoded in a different way than the outer encrypted - * string. For non `UserData` uploads, this field is ignored. - * @param {google.ads.datamanager.v1.EncryptionInfo} [request.encryptionInfo] - * Optional. Encryption information for - * {@link protos.google.ads.datamanager.v1.UserData|UserData} uploads. If not set, it's - * assumed that uploaded identifying information is hashed but not encrypted. - * For non `UserData` uploads, this field is ignored. - * @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.ads.datamanager.v1.IngestEventsResponse|IngestEventsResponse}. - * 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/ingestion_service.ingest_events.js - * region_tag:datamanager_v1_generated_IngestionService_IngestEvents_async - */ + /** + * Uploads a list of + * {@link protos.google.ads.datamanager.v1.Event|Event} resources from + * the provided {@link protos.google.ads.datamanager.v1.Destination|Destination}. + * + * @param {Object} request + * The request object that will be sent. + * @param {number[]} request.destinations + * Required. The list of destinations to send the events to. + * @param {number[]} request.events + * Required. The list of events to send to the specified destinations. At most + * 2000 {@link protos.google.ads.datamanager.v1.Event|Event} resources + * can be sent in a single request. + * @param {google.ads.datamanager.v1.Consent} [request.consent] + * Optional. Request-level consent to apply to all users in the request. + * User-level consent overrides request-level consent, and can be specified in + * each {@link protos.google.ads.datamanager.v1.Event|Event}. + * @param {boolean} [request.validateOnly] + * Optional. For testing purposes. If `true`, the request is validated but not + * executed. Only errors are returned, not results. + * @param {google.ads.datamanager.v1.Encoding} [request.encoding] + * Optional. Required for {@link protos.google.ads.datamanager.v1.UserData|UserData} + * uploads. The encoding type of the user identifiers. For hashed user + * identifiers, this is the encoding type of the hashed string. For encrypted + * hashed user identifiers, this is the encoding type of the outer encrypted + * string, but not necessarily the inner hashed string, meaning the inner + * hashed string could be encoded in a different way than the outer encrypted + * string. For non `UserData` uploads, this field is ignored. + * @param {google.ads.datamanager.v1.EncryptionInfo} [request.encryptionInfo] + * Optional. Encryption information for + * {@link protos.google.ads.datamanager.v1.UserData|UserData} uploads. If not set, it's + * assumed that uploaded identifying information is hashed but not encrypted. + * For non `UserData` uploads, this field is ignored. + * @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.ads.datamanager.v1.IngestEventsResponse|IngestEventsResponse}. + * 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/ingestion_service.ingest_events.js + * region_tag:datamanager_v1_generated_IngestionService_IngestEvents_async + */ ingestEvents( - request?: protos.google.ads.datamanager.v1.IIngestEventsRequest, - options?: CallOptions): - Promise<[ - protos.google.ads.datamanager.v1.IIngestEventsResponse, - protos.google.ads.datamanager.v1.IIngestEventsRequest|undefined, {}|undefined - ]>; + request?: protos.google.ads.datamanager.v1.IIngestEventsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ads.datamanager.v1.IIngestEventsResponse, + protos.google.ads.datamanager.v1.IIngestEventsRequest | undefined, + {} | undefined, + ] + >; ingestEvents( - request: protos.google.ads.datamanager.v1.IIngestEventsRequest, - options: CallOptions, - callback: Callback< - protos.google.ads.datamanager.v1.IIngestEventsResponse, - protos.google.ads.datamanager.v1.IIngestEventsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IIngestEventsRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IIngestEventsResponse, + protos.google.ads.datamanager.v1.IIngestEventsRequest | null | undefined, + {} | null | undefined + >, + ): void; ingestEvents( - request: protos.google.ads.datamanager.v1.IIngestEventsRequest, - callback: Callback< - protos.google.ads.datamanager.v1.IIngestEventsResponse, - protos.google.ads.datamanager.v1.IIngestEventsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IIngestEventsRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IIngestEventsResponse, + protos.google.ads.datamanager.v1.IIngestEventsRequest | null | undefined, + {} | null | undefined + >, + ): void; ingestEvents( - request?: protos.google.ads.datamanager.v1.IIngestEventsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ads.datamanager.v1.IIngestEventsResponse, - protos.google.ads.datamanager.v1.IIngestEventsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ads.datamanager.v1.IIngestEventsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ads.datamanager.v1.IIngestEventsResponse, - protos.google.ads.datamanager.v1.IIngestEventsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ads.datamanager.v1.IIngestEventsResponse, - protos.google.ads.datamanager.v1.IIngestEventsRequest|undefined, {}|undefined - ]>|void { + | protos.google.ads.datamanager.v1.IIngestEventsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ads.datamanager.v1.IIngestEventsResponse, + protos.google.ads.datamanager.v1.IIngestEventsRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ads.datamanager.v1.IIngestEventsResponse, + protos.google.ads.datamanager.v1.IIngestEventsRequest | 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 || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('ingestEvents request %j', request); - const wrappedCallback: Callback< - protos.google.ads.datamanager.v1.IIngestEventsResponse, - protos.google.ads.datamanager.v1.IIngestEventsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ads.datamanager.v1.IIngestEventsResponse, + | protos.google.ads.datamanager.v1.IIngestEventsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('ingestEvents response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.ingestEvents(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ads.datamanager.v1.IIngestEventsResponse, - protos.google.ads.datamanager.v1.IIngestEventsRequest|undefined, - {}|undefined - ]) => { - this._log.info('ingestEvents response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .ingestEvents(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IIngestEventsResponse, + protos.google.ads.datamanager.v1.IIngestEventsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('ingestEvents response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets the status of a request given request id. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.requestId - * Required. Required. The request ID of the Data Manager API request. - * @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.ads.datamanager.v1.RetrieveRequestStatusResponse|RetrieveRequestStatusResponse}. - * 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/ingestion_service.retrieve_request_status.js - * region_tag:datamanager_v1_generated_IngestionService_RetrieveRequestStatus_async - */ + /** + * Gets the status of a request given request id. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.requestId + * Required. Required. The request ID of the Data Manager API request. + * @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.ads.datamanager.v1.RetrieveRequestStatusResponse|RetrieveRequestStatusResponse}. + * 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/ingestion_service.retrieve_request_status.js + * region_tag:datamanager_v1_generated_IngestionService_RetrieveRequestStatus_async + */ retrieveRequestStatus( - request?: protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest, - options?: CallOptions): - Promise<[ - protos.google.ads.datamanager.v1.IRetrieveRequestStatusResponse, - protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest|undefined, {}|undefined - ]>; + request?: protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ads.datamanager.v1.IRetrieveRequestStatusResponse, + ( + | protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest + | undefined + ), + {} | undefined, + ] + >; retrieveRequestStatus( - request: protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest, - options: CallOptions, - callback: Callback< - protos.google.ads.datamanager.v1.IRetrieveRequestStatusResponse, - protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IRetrieveRequestStatusResponse, + | protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest + | null + | undefined, + {} | null | undefined + >, + ): void; retrieveRequestStatus( - request: protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest, - callback: Callback< - protos.google.ads.datamanager.v1.IRetrieveRequestStatusResponse, - protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IRetrieveRequestStatusResponse, + | protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest + | null + | undefined, + {} | null | undefined + >, + ): void; retrieveRequestStatus( - request?: protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ads.datamanager.v1.IRetrieveRequestStatusResponse, - protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ads.datamanager.v1.IRetrieveRequestStatusResponse, - protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ads.datamanager.v1.IRetrieveRequestStatusResponse, - protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest|undefined, {}|undefined - ]>|void { + | protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ads.datamanager.v1.IRetrieveRequestStatusResponse, + | protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ads.datamanager.v1.IRetrieveRequestStatusResponse, + ( + | protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest + | 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 || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('retrieveRequestStatus request %j', request); - const wrappedCallback: Callback< - protos.google.ads.datamanager.v1.IRetrieveRequestStatusResponse, - protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ads.datamanager.v1.IRetrieveRequestStatusResponse, + | protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('retrieveRequestStatus response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.retrieveRequestStatus(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ads.datamanager.v1.IRetrieveRequestStatusResponse, - protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest|undefined, - {}|undefined - ]) => { - this._log.info('retrieveRequestStatus response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .retrieveRequestStatus(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IRetrieveRequestStatusResponse, + ( + | protos.google.ads.datamanager.v1.IRetrieveRequestStatusRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('retrieveRequestStatus response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -779,7 +1011,7 @@ export class IngestionServiceClient { * @param {string} partner_link * @returns {string} Resource name string. */ - partnerLinkPath(accountType:string,account:string,partnerLink:string) { + partnerLinkPath(accountType: string, account: string, partnerLink: string) { return this.pathTemplates.partnerLinkPathTemplate.render({ account_type: accountType, account: account, @@ -795,7 +1027,8 @@ export class IngestionServiceClient { * @returns {string} A string representing the account_type. */ matchAccountTypeFromPartnerLinkName(partnerLinkName: string) { - return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account_type; + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName) + .account_type; } /** @@ -806,7 +1039,8 @@ export class IngestionServiceClient { * @returns {string} A string representing the account. */ matchAccountFromPartnerLinkName(partnerLinkName: string) { - return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account; + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName) + .account; } /** @@ -817,7 +1051,8 @@ export class IngestionServiceClient { * @returns {string} A string representing the partner_link. */ matchPartnerLinkFromPartnerLinkName(partnerLinkName: string) { - return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).partner_link; + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName) + .partner_link; } /** @@ -828,7 +1063,7 @@ export class IngestionServiceClient { * @param {string} user_list * @returns {string} Resource name string. */ - userListPath(accountType:string,account:string,userList:string) { + userListPath(accountType: string, account: string, userList: string) { return this.pathTemplates.userListPathTemplate.render({ account_type: accountType, account: account, @@ -844,7 +1079,8 @@ export class IngestionServiceClient { * @returns {string} A string representing the account_type. */ matchAccountTypeFromUserListName(userListName: string) { - return this.pathTemplates.userListPathTemplate.match(userListName).account_type; + return this.pathTemplates.userListPathTemplate.match(userListName) + .account_type; } /** @@ -866,7 +1102,8 @@ export class IngestionServiceClient { * @returns {string} A string representing the user_list. */ matchUserListFromUserListName(userListName: string) { - return this.pathTemplates.userListPathTemplate.match(userListName).user_list; + return this.pathTemplates.userListPathTemplate.match(userListName) + .user_list; } /** @@ -877,7 +1114,11 @@ export class IngestionServiceClient { * @param {string} user_list_direct_license * @returns {string} Resource name string. */ - userListDirectLicensePath(accountType:string,account:string,userListDirectLicense:string) { + userListDirectLicensePath( + accountType: string, + account: string, + userListDirectLicense: string, + ) { return this.pathTemplates.userListDirectLicensePathTemplate.render({ account_type: accountType, account: account, @@ -892,8 +1133,12 @@ export class IngestionServiceClient { * A fully-qualified path representing UserListDirectLicense resource. * @returns {string} A string representing the account_type. */ - matchAccountTypeFromUserListDirectLicenseName(userListDirectLicenseName: string) { - return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account_type; + matchAccountTypeFromUserListDirectLicenseName( + userListDirectLicenseName: string, + ) { + return this.pathTemplates.userListDirectLicensePathTemplate.match( + userListDirectLicenseName, + ).account_type; } /** @@ -904,7 +1149,9 @@ export class IngestionServiceClient { * @returns {string} A string representing the account. */ matchAccountFromUserListDirectLicenseName(userListDirectLicenseName: string) { - return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account; + return this.pathTemplates.userListDirectLicensePathTemplate.match( + userListDirectLicenseName, + ).account; } /** @@ -914,8 +1161,12 @@ export class IngestionServiceClient { * A fully-qualified path representing UserListDirectLicense resource. * @returns {string} A string representing the user_list_direct_license. */ - matchUserListDirectLicenseFromUserListDirectLicenseName(userListDirectLicenseName: string) { - return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).user_list_direct_license; + matchUserListDirectLicenseFromUserListDirectLicenseName( + userListDirectLicenseName: string, + ) { + return this.pathTemplates.userListDirectLicensePathTemplate.match( + userListDirectLicenseName, + ).user_list_direct_license; } /** @@ -926,7 +1177,11 @@ export class IngestionServiceClient { * @param {string} user_list_global_license * @returns {string} Resource name string. */ - userListGlobalLicensePath(accountType:string,account:string,userListGlobalLicense:string) { + userListGlobalLicensePath( + accountType: string, + account: string, + userListGlobalLicense: string, + ) { return this.pathTemplates.userListGlobalLicensePathTemplate.render({ account_type: accountType, account: account, @@ -941,8 +1196,12 @@ export class IngestionServiceClient { * A fully-qualified path representing UserListGlobalLicense resource. * @returns {string} A string representing the account_type. */ - matchAccountTypeFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { - return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account_type; + matchAccountTypeFromUserListGlobalLicenseName( + userListGlobalLicenseName: string, + ) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match( + userListGlobalLicenseName, + ).account_type; } /** @@ -953,7 +1212,9 @@ export class IngestionServiceClient { * @returns {string} A string representing the account. */ matchAccountFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { - return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account; + return this.pathTemplates.userListGlobalLicensePathTemplate.match( + userListGlobalLicenseName, + ).account; } /** @@ -963,8 +1224,12 @@ export class IngestionServiceClient { * A fully-qualified path representing UserListGlobalLicense resource. * @returns {string} A string representing the user_list_global_license. */ - matchUserListGlobalLicenseFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { - return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).user_list_global_license; + matchUserListGlobalLicenseFromUserListGlobalLicenseName( + userListGlobalLicenseName: string, + ) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match( + userListGlobalLicenseName, + ).user_list_global_license; } /** @@ -976,13 +1241,20 @@ export class IngestionServiceClient { * @param {string} license_customer_info * @returns {string} Resource name string. */ - userListGlobalLicenseCustomerInfoPath(accountType:string,account:string,userListGlobalLicense:string,licenseCustomerInfo:string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render({ - account_type: accountType, - account: account, - user_list_global_license: userListGlobalLicense, - license_customer_info: licenseCustomerInfo, - }); + userListGlobalLicenseCustomerInfoPath( + accountType: string, + account: string, + userListGlobalLicense: string, + licenseCustomerInfo: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render( + { + account_type: accountType, + account: account, + user_list_global_license: userListGlobalLicense, + license_customer_info: licenseCustomerInfo, + }, + ); } /** @@ -992,8 +1264,12 @@ export class IngestionServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the account_type. */ - matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account_type; + matchAccountTypeFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).account_type; } /** @@ -1003,8 +1279,12 @@ export class IngestionServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the account. */ - matchAccountFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account; + matchAccountFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).account; } /** @@ -1014,8 +1294,12 @@ export class IngestionServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the user_list_global_license. */ - matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).user_list_global_license; + matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).user_list_global_license; } /** @@ -1025,8 +1309,12 @@ export class IngestionServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the license_customer_info. */ - matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).license_customer_info; + matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).license_customer_info; } /** @@ -1037,7 +1325,7 @@ export class IngestionServiceClient { */ close(): Promise { if (this.ingestionServiceStub && !this._terminated) { - return this.ingestionServiceStub.then(stub => { + return this.ingestionServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1045,4 +1333,4 @@ export class IngestionServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ads-datamanager/src/v1/marketing_data_insights_service_client.ts b/packages/google-ads-datamanager/src/v1/marketing_data_insights_service_client.ts index e2953da9aa47..d0035553ddbc 100644 --- a/packages/google-ads-datamanager/src/v1/marketing_data_insights_service_client.ts +++ b/packages/google-ads-datamanager/src/v1/marketing_data_insights_service_client.ts @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -46,7 +51,7 @@ export class MarketingDataInsightsServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('datamanager'); @@ -59,9 +64,9 @@ export class MarketingDataInsightsServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - marketingDataInsightsServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + marketingDataInsightsServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of MarketingDataInsightsServiceClient. @@ -102,21 +107,43 @@ export class MarketingDataInsightsServiceClient { * const client = new MarketingDataInsightsServiceClient({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 MarketingDataInsightsServiceClient; - 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 staticMembers = this + .constructor as typeof MarketingDataInsightsServiceClient; + 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 = 'datamanager.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -141,7 +168,7 @@ export class MarketingDataInsightsServiceClient { 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; @@ -155,10 +182,7 @@ export class MarketingDataInsightsServiceClient { } // 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 { @@ -180,26 +204,30 @@ export class MarketingDataInsightsServiceClient { // Create useful helper objects for these. this.pathTemplates = { partnerLinkPathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link}' + 'accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link}', ), userListPathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userLists/{user_list}' + 'accountTypes/{account_type}/accounts/{account}/userLists/{user_list}', ), userListDirectLicensePathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userListDirectLicenses/{user_list_direct_license}' + 'accountTypes/{account_type}/accounts/{account}/userListDirectLicenses/{user_list_direct_license}', ), userListGlobalLicensePathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}' - ), - userListGlobalLicenseCustomerInfoPathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}/customerInfos/{license_customer_info}' + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}', ), + userListGlobalLicenseCustomerInfoPathTemplate: + new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}/customerInfos/{license_customer_info}', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ads.datamanager.v1.MarketingDataInsightsService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ads.datamanager.v1.MarketingDataInsightsService', + 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 @@ -230,36 +258,41 @@ export class MarketingDataInsightsServiceClient { // Put together the "service stub" for // google.ads.datamanager.v1.MarketingDataInsightsService. this.marketingDataInsightsServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ads.datamanager.v1.MarketingDataInsightsService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ads.datamanager.v1.MarketingDataInsightsService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ads.datamanager.v1.MarketingDataInsightsService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ads.datamanager.v1 + .MarketingDataInsightsService, + 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 marketingDataInsightsServiceStubMethods = - ['retrieveInsights']; + const marketingDataInsightsServiceStubMethods = ['retrieveInsights']; for (const methodName of marketingDataInsightsServiceStubMethods) { const callPromise = this.marketingDataInsightsServiceStub.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 = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -274,8 +307,14 @@ export class MarketingDataInsightsServiceClient { * @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 'datamanager.googleapis.com'; } @@ -286,8 +325,14 @@ export class MarketingDataInsightsServiceClient { * @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 'datamanager.googleapis.com'; } @@ -318,9 +363,7 @@ export class MarketingDataInsightsServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/datamanager' - ]; + return ['https://www.googleapis.com/auth/datamanager']; } getProjectId(): Promise; @@ -329,8 +372,9 @@ export class MarketingDataInsightsServiceClient { * 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; @@ -341,116 +385,156 @@ export class MarketingDataInsightsServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Retrieves marketing data insights for a given user list. - * - * This feature is only available to data partners. - * - * Authorization Headers: - * - * This method supports the following optional headers to define how the API - * authorizes access for the request: - * - * * `login-account`: (Optional) The resource name of the account where the - * Google Account of the credentials is a user. If not set, defaults to the - * account of the request. Format: - * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` - * * `linked-account`: (Optional) The resource name of the account with an - * established product link to the `login-account`. Format: - * `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent account that owns the user list. - * Format: `accountTypes/{account_type}/accounts/{account}` - * @param {google.ads.datamanager.v1.Baseline} request.baseline - * Required. Baseline for the insights requested. - * @param {string} request.userListId - * Required. The user list ID for which insights are requested. - * @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.ads.datamanager.v1.RetrieveInsightsResponse|RetrieveInsightsResponse}. - * 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/marketing_data_insights_service.retrieve_insights.js - * region_tag:datamanager_v1_generated_MarketingDataInsightsService_RetrieveInsights_async - */ + /** + * Retrieves marketing data insights for a given user list. + * + * This feature is only available to data partners. + * + * Authorization Headers: + * + * This method supports the following optional headers to define how the API + * authorizes access for the request: + * + * * `login-account`: (Optional) The resource name of the account where the + * Google Account of the credentials is a user. If not set, defaults to the + * account of the request. Format: + * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + * * `linked-account`: (Optional) The resource name of the account with an + * established product link to the `login-account`. Format: + * `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent account that owns the user list. + * Format: `accountTypes/{account_type}/accounts/{account}` + * @param {google.ads.datamanager.v1.Baseline} request.baseline + * Required. Baseline for the insights requested. + * @param {string} request.userListId + * Required. The user list ID for which insights are requested. + * @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.ads.datamanager.v1.RetrieveInsightsResponse|RetrieveInsightsResponse}. + * 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/marketing_data_insights_service.retrieve_insights.js + * region_tag:datamanager_v1_generated_MarketingDataInsightsService_RetrieveInsights_async + */ retrieveInsights( - request?: protos.google.ads.datamanager.v1.IRetrieveInsightsRequest, - options?: CallOptions): - Promise<[ - protos.google.ads.datamanager.v1.IRetrieveInsightsResponse, - protos.google.ads.datamanager.v1.IRetrieveInsightsRequest|undefined, {}|undefined - ]>; + request?: protos.google.ads.datamanager.v1.IRetrieveInsightsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ads.datamanager.v1.IRetrieveInsightsResponse, + protos.google.ads.datamanager.v1.IRetrieveInsightsRequest | undefined, + {} | undefined, + ] + >; retrieveInsights( - request: protos.google.ads.datamanager.v1.IRetrieveInsightsRequest, - options: CallOptions, - callback: Callback< - protos.google.ads.datamanager.v1.IRetrieveInsightsResponse, - protos.google.ads.datamanager.v1.IRetrieveInsightsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IRetrieveInsightsRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IRetrieveInsightsResponse, + | protos.google.ads.datamanager.v1.IRetrieveInsightsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; retrieveInsights( - request: protos.google.ads.datamanager.v1.IRetrieveInsightsRequest, - callback: Callback< - protos.google.ads.datamanager.v1.IRetrieveInsightsResponse, - protos.google.ads.datamanager.v1.IRetrieveInsightsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IRetrieveInsightsRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IRetrieveInsightsResponse, + | protos.google.ads.datamanager.v1.IRetrieveInsightsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; retrieveInsights( - request?: protos.google.ads.datamanager.v1.IRetrieveInsightsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ads.datamanager.v1.IRetrieveInsightsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ads.datamanager.v1.IRetrieveInsightsResponse, - protos.google.ads.datamanager.v1.IRetrieveInsightsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ads.datamanager.v1.IRetrieveInsightsResponse, - protos.google.ads.datamanager.v1.IRetrieveInsightsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ads.datamanager.v1.IRetrieveInsightsResponse, - protos.google.ads.datamanager.v1.IRetrieveInsightsRequest|undefined, {}|undefined - ]>|void { + | protos.google.ads.datamanager.v1.IRetrieveInsightsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ads.datamanager.v1.IRetrieveInsightsResponse, + | protos.google.ads.datamanager.v1.IRetrieveInsightsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ads.datamanager.v1.IRetrieveInsightsResponse, + protos.google.ads.datamanager.v1.IRetrieveInsightsRequest | 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('retrieveInsights request %j', request); - const wrappedCallback: Callback< - protos.google.ads.datamanager.v1.IRetrieveInsightsResponse, - protos.google.ads.datamanager.v1.IRetrieveInsightsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ads.datamanager.v1.IRetrieveInsightsResponse, + | protos.google.ads.datamanager.v1.IRetrieveInsightsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('retrieveInsights response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.retrieveInsights(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ads.datamanager.v1.IRetrieveInsightsResponse, - protos.google.ads.datamanager.v1.IRetrieveInsightsRequest|undefined, - {}|undefined - ]) => { - this._log.info('retrieveInsights response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .retrieveInsights(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IRetrieveInsightsResponse, + protos.google.ads.datamanager.v1.IRetrieveInsightsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('retrieveInsights response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -468,7 +552,7 @@ export class MarketingDataInsightsServiceClient { * @param {string} partner_link * @returns {string} Resource name string. */ - partnerLinkPath(accountType:string,account:string,partnerLink:string) { + partnerLinkPath(accountType: string, account: string, partnerLink: string) { return this.pathTemplates.partnerLinkPathTemplate.render({ account_type: accountType, account: account, @@ -484,7 +568,8 @@ export class MarketingDataInsightsServiceClient { * @returns {string} A string representing the account_type. */ matchAccountTypeFromPartnerLinkName(partnerLinkName: string) { - return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account_type; + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName) + .account_type; } /** @@ -495,7 +580,8 @@ export class MarketingDataInsightsServiceClient { * @returns {string} A string representing the account. */ matchAccountFromPartnerLinkName(partnerLinkName: string) { - return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account; + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName) + .account; } /** @@ -506,7 +592,8 @@ export class MarketingDataInsightsServiceClient { * @returns {string} A string representing the partner_link. */ matchPartnerLinkFromPartnerLinkName(partnerLinkName: string) { - return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).partner_link; + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName) + .partner_link; } /** @@ -517,7 +604,7 @@ export class MarketingDataInsightsServiceClient { * @param {string} user_list * @returns {string} Resource name string. */ - userListPath(accountType:string,account:string,userList:string) { + userListPath(accountType: string, account: string, userList: string) { return this.pathTemplates.userListPathTemplate.render({ account_type: accountType, account: account, @@ -533,7 +620,8 @@ export class MarketingDataInsightsServiceClient { * @returns {string} A string representing the account_type. */ matchAccountTypeFromUserListName(userListName: string) { - return this.pathTemplates.userListPathTemplate.match(userListName).account_type; + return this.pathTemplates.userListPathTemplate.match(userListName) + .account_type; } /** @@ -555,7 +643,8 @@ export class MarketingDataInsightsServiceClient { * @returns {string} A string representing the user_list. */ matchUserListFromUserListName(userListName: string) { - return this.pathTemplates.userListPathTemplate.match(userListName).user_list; + return this.pathTemplates.userListPathTemplate.match(userListName) + .user_list; } /** @@ -566,7 +655,11 @@ export class MarketingDataInsightsServiceClient { * @param {string} user_list_direct_license * @returns {string} Resource name string. */ - userListDirectLicensePath(accountType:string,account:string,userListDirectLicense:string) { + userListDirectLicensePath( + accountType: string, + account: string, + userListDirectLicense: string, + ) { return this.pathTemplates.userListDirectLicensePathTemplate.render({ account_type: accountType, account: account, @@ -581,8 +674,12 @@ export class MarketingDataInsightsServiceClient { * A fully-qualified path representing UserListDirectLicense resource. * @returns {string} A string representing the account_type. */ - matchAccountTypeFromUserListDirectLicenseName(userListDirectLicenseName: string) { - return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account_type; + matchAccountTypeFromUserListDirectLicenseName( + userListDirectLicenseName: string, + ) { + return this.pathTemplates.userListDirectLicensePathTemplate.match( + userListDirectLicenseName, + ).account_type; } /** @@ -593,7 +690,9 @@ export class MarketingDataInsightsServiceClient { * @returns {string} A string representing the account. */ matchAccountFromUserListDirectLicenseName(userListDirectLicenseName: string) { - return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account; + return this.pathTemplates.userListDirectLicensePathTemplate.match( + userListDirectLicenseName, + ).account; } /** @@ -603,8 +702,12 @@ export class MarketingDataInsightsServiceClient { * A fully-qualified path representing UserListDirectLicense resource. * @returns {string} A string representing the user_list_direct_license. */ - matchUserListDirectLicenseFromUserListDirectLicenseName(userListDirectLicenseName: string) { - return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).user_list_direct_license; + matchUserListDirectLicenseFromUserListDirectLicenseName( + userListDirectLicenseName: string, + ) { + return this.pathTemplates.userListDirectLicensePathTemplate.match( + userListDirectLicenseName, + ).user_list_direct_license; } /** @@ -615,7 +718,11 @@ export class MarketingDataInsightsServiceClient { * @param {string} user_list_global_license * @returns {string} Resource name string. */ - userListGlobalLicensePath(accountType:string,account:string,userListGlobalLicense:string) { + userListGlobalLicensePath( + accountType: string, + account: string, + userListGlobalLicense: string, + ) { return this.pathTemplates.userListGlobalLicensePathTemplate.render({ account_type: accountType, account: account, @@ -630,8 +737,12 @@ export class MarketingDataInsightsServiceClient { * A fully-qualified path representing UserListGlobalLicense resource. * @returns {string} A string representing the account_type. */ - matchAccountTypeFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { - return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account_type; + matchAccountTypeFromUserListGlobalLicenseName( + userListGlobalLicenseName: string, + ) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match( + userListGlobalLicenseName, + ).account_type; } /** @@ -642,7 +753,9 @@ export class MarketingDataInsightsServiceClient { * @returns {string} A string representing the account. */ matchAccountFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { - return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account; + return this.pathTemplates.userListGlobalLicensePathTemplate.match( + userListGlobalLicenseName, + ).account; } /** @@ -652,8 +765,12 @@ export class MarketingDataInsightsServiceClient { * A fully-qualified path representing UserListGlobalLicense resource. * @returns {string} A string representing the user_list_global_license. */ - matchUserListGlobalLicenseFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { - return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).user_list_global_license; + matchUserListGlobalLicenseFromUserListGlobalLicenseName( + userListGlobalLicenseName: string, + ) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match( + userListGlobalLicenseName, + ).user_list_global_license; } /** @@ -665,13 +782,20 @@ export class MarketingDataInsightsServiceClient { * @param {string} license_customer_info * @returns {string} Resource name string. */ - userListGlobalLicenseCustomerInfoPath(accountType:string,account:string,userListGlobalLicense:string,licenseCustomerInfo:string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render({ - account_type: accountType, - account: account, - user_list_global_license: userListGlobalLicense, - license_customer_info: licenseCustomerInfo, - }); + userListGlobalLicenseCustomerInfoPath( + accountType: string, + account: string, + userListGlobalLicense: string, + licenseCustomerInfo: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render( + { + account_type: accountType, + account: account, + user_list_global_license: userListGlobalLicense, + license_customer_info: licenseCustomerInfo, + }, + ); } /** @@ -681,8 +805,12 @@ export class MarketingDataInsightsServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the account_type. */ - matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account_type; + matchAccountTypeFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).account_type; } /** @@ -692,8 +820,12 @@ export class MarketingDataInsightsServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the account. */ - matchAccountFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account; + matchAccountFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).account; } /** @@ -703,8 +835,12 @@ export class MarketingDataInsightsServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the user_list_global_license. */ - matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).user_list_global_license; + matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).user_list_global_license; } /** @@ -714,8 +850,12 @@ export class MarketingDataInsightsServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the license_customer_info. */ - matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).license_customer_info; + matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).license_customer_info; } /** @@ -726,7 +866,7 @@ export class MarketingDataInsightsServiceClient { */ close(): Promise { if (this.marketingDataInsightsServiceStub && !this._terminated) { - return this.marketingDataInsightsServiceStub.then(stub => { + return this.marketingDataInsightsServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -734,4 +874,4 @@ export class MarketingDataInsightsServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ads-datamanager/src/v1/partner_link_service_client.ts b/packages/google-ads-datamanager/src/v1/partner_link_service_client.ts index db057a159bd9..dc5eefc49ca2 100644 --- a/packages/google-ads-datamanager/src/v1/partner_link_service_client.ts +++ b/packages/google-ads-datamanager/src/v1/partner_link_service_client.ts @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class PartnerLinkServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('datamanager'); @@ -57,9 +64,9 @@ export class PartnerLinkServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - partnerLinkServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + partnerLinkServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of PartnerLinkServiceClient. @@ -100,21 +107,42 @@ export class PartnerLinkServiceClient { * const client = new PartnerLinkServiceClient({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 PartnerLinkServiceClient; - 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 = 'datamanager.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -139,7 +167,7 @@ export class PartnerLinkServiceClient { 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; @@ -153,10 +181,7 @@ export class PartnerLinkServiceClient { } // 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 { @@ -178,37 +203,44 @@ export class PartnerLinkServiceClient { // Create useful helper objects for these. this.pathTemplates = { accountPathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}' + 'accountTypes/{account_type}/accounts/{account}', ), partnerLinkPathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link}' + 'accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link}', ), userListPathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userLists/{user_list}' + 'accountTypes/{account_type}/accounts/{account}/userLists/{user_list}', ), userListDirectLicensePathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userListDirectLicenses/{user_list_direct_license}' + 'accountTypes/{account_type}/accounts/{account}/userListDirectLicenses/{user_list_direct_license}', ), userListGlobalLicensePathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}' - ), - userListGlobalLicenseCustomerInfoPathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}/customerInfos/{license_customer_info}' + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}', ), + userListGlobalLicenseCustomerInfoPathTemplate: + new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}/customerInfos/{license_customer_info}', + ), }; // 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 = { - searchPartnerLinks: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'partnerLinks') + searchPartnerLinks: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'partnerLinks', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ads.datamanager.v1.PartnerLinkService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ads.datamanager.v1.PartnerLinkService', + 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,37 +271,44 @@ export class PartnerLinkServiceClient { // Put together the "service stub" for // google.ads.datamanager.v1.PartnerLinkService. this.partnerLinkServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ads.datamanager.v1.PartnerLinkService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ads.datamanager.v1.PartnerLinkService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.ads.datamanager.v1.PartnerLinkService, - 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 partnerLinkServiceStubMethods = - ['createPartnerLink', 'deletePartnerLink', 'searchPartnerLinks']; + const partnerLinkServiceStubMethods = [ + 'createPartnerLink', + 'deletePartnerLink', + 'searchPartnerLinks', + ]; for (const methodName of partnerLinkServiceStubMethods) { const callPromise = this.partnerLinkServiceStub.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] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -284,8 +323,14 @@ export class PartnerLinkServiceClient { * @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 'datamanager.googleapis.com'; } @@ -296,8 +341,14 @@ export class PartnerLinkServiceClient { * @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 'datamanager.googleapis.com'; } @@ -328,9 +379,7 @@ export class PartnerLinkServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/datamanager' - ]; + return ['https://www.googleapis.com/auth/datamanager']; } getProjectId(): Promise; @@ -339,8 +388,9 @@ export class PartnerLinkServiceClient { * 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; @@ -351,347 +401,458 @@ export class PartnerLinkServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a partner link for the given account. - * - * Authorization Headers: - * - * This method supports the following optional headers to define how the API - * authorizes access for the request: - * - * * `login-account`: (Optional) The resource name of the account where the - * Google Account of the credentials is a user. If not set, defaults to the - * account of the request. Format: - * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent, which owns this collection of partner links. - * Format: accountTypes/{account_type}/accounts/{account} - * @param {google.ads.datamanager.v1.PartnerLink} request.partnerLink - * Required. The partner link 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.ads.datamanager.v1.PartnerLink|PartnerLink}. - * 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/partner_link_service.create_partner_link.js - * region_tag:datamanager_v1_generated_PartnerLinkService_CreatePartnerLink_async - */ + /** + * Creates a partner link for the given account. + * + * Authorization Headers: + * + * This method supports the following optional headers to define how the API + * authorizes access for the request: + * + * * `login-account`: (Optional) The resource name of the account where the + * Google Account of the credentials is a user. If not set, defaults to the + * account of the request. Format: + * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent, which owns this collection of partner links. + * Format: accountTypes/{account_type}/accounts/{account} + * @param {google.ads.datamanager.v1.PartnerLink} request.partnerLink + * Required. The partner link 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.ads.datamanager.v1.PartnerLink|PartnerLink}. + * 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/partner_link_service.create_partner_link.js + * region_tag:datamanager_v1_generated_PartnerLinkService_CreatePartnerLink_async + */ createPartnerLink( - request?: protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.ads.datamanager.v1.IPartnerLink, - protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ads.datamanager.v1.IPartnerLink, + protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest | undefined, + {} | undefined, + ] + >; createPartnerLink( - request: protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.ads.datamanager.v1.IPartnerLink, - protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IPartnerLink, + | protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createPartnerLink( - request: protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest, - callback: Callback< - protos.google.ads.datamanager.v1.IPartnerLink, - protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IPartnerLink, + | protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createPartnerLink( - request?: protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ads.datamanager.v1.IPartnerLink, - protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ads.datamanager.v1.IPartnerLink, - protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ads.datamanager.v1.IPartnerLink, - protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ads.datamanager.v1.IPartnerLink, + | protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ads.datamanager.v1.IPartnerLink, + protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest | 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('createPartnerLink request %j', request); - const wrappedCallback: Callback< - protos.google.ads.datamanager.v1.IPartnerLink, - protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ads.datamanager.v1.IPartnerLink, + | protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createPartnerLink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createPartnerLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ads.datamanager.v1.IPartnerLink, - protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('createPartnerLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createPartnerLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IPartnerLink, + ( + | protos.google.ads.datamanager.v1.ICreatePartnerLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createPartnerLink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a partner link for the given account. - * - * Authorization Headers: - * - * This method supports the following optional headers to define how the API - * authorizes access for the request: - * - * * `login-account`: (Optional) The resource name of the account where the - * Google Account of the credentials is a user. If not set, defaults to the - * account of the request. Format: - * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the partner link to delete. - * Format: - * accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link} - * @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/partner_link_service.delete_partner_link.js - * region_tag:datamanager_v1_generated_PartnerLinkService_DeletePartnerLink_async - */ + /** + * Deletes a partner link for the given account. + * + * Authorization Headers: + * + * This method supports the following optional headers to define how the API + * authorizes access for the request: + * + * * `login-account`: (Optional) The resource name of the account where the + * Google Account of the credentials is a user. If not set, defaults to the + * account of the request. Format: + * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the partner link to delete. + * Format: + * accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link} + * @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/partner_link_service.delete_partner_link.js + * region_tag:datamanager_v1_generated_PartnerLinkService_DeletePartnerLink_async + */ deletePartnerLink( - request?: protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest | undefined, + {} | undefined, + ] + >; deletePartnerLink( - request: protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deletePartnerLink( - request: protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deletePartnerLink( - request?: protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest | 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('deletePartnerLink request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deletePartnerLink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deletePartnerLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('deletePartnerLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deletePartnerLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ads.datamanager.v1.IDeletePartnerLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deletePartnerLink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Searches for all partner links to and from a given account. - * - * Authorization Headers: - * - * This method supports the following optional headers to define how the API - * authorizes access for the request: - * - * * `login-account`: (Optional) The resource name of the account where the - * Google Account of the credentials is a user. If not set, defaults to the - * account of the request. Format: - * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Account to search for partner links. If no `filter` is specified, - * all partner links where this account is either the `owning_account` or - * `partner_account` are returned. - * - * Format: `accountTypes/{account_type}/accounts/{account}` - * @param {number} request.pageSize - * The maximum number of partner links to return. The service may return - * fewer than this value. - * If unspecified, at most 10 partner links will be returned. - * The maximum value is 100; values above 100 will be coerced to 100. - * @param {string} request.pageToken - * A page token, received from a previous `SearchPartnerLinks` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `SearchPartnerLinks` - * must match the call that provided the page token. - * @param {string} [request.filter] - * Optional. A [filter string](https://google.aip.dev/160). All fields need to - * be on the left hand side of each condition (for example: `partner_link_id = - * 123456789`). Fields must be specified using either all [camel - * case](https://en.wikipedia.org/wiki/Camel_case) or all [snake - * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of - * camel case and snake case. - * - * Supported operations: - * - * - `AND` - * - `=` - * - `!=` - * - * Supported fields: - * - * - `partner_link_id` - * - `owning_account.account_type` - * - `owning_account.account_id` - * - `partner_account.account_type` - * - `partner_account.account_id` - * - * Example: - * `owning_account.account_type = "GOOGLE_ADS" AND partner_account.account_id - * = 987654321` - * @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.ads.datamanager.v1.PartnerLink|PartnerLink}. - * 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 `searchPartnerLinksAsync()` - * 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. - */ + /** + * Searches for all partner links to and from a given account. + * + * Authorization Headers: + * + * This method supports the following optional headers to define how the API + * authorizes access for the request: + * + * * `login-account`: (Optional) The resource name of the account where the + * Google Account of the credentials is a user. If not set, defaults to the + * account of the request. Format: + * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Account to search for partner links. If no `filter` is specified, + * all partner links where this account is either the `owning_account` or + * `partner_account` are returned. + * + * Format: `accountTypes/{account_type}/accounts/{account}` + * @param {number} request.pageSize + * The maximum number of partner links to return. The service may return + * fewer than this value. + * If unspecified, at most 10 partner links will be returned. + * The maximum value is 100; values above 100 will be coerced to 100. + * @param {string} request.pageToken + * A page token, received from a previous `SearchPartnerLinks` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `SearchPartnerLinks` + * must match the call that provided the page token. + * @param {string} [request.filter] + * Optional. A [filter string](https://google.aip.dev/160). All fields need to + * be on the left hand side of each condition (for example: `partner_link_id = + * 123456789`). Fields must be specified using either all [camel + * case](https://en.wikipedia.org/wiki/Camel_case) or all [snake + * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of + * camel case and snake case. + * + * Supported operations: + * + * - `AND` + * - `=` + * - `!=` + * + * Supported fields: + * + * - `partner_link_id` + * - `owning_account.account_type` + * - `owning_account.account_id` + * - `partner_account.account_type` + * - `partner_account.account_id` + * + * Example: + * `owning_account.account_type = "GOOGLE_ADS" AND partner_account.account_id + * = 987654321` + * @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.ads.datamanager.v1.PartnerLink|PartnerLink}. + * 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 `searchPartnerLinksAsync()` + * 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. + */ searchPartnerLinks( - request?: protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, - options?: CallOptions): - Promise<[ - protos.google.ads.datamanager.v1.IPartnerLink[], - protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest|null, - protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse - ]>; + request?: protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ads.datamanager.v1.IPartnerLink[], + protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest | null, + protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse, + ] + >; searchPartnerLinks( - request: protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, - protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse|null|undefined, - protos.google.ads.datamanager.v1.IPartnerLink>): void; + request: protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, + | protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IPartnerLink + >, + ): void; searchPartnerLinks( - request: protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, - callback: PaginationCallback< - protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, - protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse|null|undefined, - protos.google.ads.datamanager.v1.IPartnerLink>): void; + request: protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, + callback: PaginationCallback< + protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, + | protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IPartnerLink + >, + ): void; searchPartnerLinks( - request?: protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, - protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse|null|undefined, - protos.google.ads.datamanager.v1.IPartnerLink>, - callback?: PaginationCallback< + request?: protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, - protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse|null|undefined, - protos.google.ads.datamanager.v1.IPartnerLink>): - Promise<[ - protos.google.ads.datamanager.v1.IPartnerLink[], - protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest|null, - protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse - ]>|void { + | protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IPartnerLink + >, + callback?: PaginationCallback< + protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, + | protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IPartnerLink + >, + ): Promise< + [ + protos.google.ads.datamanager.v1.IPartnerLink[], + protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest | null, + protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse, + ] + > | 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.ads.datamanager.v1.ISearchPartnerLinksRequest, - protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse|null|undefined, - protos.google.ads.datamanager.v1.IPartnerLink>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, + | protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IPartnerLink + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('searchPartnerLinks values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -700,178 +861,182 @@ export class PartnerLinkServiceClient { this._log.info('searchPartnerLinks request %j', request); return this.innerApiCalls .searchPartnerLinks(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ads.datamanager.v1.IPartnerLink[], - protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest|null, - protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse - ]) => { - this._log.info('searchPartnerLinks values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ads.datamanager.v1.IPartnerLink[], + protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest | null, + protos.google.ads.datamanager.v1.ISearchPartnerLinksResponse, + ]) => { + this._log.info('searchPartnerLinks values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `searchPartnerLinks`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Account to search for partner links. If no `filter` is specified, - * all partner links where this account is either the `owning_account` or - * `partner_account` are returned. - * - * Format: `accountTypes/{account_type}/accounts/{account}` - * @param {number} request.pageSize - * The maximum number of partner links to return. The service may return - * fewer than this value. - * If unspecified, at most 10 partner links will be returned. - * The maximum value is 100; values above 100 will be coerced to 100. - * @param {string} request.pageToken - * A page token, received from a previous `SearchPartnerLinks` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `SearchPartnerLinks` - * must match the call that provided the page token. - * @param {string} [request.filter] - * Optional. A [filter string](https://google.aip.dev/160). All fields need to - * be on the left hand side of each condition (for example: `partner_link_id = - * 123456789`). Fields must be specified using either all [camel - * case](https://en.wikipedia.org/wiki/Camel_case) or all [snake - * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of - * camel case and snake case. - * - * Supported operations: - * - * - `AND` - * - `=` - * - `!=` - * - * Supported fields: - * - * - `partner_link_id` - * - `owning_account.account_type` - * - `owning_account.account_id` - * - `partner_account.account_type` - * - `partner_account.account_id` - * - * Example: - * `owning_account.account_type = "GOOGLE_ADS" AND partner_account.account_id - * = 987654321` - * @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.ads.datamanager.v1.PartnerLink|PartnerLink} 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 `searchPartnerLinksAsync()` - * 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 `searchPartnerLinks`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Account to search for partner links. If no `filter` is specified, + * all partner links where this account is either the `owning_account` or + * `partner_account` are returned. + * + * Format: `accountTypes/{account_type}/accounts/{account}` + * @param {number} request.pageSize + * The maximum number of partner links to return. The service may return + * fewer than this value. + * If unspecified, at most 10 partner links will be returned. + * The maximum value is 100; values above 100 will be coerced to 100. + * @param {string} request.pageToken + * A page token, received from a previous `SearchPartnerLinks` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `SearchPartnerLinks` + * must match the call that provided the page token. + * @param {string} [request.filter] + * Optional. A [filter string](https://google.aip.dev/160). All fields need to + * be on the left hand side of each condition (for example: `partner_link_id = + * 123456789`). Fields must be specified using either all [camel + * case](https://en.wikipedia.org/wiki/Camel_case) or all [snake + * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of + * camel case and snake case. + * + * Supported operations: + * + * - `AND` + * - `=` + * - `!=` + * + * Supported fields: + * + * - `partner_link_id` + * - `owning_account.account_type` + * - `owning_account.account_id` + * - `partner_account.account_type` + * - `partner_account.account_id` + * + * Example: + * `owning_account.account_type = "GOOGLE_ADS" AND partner_account.account_id + * = 987654321` + * @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.ads.datamanager.v1.PartnerLink|PartnerLink} 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 `searchPartnerLinksAsync()` + * 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. + */ searchPartnerLinksStream( - request?: protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, + 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['searchPartnerLinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('searchPartnerLinks stream %j', request); return this.descriptors.page.searchPartnerLinks.createStream( this.innerApiCalls.searchPartnerLinks as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `searchPartnerLinks`, 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. Account to search for partner links. If no `filter` is specified, - * all partner links where this account is either the `owning_account` or - * `partner_account` are returned. - * - * Format: `accountTypes/{account_type}/accounts/{account}` - * @param {number} request.pageSize - * The maximum number of partner links to return. The service may return - * fewer than this value. - * If unspecified, at most 10 partner links will be returned. - * The maximum value is 100; values above 100 will be coerced to 100. - * @param {string} request.pageToken - * A page token, received from a previous `SearchPartnerLinks` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `SearchPartnerLinks` - * must match the call that provided the page token. - * @param {string} [request.filter] - * Optional. A [filter string](https://google.aip.dev/160). All fields need to - * be on the left hand side of each condition (for example: `partner_link_id = - * 123456789`). Fields must be specified using either all [camel - * case](https://en.wikipedia.org/wiki/Camel_case) or all [snake - * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of - * camel case and snake case. - * - * Supported operations: - * - * - `AND` - * - `=` - * - `!=` - * - * Supported fields: - * - * - `partner_link_id` - * - `owning_account.account_type` - * - `owning_account.account_id` - * - `partner_account.account_type` - * - `partner_account.account_id` - * - * Example: - * `owning_account.account_type = "GOOGLE_ADS" AND partner_account.account_id - * = 987654321` - * @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.ads.datamanager.v1.PartnerLink|PartnerLink}. 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 include:samples/generated/v1/partner_link_service.search_partner_links.js - * region_tag:datamanager_v1_generated_PartnerLinkService_SearchPartnerLinks_async - */ + /** + * Equivalent to `searchPartnerLinks`, 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. Account to search for partner links. If no `filter` is specified, + * all partner links where this account is either the `owning_account` or + * `partner_account` are returned. + * + * Format: `accountTypes/{account_type}/accounts/{account}` + * @param {number} request.pageSize + * The maximum number of partner links to return. The service may return + * fewer than this value. + * If unspecified, at most 10 partner links will be returned. + * The maximum value is 100; values above 100 will be coerced to 100. + * @param {string} request.pageToken + * A page token, received from a previous `SearchPartnerLinks` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `SearchPartnerLinks` + * must match the call that provided the page token. + * @param {string} [request.filter] + * Optional. A [filter string](https://google.aip.dev/160). All fields need to + * be on the left hand side of each condition (for example: `partner_link_id = + * 123456789`). Fields must be specified using either all [camel + * case](https://en.wikipedia.org/wiki/Camel_case) or all [snake + * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of + * camel case and snake case. + * + * Supported operations: + * + * - `AND` + * - `=` + * - `!=` + * + * Supported fields: + * + * - `partner_link_id` + * - `owning_account.account_type` + * - `owning_account.account_id` + * - `partner_account.account_type` + * - `partner_account.account_id` + * + * Example: + * `owning_account.account_type = "GOOGLE_ADS" AND partner_account.account_id + * = 987654321` + * @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.ads.datamanager.v1.PartnerLink|PartnerLink}. 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 include:samples/generated/v1/partner_link_service.search_partner_links.js + * region_tag:datamanager_v1_generated_PartnerLinkService_SearchPartnerLinks_async + */ searchPartnerLinksAsync( - request?: protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ads.datamanager.v1.ISearchPartnerLinksRequest, + 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['searchPartnerLinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('searchPartnerLinks iterate %j', request); return this.descriptors.page.searchPartnerLinks.asyncIterate( this.innerApiCalls['searchPartnerLinks'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -885,7 +1050,7 @@ export class PartnerLinkServiceClient { * @param {string} account * @returns {string} Resource name string. */ - accountPath(accountType:string,account:string) { + accountPath(accountType: string, account: string) { return this.pathTemplates.accountPathTemplate.render({ account_type: accountType, account: account, @@ -900,7 +1065,8 @@ export class PartnerLinkServiceClient { * @returns {string} A string representing the account_type. */ matchAccountTypeFromAccountName(accountName: string) { - return this.pathTemplates.accountPathTemplate.match(accountName).account_type; + return this.pathTemplates.accountPathTemplate.match(accountName) + .account_type; } /** @@ -922,7 +1088,7 @@ export class PartnerLinkServiceClient { * @param {string} partner_link * @returns {string} Resource name string. */ - partnerLinkPath(accountType:string,account:string,partnerLink:string) { + partnerLinkPath(accountType: string, account: string, partnerLink: string) { return this.pathTemplates.partnerLinkPathTemplate.render({ account_type: accountType, account: account, @@ -938,7 +1104,8 @@ export class PartnerLinkServiceClient { * @returns {string} A string representing the account_type. */ matchAccountTypeFromPartnerLinkName(partnerLinkName: string) { - return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account_type; + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName) + .account_type; } /** @@ -949,7 +1116,8 @@ export class PartnerLinkServiceClient { * @returns {string} A string representing the account. */ matchAccountFromPartnerLinkName(partnerLinkName: string) { - return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account; + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName) + .account; } /** @@ -960,7 +1128,8 @@ export class PartnerLinkServiceClient { * @returns {string} A string representing the partner_link. */ matchPartnerLinkFromPartnerLinkName(partnerLinkName: string) { - return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).partner_link; + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName) + .partner_link; } /** @@ -971,7 +1140,7 @@ export class PartnerLinkServiceClient { * @param {string} user_list * @returns {string} Resource name string. */ - userListPath(accountType:string,account:string,userList:string) { + userListPath(accountType: string, account: string, userList: string) { return this.pathTemplates.userListPathTemplate.render({ account_type: accountType, account: account, @@ -987,7 +1156,8 @@ export class PartnerLinkServiceClient { * @returns {string} A string representing the account_type. */ matchAccountTypeFromUserListName(userListName: string) { - return this.pathTemplates.userListPathTemplate.match(userListName).account_type; + return this.pathTemplates.userListPathTemplate.match(userListName) + .account_type; } /** @@ -1009,7 +1179,8 @@ export class PartnerLinkServiceClient { * @returns {string} A string representing the user_list. */ matchUserListFromUserListName(userListName: string) { - return this.pathTemplates.userListPathTemplate.match(userListName).user_list; + return this.pathTemplates.userListPathTemplate.match(userListName) + .user_list; } /** @@ -1020,7 +1191,11 @@ export class PartnerLinkServiceClient { * @param {string} user_list_direct_license * @returns {string} Resource name string. */ - userListDirectLicensePath(accountType:string,account:string,userListDirectLicense:string) { + userListDirectLicensePath( + accountType: string, + account: string, + userListDirectLicense: string, + ) { return this.pathTemplates.userListDirectLicensePathTemplate.render({ account_type: accountType, account: account, @@ -1035,8 +1210,12 @@ export class PartnerLinkServiceClient { * A fully-qualified path representing UserListDirectLicense resource. * @returns {string} A string representing the account_type. */ - matchAccountTypeFromUserListDirectLicenseName(userListDirectLicenseName: string) { - return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account_type; + matchAccountTypeFromUserListDirectLicenseName( + userListDirectLicenseName: string, + ) { + return this.pathTemplates.userListDirectLicensePathTemplate.match( + userListDirectLicenseName, + ).account_type; } /** @@ -1047,7 +1226,9 @@ export class PartnerLinkServiceClient { * @returns {string} A string representing the account. */ matchAccountFromUserListDirectLicenseName(userListDirectLicenseName: string) { - return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account; + return this.pathTemplates.userListDirectLicensePathTemplate.match( + userListDirectLicenseName, + ).account; } /** @@ -1057,8 +1238,12 @@ export class PartnerLinkServiceClient { * A fully-qualified path representing UserListDirectLicense resource. * @returns {string} A string representing the user_list_direct_license. */ - matchUserListDirectLicenseFromUserListDirectLicenseName(userListDirectLicenseName: string) { - return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).user_list_direct_license; + matchUserListDirectLicenseFromUserListDirectLicenseName( + userListDirectLicenseName: string, + ) { + return this.pathTemplates.userListDirectLicensePathTemplate.match( + userListDirectLicenseName, + ).user_list_direct_license; } /** @@ -1069,7 +1254,11 @@ export class PartnerLinkServiceClient { * @param {string} user_list_global_license * @returns {string} Resource name string. */ - userListGlobalLicensePath(accountType:string,account:string,userListGlobalLicense:string) { + userListGlobalLicensePath( + accountType: string, + account: string, + userListGlobalLicense: string, + ) { return this.pathTemplates.userListGlobalLicensePathTemplate.render({ account_type: accountType, account: account, @@ -1084,8 +1273,12 @@ export class PartnerLinkServiceClient { * A fully-qualified path representing UserListGlobalLicense resource. * @returns {string} A string representing the account_type. */ - matchAccountTypeFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { - return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account_type; + matchAccountTypeFromUserListGlobalLicenseName( + userListGlobalLicenseName: string, + ) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match( + userListGlobalLicenseName, + ).account_type; } /** @@ -1096,7 +1289,9 @@ export class PartnerLinkServiceClient { * @returns {string} A string representing the account. */ matchAccountFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { - return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account; + return this.pathTemplates.userListGlobalLicensePathTemplate.match( + userListGlobalLicenseName, + ).account; } /** @@ -1106,8 +1301,12 @@ export class PartnerLinkServiceClient { * A fully-qualified path representing UserListGlobalLicense resource. * @returns {string} A string representing the user_list_global_license. */ - matchUserListGlobalLicenseFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { - return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).user_list_global_license; + matchUserListGlobalLicenseFromUserListGlobalLicenseName( + userListGlobalLicenseName: string, + ) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match( + userListGlobalLicenseName, + ).user_list_global_license; } /** @@ -1119,13 +1318,20 @@ export class PartnerLinkServiceClient { * @param {string} license_customer_info * @returns {string} Resource name string. */ - userListGlobalLicenseCustomerInfoPath(accountType:string,account:string,userListGlobalLicense:string,licenseCustomerInfo:string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render({ - account_type: accountType, - account: account, - user_list_global_license: userListGlobalLicense, - license_customer_info: licenseCustomerInfo, - }); + userListGlobalLicenseCustomerInfoPath( + accountType: string, + account: string, + userListGlobalLicense: string, + licenseCustomerInfo: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render( + { + account_type: accountType, + account: account, + user_list_global_license: userListGlobalLicense, + license_customer_info: licenseCustomerInfo, + }, + ); } /** @@ -1135,8 +1341,12 @@ export class PartnerLinkServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the account_type. */ - matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account_type; + matchAccountTypeFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).account_type; } /** @@ -1146,8 +1356,12 @@ export class PartnerLinkServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the account. */ - matchAccountFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account; + matchAccountFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).account; } /** @@ -1157,8 +1371,12 @@ export class PartnerLinkServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the user_list_global_license. */ - matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).user_list_global_license; + matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).user_list_global_license; } /** @@ -1168,8 +1386,12 @@ export class PartnerLinkServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the license_customer_info. */ - matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).license_customer_info; + matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).license_customer_info; } /** @@ -1180,7 +1402,7 @@ export class PartnerLinkServiceClient { */ close(): Promise { if (this.partnerLinkServiceStub && !this._terminated) { - return this.partnerLinkServiceStub.then(stub => { + return this.partnerLinkServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1188,4 +1410,4 @@ export class PartnerLinkServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ads-datamanager/src/v1/user_list_direct_license_service_client.ts b/packages/google-ads-datamanager/src/v1/user_list_direct_license_service_client.ts index dab87b792290..760d7957f876 100644 --- a/packages/google-ads-datamanager/src/v1/user_list_direct_license_service_client.ts +++ b/packages/google-ads-datamanager/src/v1/user_list_direct_license_service_client.ts @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -48,7 +55,7 @@ export class UserListDirectLicenseServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('datamanager'); @@ -61,9 +68,9 @@ export class UserListDirectLicenseServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - userListDirectLicenseServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + userListDirectLicenseServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of UserListDirectLicenseServiceClient. @@ -104,21 +111,43 @@ export class UserListDirectLicenseServiceClient { * const client = new UserListDirectLicenseServiceClient({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 UserListDirectLicenseServiceClient; - 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 staticMembers = this + .constructor as typeof UserListDirectLicenseServiceClient; + 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 = 'datamanager.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -143,7 +172,7 @@ export class UserListDirectLicenseServiceClient { 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; @@ -157,10 +186,7 @@ export class UserListDirectLicenseServiceClient { } // 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 { @@ -182,37 +208,44 @@ export class UserListDirectLicenseServiceClient { // Create useful helper objects for these. this.pathTemplates = { accountPathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}' + 'accountTypes/{account_type}/accounts/{account}', ), partnerLinkPathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link}' + 'accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link}', ), userListPathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userLists/{user_list}' + 'accountTypes/{account_type}/accounts/{account}/userLists/{user_list}', ), userListDirectLicensePathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userListDirectLicenses/{user_list_direct_license}' + 'accountTypes/{account_type}/accounts/{account}/userListDirectLicenses/{user_list_direct_license}', ), userListGlobalLicensePathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}' - ), - userListGlobalLicenseCustomerInfoPathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}/customerInfos/{license_customer_info}' + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}', ), + userListGlobalLicenseCustomerInfoPathTemplate: + new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}/customerInfos/{license_customer_info}', + ), }; // 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 = { - listUserListDirectLicenses: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'userListDirectLicenses') + listUserListDirectLicenses: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'userListDirectLicenses', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ads.datamanager.v1.UserListDirectLicenseService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ads.datamanager.v1.UserListDirectLicenseService', + 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 @@ -243,37 +276,46 @@ export class UserListDirectLicenseServiceClient { // Put together the "service stub" for // google.ads.datamanager.v1.UserListDirectLicenseService. this.userListDirectLicenseServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ads.datamanager.v1.UserListDirectLicenseService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ads.datamanager.v1.UserListDirectLicenseService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ads.datamanager.v1.UserListDirectLicenseService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ads.datamanager.v1 + .UserListDirectLicenseService, + 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 userListDirectLicenseServiceStubMethods = - ['createUserListDirectLicense', 'getUserListDirectLicense', 'updateUserListDirectLicense', 'listUserListDirectLicenses']; + const userListDirectLicenseServiceStubMethods = [ + 'createUserListDirectLicense', + 'getUserListDirectLicense', + 'updateUserListDirectLicense', + 'listUserListDirectLicenses', + ]; for (const methodName of userListDirectLicenseServiceStubMethods) { const callPromise = this.userListDirectLicenseServiceStub.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] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -288,8 +330,14 @@ export class UserListDirectLicenseServiceClient { * @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 'datamanager.googleapis.com'; } @@ -300,8 +348,14 @@ export class UserListDirectLicenseServiceClient { * @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 'datamanager.googleapis.com'; } @@ -332,9 +386,7 @@ export class UserListDirectLicenseServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/datamanager' - ]; + return ['https://www.googleapis.com/auth/datamanager']; } getProjectId(): Promise; @@ -343,8 +395,9 @@ export class UserListDirectLicenseServiceClient { * 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; @@ -355,419 +408,592 @@ export class UserListDirectLicenseServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a user list direct license. - * - * This feature is only available to data partners. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The account that owns the user list being licensed. Should be in - * the format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} - * @param {google.ads.datamanager.v1.UserListDirectLicense} request.userListDirectLicense - * Required. The user list direct license 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.ads.datamanager.v1.UserListDirectLicense|UserListDirectLicense}. - * 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/user_list_direct_license_service.create_user_list_direct_license.js - * region_tag:datamanager_v1_generated_UserListDirectLicenseService_CreateUserListDirectLicense_async - */ + /** + * Creates a user list direct license. + * + * This feature is only available to data partners. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account that owns the user list being licensed. Should be in + * the format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + * @param {google.ads.datamanager.v1.UserListDirectLicense} request.userListDirectLicense + * Required. The user list direct license 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.ads.datamanager.v1.UserListDirectLicense|UserListDirectLicense}. + * 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/user_list_direct_license_service.create_user_list_direct_license.js + * region_tag:datamanager_v1_generated_UserListDirectLicenseService_CreateUserListDirectLicense_async + */ createUserListDirectLicense( - request?: protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest, - options?: CallOptions): - Promise<[ - protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest|undefined, {}|undefined - ]>; + request?: protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserListDirectLicense, + ( + | protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest + | undefined + ), + {} | undefined, + ] + >; createUserListDirectLicense( - request: protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest, - options: CallOptions, - callback: Callback< - protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + | protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createUserListDirectLicense( - request: protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest, - callback: Callback< - protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + | protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createUserListDirectLicense( - request?: protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest|undefined, {}|undefined - ]>|void { + | protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + | protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserListDirectLicense, + ( + | protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest + | 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('createUserListDirectLicense request %j', request); - const wrappedCallback: Callback< - protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + | protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createUserListDirectLicense response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createUserListDirectLicense(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest|undefined, - {}|undefined - ]) => { - this._log.info('createUserListDirectLicense response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createUserListDirectLicense(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IUserListDirectLicense, + ( + | protos.google.ads.datamanager.v1.ICreateUserListDirectLicenseRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createUserListDirectLicense response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieves a user list direct license. - * - * This feature is only available to data partners. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the user list direct license. - * @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.ads.datamanager.v1.UserListDirectLicense|UserListDirectLicense}. - * 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/user_list_direct_license_service.get_user_list_direct_license.js - * region_tag:datamanager_v1_generated_UserListDirectLicenseService_GetUserListDirectLicense_async - */ + /** + * Retrieves a user list direct license. + * + * This feature is only available to data partners. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the user list direct license. + * @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.ads.datamanager.v1.UserListDirectLicense|UserListDirectLicense}. + * 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/user_list_direct_license_service.get_user_list_direct_license.js + * region_tag:datamanager_v1_generated_UserListDirectLicenseService_GetUserListDirectLicense_async + */ getUserListDirectLicense( - request?: protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest, - options?: CallOptions): - Promise<[ - protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest|undefined, {}|undefined - ]>; + request?: protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserListDirectLicense, + ( + | protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest + | undefined + ), + {} | undefined, + ] + >; getUserListDirectLicense( - request: protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest, - options: CallOptions, - callback: Callback< - protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + | protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getUserListDirectLicense( - request: protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest, - callback: Callback< - protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + | protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getUserListDirectLicense( - request?: protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest|undefined, {}|undefined - ]>|void { + | protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + | protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserListDirectLicense, + ( + | protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest + | 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('getUserListDirectLicense request %j', request); - const wrappedCallback: Callback< - protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + | protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getUserListDirectLicense response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getUserListDirectLicense(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest|undefined, - {}|undefined - ]) => { - this._log.info('getUserListDirectLicense response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getUserListDirectLicense(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IUserListDirectLicense, + ( + | protos.google.ads.datamanager.v1.IGetUserListDirectLicenseRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getUserListDirectLicense response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a user list direct license. - * - * This feature is only available to data partners. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ads.datamanager.v1.UserListDirectLicense} request.userListDirectLicense - * Required. The licenses' `name` field is used to identify the license to - * update. - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. The list of fields to update. The special character `*` is not - * supported and an `INVALID_UPDATE_MASK` error will be thrown if used. - * @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.ads.datamanager.v1.UserListDirectLicense|UserListDirectLicense}. - * 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/user_list_direct_license_service.update_user_list_direct_license.js - * region_tag:datamanager_v1_generated_UserListDirectLicenseService_UpdateUserListDirectLicense_async - */ + /** + * Updates a user list direct license. + * + * This feature is only available to data partners. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ads.datamanager.v1.UserListDirectLicense} request.userListDirectLicense + * Required. The licenses' `name` field is used to identify the license to + * update. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. The list of fields to update. The special character `*` is not + * supported and an `INVALID_UPDATE_MASK` error will be thrown if used. + * @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.ads.datamanager.v1.UserListDirectLicense|UserListDirectLicense}. + * 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/user_list_direct_license_service.update_user_list_direct_license.js + * region_tag:datamanager_v1_generated_UserListDirectLicenseService_UpdateUserListDirectLicense_async + */ updateUserListDirectLicense( - request?: protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest, - options?: CallOptions): - Promise<[ - protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest|undefined, {}|undefined - ]>; + request?: protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserListDirectLicense, + ( + | protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest + | undefined + ), + {} | undefined, + ] + >; updateUserListDirectLicense( - request: protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest, - options: CallOptions, - callback: Callback< - protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + | protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateUserListDirectLicense( - request: protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest, - callback: Callback< - protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + | protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateUserListDirectLicense( - request?: protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest|undefined, {}|undefined - ]>|void { + | protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + | protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserListDirectLicense, + ( + | protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest + | 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({ - 'user_list_direct_license.name': request.userListDirectLicense!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'user_list_direct_license.name': + request.userListDirectLicense!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateUserListDirectLicense request %j', request); - const wrappedCallback: Callback< - protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ads.datamanager.v1.IUserListDirectLicense, + | protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateUserListDirectLicense response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateUserListDirectLicense(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ads.datamanager.v1.IUserListDirectLicense, - protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateUserListDirectLicense response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateUserListDirectLicense(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IUserListDirectLicense, + ( + | protos.google.ads.datamanager.v1.IUpdateUserListDirectLicenseRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateUserListDirectLicense response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all user list direct licenses owned by the parent account. - * - * This feature is only available to data partners. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The account whose licenses are being queried. Should be in the - * format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} - * @param {string} [request.filter] - * Optional. A [filter string](https://google.aip.dev/160) to apply to the - * list request. All fields need to be on the left hand side of each condition - * (for example: `user_list_id = 123`). Fields must be specified using either - * all [camel case](https://en.wikipedia.org/wiki/Camel_case) or all [snake - * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of - * camel case and snake case. - * - * **Supported Operations:** - * - * - `AND` - * - `=` - * - `!=` - * - `>` - * - `>=` - * - `<` - * - `<=` - * - * **Unsupported Fields:** - * - * - `name` (use get method instead) - * - `historical_pricings` and all its subfields - * - `pricing.start_time` - * - `pricing.end_time` - * @param {number} [request.pageSize] - * Optional. The maximum number of licenses to return per page. The service - * may return fewer than this value. If unspecified, at most 50 licenses will - * be returned. The maximum value is 1000; values above 1000 will be coerced - * to 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListUserListDirectLicense` call. Provide this to retrieve the subsequent - * page. - * - * When paginating, all other parameters provided to - * `ListUserListDirectLicense` must match the call that provided the page - * token. - * @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.ads.datamanager.v1.UserListDirectLicense|UserListDirectLicense}. - * 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 `listUserListDirectLicensesAsync()` - * 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 user list direct licenses owned by the parent account. + * + * This feature is only available to data partners. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account whose licenses are being queried. Should be in the + * format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + * @param {string} [request.filter] + * Optional. A [filter string](https://google.aip.dev/160) to apply to the + * list request. All fields need to be on the left hand side of each condition + * (for example: `user_list_id = 123`). Fields must be specified using either + * all [camel case](https://en.wikipedia.org/wiki/Camel_case) or all [snake + * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of + * camel case and snake case. + * + * **Supported Operations:** + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * + * **Unsupported Fields:** + * + * - `name` (use get method instead) + * - `historical_pricings` and all its subfields + * - `pricing.start_time` + * - `pricing.end_time` + * @param {number} [request.pageSize] + * Optional. The maximum number of licenses to return per page. The service + * may return fewer than this value. If unspecified, at most 50 licenses will + * be returned. The maximum value is 1000; values above 1000 will be coerced + * to 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListUserListDirectLicense` call. Provide this to retrieve the subsequent + * page. + * + * When paginating, all other parameters provided to + * `ListUserListDirectLicense` must match the call that provided the page + * token. + * @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.ads.datamanager.v1.UserListDirectLicense|UserListDirectLicense}. + * 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 `listUserListDirectLicensesAsync()` + * 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. + */ listUserListDirectLicenses( - request?: protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, - options?: CallOptions): - Promise<[ - protos.google.ads.datamanager.v1.IUserListDirectLicense[], - protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest|null, - protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse - ]>; + request?: protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserListDirectLicense[], + protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest | null, + protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse, + ] + >; listUserListDirectLicenses( - request: protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, - protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse|null|undefined, - protos.google.ads.datamanager.v1.IUserListDirectLicense>): void; + request: protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, + | protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IUserListDirectLicense + >, + ): void; listUserListDirectLicenses( - request: protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, - callback: PaginationCallback< - protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, - protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse|null|undefined, - protos.google.ads.datamanager.v1.IUserListDirectLicense>): void; + request: protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, + callback: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, + | protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IUserListDirectLicense + >, + ): void; listUserListDirectLicenses( - request?: protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, - protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse|null|undefined, - protos.google.ads.datamanager.v1.IUserListDirectLicense>, - callback?: PaginationCallback< + request?: protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, - protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse|null|undefined, - protos.google.ads.datamanager.v1.IUserListDirectLicense>): - Promise<[ - protos.google.ads.datamanager.v1.IUserListDirectLicense[], - protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest|null, - protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse - ]>|void { + | protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IUserListDirectLicense + >, + callback?: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, + | protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IUserListDirectLicense + >, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserListDirectLicense[], + protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest | null, + protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse, + ] + > | 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.ads.datamanager.v1.IListUserListDirectLicensesRequest, - protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse|null|undefined, - protos.google.ads.datamanager.v1.IUserListDirectLicense>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, + | protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IUserListDirectLicense + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listUserListDirectLicenses values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -776,174 +1002,178 @@ export class UserListDirectLicenseServiceClient { this._log.info('listUserListDirectLicenses request %j', request); return this.innerApiCalls .listUserListDirectLicenses(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ads.datamanager.v1.IUserListDirectLicense[], - protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest|null, - protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse - ]) => { - this._log.info('listUserListDirectLicenses values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ads.datamanager.v1.IUserListDirectLicense[], + protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest | null, + protos.google.ads.datamanager.v1.IListUserListDirectLicensesResponse, + ]) => { + this._log.info('listUserListDirectLicenses values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listUserListDirectLicenses`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The account whose licenses are being queried. Should be in the - * format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} - * @param {string} [request.filter] - * Optional. A [filter string](https://google.aip.dev/160) to apply to the - * list request. All fields need to be on the left hand side of each condition - * (for example: `user_list_id = 123`). Fields must be specified using either - * all [camel case](https://en.wikipedia.org/wiki/Camel_case) or all [snake - * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of - * camel case and snake case. - * - * **Supported Operations:** - * - * - `AND` - * - `=` - * - `!=` - * - `>` - * - `>=` - * - `<` - * - `<=` - * - * **Unsupported Fields:** - * - * - `name` (use get method instead) - * - `historical_pricings` and all its subfields - * - `pricing.start_time` - * - `pricing.end_time` - * @param {number} [request.pageSize] - * Optional. The maximum number of licenses to return per page. The service - * may return fewer than this value. If unspecified, at most 50 licenses will - * be returned. The maximum value is 1000; values above 1000 will be coerced - * to 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListUserListDirectLicense` call. Provide this to retrieve the subsequent - * page. - * - * When paginating, all other parameters provided to - * `ListUserListDirectLicense` must match the call that provided the page - * token. - * @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.ads.datamanager.v1.UserListDirectLicense|UserListDirectLicense} 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 `listUserListDirectLicensesAsync()` - * 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 `listUserListDirectLicenses`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account whose licenses are being queried. Should be in the + * format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + * @param {string} [request.filter] + * Optional. A [filter string](https://google.aip.dev/160) to apply to the + * list request. All fields need to be on the left hand side of each condition + * (for example: `user_list_id = 123`). Fields must be specified using either + * all [camel case](https://en.wikipedia.org/wiki/Camel_case) or all [snake + * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of + * camel case and snake case. + * + * **Supported Operations:** + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * + * **Unsupported Fields:** + * + * - `name` (use get method instead) + * - `historical_pricings` and all its subfields + * - `pricing.start_time` + * - `pricing.end_time` + * @param {number} [request.pageSize] + * Optional. The maximum number of licenses to return per page. The service + * may return fewer than this value. If unspecified, at most 50 licenses will + * be returned. The maximum value is 1000; values above 1000 will be coerced + * to 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListUserListDirectLicense` call. Provide this to retrieve the subsequent + * page. + * + * When paginating, all other parameters provided to + * `ListUserListDirectLicense` must match the call that provided the page + * token. + * @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.ads.datamanager.v1.UserListDirectLicense|UserListDirectLicense} 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 `listUserListDirectLicensesAsync()` + * 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. + */ listUserListDirectLicensesStream( - request?: protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, + 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['listUserListDirectLicenses']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listUserListDirectLicenses stream %j', request); return this.descriptors.page.listUserListDirectLicenses.createStream( this.innerApiCalls.listUserListDirectLicenses as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listUserListDirectLicenses`, 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 account whose licenses are being queried. Should be in the - * format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} - * @param {string} [request.filter] - * Optional. A [filter string](https://google.aip.dev/160) to apply to the - * list request. All fields need to be on the left hand side of each condition - * (for example: `user_list_id = 123`). Fields must be specified using either - * all [camel case](https://en.wikipedia.org/wiki/Camel_case) or all [snake - * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of - * camel case and snake case. - * - * **Supported Operations:** - * - * - `AND` - * - `=` - * - `!=` - * - `>` - * - `>=` - * - `<` - * - `<=` - * - * **Unsupported Fields:** - * - * - `name` (use get method instead) - * - `historical_pricings` and all its subfields - * - `pricing.start_time` - * - `pricing.end_time` - * @param {number} [request.pageSize] - * Optional. The maximum number of licenses to return per page. The service - * may return fewer than this value. If unspecified, at most 50 licenses will - * be returned. The maximum value is 1000; values above 1000 will be coerced - * to 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListUserListDirectLicense` call. Provide this to retrieve the subsequent - * page. - * - * When paginating, all other parameters provided to - * `ListUserListDirectLicense` must match the call that provided the 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 protos.google.ads.datamanager.v1.UserListDirectLicense|UserListDirectLicense}. 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 include:samples/generated/v1/user_list_direct_license_service.list_user_list_direct_licenses.js - * region_tag:datamanager_v1_generated_UserListDirectLicenseService_ListUserListDirectLicenses_async - */ + /** + * Equivalent to `listUserListDirectLicenses`, 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 account whose licenses are being queried. Should be in the + * format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + * @param {string} [request.filter] + * Optional. A [filter string](https://google.aip.dev/160) to apply to the + * list request. All fields need to be on the left hand side of each condition + * (for example: `user_list_id = 123`). Fields must be specified using either + * all [camel case](https://en.wikipedia.org/wiki/Camel_case) or all [snake + * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of + * camel case and snake case. + * + * **Supported Operations:** + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * + * **Unsupported Fields:** + * + * - `name` (use get method instead) + * - `historical_pricings` and all its subfields + * - `pricing.start_time` + * - `pricing.end_time` + * @param {number} [request.pageSize] + * Optional. The maximum number of licenses to return per page. The service + * may return fewer than this value. If unspecified, at most 50 licenses will + * be returned. The maximum value is 1000; values above 1000 will be coerced + * to 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListUserListDirectLicense` call. Provide this to retrieve the subsequent + * page. + * + * When paginating, all other parameters provided to + * `ListUserListDirectLicense` must match the call that provided the 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 protos.google.ads.datamanager.v1.UserListDirectLicense|UserListDirectLicense}. 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 include:samples/generated/v1/user_list_direct_license_service.list_user_list_direct_licenses.js + * region_tag:datamanager_v1_generated_UserListDirectLicenseService_ListUserListDirectLicenses_async + */ listUserListDirectLicensesAsync( - request?: protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ads.datamanager.v1.IListUserListDirectLicensesRequest, + 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['listUserListDirectLicenses']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listUserListDirectLicenses iterate %j', request); return this.descriptors.page.listUserListDirectLicenses.asyncIterate( this.innerApiCalls['listUserListDirectLicenses'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -957,7 +1187,7 @@ export class UserListDirectLicenseServiceClient { * @param {string} account * @returns {string} Resource name string. */ - accountPath(accountType:string,account:string) { + accountPath(accountType: string, account: string) { return this.pathTemplates.accountPathTemplate.render({ account_type: accountType, account: account, @@ -972,7 +1202,8 @@ export class UserListDirectLicenseServiceClient { * @returns {string} A string representing the account_type. */ matchAccountTypeFromAccountName(accountName: string) { - return this.pathTemplates.accountPathTemplate.match(accountName).account_type; + return this.pathTemplates.accountPathTemplate.match(accountName) + .account_type; } /** @@ -994,7 +1225,7 @@ export class UserListDirectLicenseServiceClient { * @param {string} partner_link * @returns {string} Resource name string. */ - partnerLinkPath(accountType:string,account:string,partnerLink:string) { + partnerLinkPath(accountType: string, account: string, partnerLink: string) { return this.pathTemplates.partnerLinkPathTemplate.render({ account_type: accountType, account: account, @@ -1010,7 +1241,8 @@ export class UserListDirectLicenseServiceClient { * @returns {string} A string representing the account_type. */ matchAccountTypeFromPartnerLinkName(partnerLinkName: string) { - return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account_type; + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName) + .account_type; } /** @@ -1021,7 +1253,8 @@ export class UserListDirectLicenseServiceClient { * @returns {string} A string representing the account. */ matchAccountFromPartnerLinkName(partnerLinkName: string) { - return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account; + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName) + .account; } /** @@ -1032,7 +1265,8 @@ export class UserListDirectLicenseServiceClient { * @returns {string} A string representing the partner_link. */ matchPartnerLinkFromPartnerLinkName(partnerLinkName: string) { - return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).partner_link; + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName) + .partner_link; } /** @@ -1043,7 +1277,7 @@ export class UserListDirectLicenseServiceClient { * @param {string} user_list * @returns {string} Resource name string. */ - userListPath(accountType:string,account:string,userList:string) { + userListPath(accountType: string, account: string, userList: string) { return this.pathTemplates.userListPathTemplate.render({ account_type: accountType, account: account, @@ -1059,7 +1293,8 @@ export class UserListDirectLicenseServiceClient { * @returns {string} A string representing the account_type. */ matchAccountTypeFromUserListName(userListName: string) { - return this.pathTemplates.userListPathTemplate.match(userListName).account_type; + return this.pathTemplates.userListPathTemplate.match(userListName) + .account_type; } /** @@ -1081,7 +1316,8 @@ export class UserListDirectLicenseServiceClient { * @returns {string} A string representing the user_list. */ matchUserListFromUserListName(userListName: string) { - return this.pathTemplates.userListPathTemplate.match(userListName).user_list; + return this.pathTemplates.userListPathTemplate.match(userListName) + .user_list; } /** @@ -1092,7 +1328,11 @@ export class UserListDirectLicenseServiceClient { * @param {string} user_list_direct_license * @returns {string} Resource name string. */ - userListDirectLicensePath(accountType:string,account:string,userListDirectLicense:string) { + userListDirectLicensePath( + accountType: string, + account: string, + userListDirectLicense: string, + ) { return this.pathTemplates.userListDirectLicensePathTemplate.render({ account_type: accountType, account: account, @@ -1107,8 +1347,12 @@ export class UserListDirectLicenseServiceClient { * A fully-qualified path representing UserListDirectLicense resource. * @returns {string} A string representing the account_type. */ - matchAccountTypeFromUserListDirectLicenseName(userListDirectLicenseName: string) { - return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account_type; + matchAccountTypeFromUserListDirectLicenseName( + userListDirectLicenseName: string, + ) { + return this.pathTemplates.userListDirectLicensePathTemplate.match( + userListDirectLicenseName, + ).account_type; } /** @@ -1119,7 +1363,9 @@ export class UserListDirectLicenseServiceClient { * @returns {string} A string representing the account. */ matchAccountFromUserListDirectLicenseName(userListDirectLicenseName: string) { - return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account; + return this.pathTemplates.userListDirectLicensePathTemplate.match( + userListDirectLicenseName, + ).account; } /** @@ -1129,8 +1375,12 @@ export class UserListDirectLicenseServiceClient { * A fully-qualified path representing UserListDirectLicense resource. * @returns {string} A string representing the user_list_direct_license. */ - matchUserListDirectLicenseFromUserListDirectLicenseName(userListDirectLicenseName: string) { - return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).user_list_direct_license; + matchUserListDirectLicenseFromUserListDirectLicenseName( + userListDirectLicenseName: string, + ) { + return this.pathTemplates.userListDirectLicensePathTemplate.match( + userListDirectLicenseName, + ).user_list_direct_license; } /** @@ -1141,7 +1391,11 @@ export class UserListDirectLicenseServiceClient { * @param {string} user_list_global_license * @returns {string} Resource name string. */ - userListGlobalLicensePath(accountType:string,account:string,userListGlobalLicense:string) { + userListGlobalLicensePath( + accountType: string, + account: string, + userListGlobalLicense: string, + ) { return this.pathTemplates.userListGlobalLicensePathTemplate.render({ account_type: accountType, account: account, @@ -1156,8 +1410,12 @@ export class UserListDirectLicenseServiceClient { * A fully-qualified path representing UserListGlobalLicense resource. * @returns {string} A string representing the account_type. */ - matchAccountTypeFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { - return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account_type; + matchAccountTypeFromUserListGlobalLicenseName( + userListGlobalLicenseName: string, + ) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match( + userListGlobalLicenseName, + ).account_type; } /** @@ -1168,7 +1426,9 @@ export class UserListDirectLicenseServiceClient { * @returns {string} A string representing the account. */ matchAccountFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { - return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account; + return this.pathTemplates.userListGlobalLicensePathTemplate.match( + userListGlobalLicenseName, + ).account; } /** @@ -1178,8 +1438,12 @@ export class UserListDirectLicenseServiceClient { * A fully-qualified path representing UserListGlobalLicense resource. * @returns {string} A string representing the user_list_global_license. */ - matchUserListGlobalLicenseFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { - return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).user_list_global_license; + matchUserListGlobalLicenseFromUserListGlobalLicenseName( + userListGlobalLicenseName: string, + ) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match( + userListGlobalLicenseName, + ).user_list_global_license; } /** @@ -1191,13 +1455,20 @@ export class UserListDirectLicenseServiceClient { * @param {string} license_customer_info * @returns {string} Resource name string. */ - userListGlobalLicenseCustomerInfoPath(accountType:string,account:string,userListGlobalLicense:string,licenseCustomerInfo:string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render({ - account_type: accountType, - account: account, - user_list_global_license: userListGlobalLicense, - license_customer_info: licenseCustomerInfo, - }); + userListGlobalLicenseCustomerInfoPath( + accountType: string, + account: string, + userListGlobalLicense: string, + licenseCustomerInfo: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render( + { + account_type: accountType, + account: account, + user_list_global_license: userListGlobalLicense, + license_customer_info: licenseCustomerInfo, + }, + ); } /** @@ -1207,8 +1478,12 @@ export class UserListDirectLicenseServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the account_type. */ - matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account_type; + matchAccountTypeFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).account_type; } /** @@ -1218,8 +1493,12 @@ export class UserListDirectLicenseServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the account. */ - matchAccountFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account; + matchAccountFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).account; } /** @@ -1229,8 +1508,12 @@ export class UserListDirectLicenseServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the user_list_global_license. */ - matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).user_list_global_license; + matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).user_list_global_license; } /** @@ -1240,8 +1523,12 @@ export class UserListDirectLicenseServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the license_customer_info. */ - matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).license_customer_info; + matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).license_customer_info; } /** @@ -1252,7 +1539,7 @@ export class UserListDirectLicenseServiceClient { */ close(): Promise { if (this.userListDirectLicenseServiceStub && !this._terminated) { - return this.userListDirectLicenseServiceStub.then(stub => { + return this.userListDirectLicenseServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1260,4 +1547,4 @@ export class UserListDirectLicenseServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ads-datamanager/src/v1/user_list_global_license_service_client.ts b/packages/google-ads-datamanager/src/v1/user_list_global_license_service_client.ts index f2fba1ccb8e0..23f9d6630fe9 100644 --- a/packages/google-ads-datamanager/src/v1/user_list_global_license_service_client.ts +++ b/packages/google-ads-datamanager/src/v1/user_list_global_license_service_client.ts @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -48,7 +55,7 @@ export class UserListGlobalLicenseServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('datamanager'); @@ -61,9 +68,9 @@ export class UserListGlobalLicenseServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - userListGlobalLicenseServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + userListGlobalLicenseServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of UserListGlobalLicenseServiceClient. @@ -104,21 +111,43 @@ export class UserListGlobalLicenseServiceClient { * const client = new UserListGlobalLicenseServiceClient({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 UserListGlobalLicenseServiceClient; - 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 staticMembers = this + .constructor as typeof UserListGlobalLicenseServiceClient; + 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 = 'datamanager.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -143,7 +172,7 @@ export class UserListGlobalLicenseServiceClient { 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; @@ -157,10 +186,7 @@ export class UserListGlobalLicenseServiceClient { } // 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 { @@ -182,39 +208,50 @@ export class UserListGlobalLicenseServiceClient { // Create useful helper objects for these. this.pathTemplates = { accountPathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}' + 'accountTypes/{account_type}/accounts/{account}', ), partnerLinkPathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link}' + 'accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link}', ), userListPathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userLists/{user_list}' + 'accountTypes/{account_type}/accounts/{account}/userLists/{user_list}', ), userListDirectLicensePathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userListDirectLicenses/{user_list_direct_license}' + 'accountTypes/{account_type}/accounts/{account}/userListDirectLicenses/{user_list_direct_license}', ), userListGlobalLicensePathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}' - ), - userListGlobalLicenseCustomerInfoPathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}/customerInfos/{license_customer_info}' + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}', ), + userListGlobalLicenseCustomerInfoPathTemplate: + new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}/customerInfos/{license_customer_info}', + ), }; // 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 = { - listUserListGlobalLicenses: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'userListGlobalLicenses'), + listUserListGlobalLicenses: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'userListGlobalLicenses', + ), listUserListGlobalLicenseCustomerInfos: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'userListGlobalLicenseCustomerInfos') + new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'userListGlobalLicenseCustomerInfos', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ads.datamanager.v1.UserListGlobalLicenseService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ads.datamanager.v1.UserListGlobalLicenseService', + 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 @@ -245,37 +282,47 @@ export class UserListGlobalLicenseServiceClient { // Put together the "service stub" for // google.ads.datamanager.v1.UserListGlobalLicenseService. this.userListGlobalLicenseServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ads.datamanager.v1.UserListGlobalLicenseService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ads.datamanager.v1.UserListGlobalLicenseService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ads.datamanager.v1.UserListGlobalLicenseService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ads.datamanager.v1 + .UserListGlobalLicenseService, + 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 userListGlobalLicenseServiceStubMethods = - ['createUserListGlobalLicense', 'updateUserListGlobalLicense', 'getUserListGlobalLicense', 'listUserListGlobalLicenses', 'listUserListGlobalLicenseCustomerInfos']; + const userListGlobalLicenseServiceStubMethods = [ + 'createUserListGlobalLicense', + 'updateUserListGlobalLicense', + 'getUserListGlobalLicense', + 'listUserListGlobalLicenses', + 'listUserListGlobalLicenseCustomerInfos', + ]; for (const methodName of userListGlobalLicenseServiceStubMethods) { const callPromise = this.userListGlobalLicenseServiceStub.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] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -290,8 +337,14 @@ export class UserListGlobalLicenseServiceClient { * @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 'datamanager.googleapis.com'; } @@ -302,8 +355,14 @@ export class UserListGlobalLicenseServiceClient { * @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 'datamanager.googleapis.com'; } @@ -334,9 +393,7 @@ export class UserListGlobalLicenseServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/datamanager' - ]; + return ['https://www.googleapis.com/auth/datamanager']; } getProjectId(): Promise; @@ -345,8 +402,9 @@ export class UserListGlobalLicenseServiceClient { * 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; @@ -357,419 +415,592 @@ export class UserListGlobalLicenseServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a user list global license. - * - * This feature is only available to data partners. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The account that owns the user list being licensed. Should be in - * the format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} - * @param {google.ads.datamanager.v1.UserListGlobalLicense} request.userListGlobalLicense - * Required. The user list global license 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.ads.datamanager.v1.UserListGlobalLicense|UserListGlobalLicense}. - * 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/user_list_global_license_service.create_user_list_global_license.js - * region_tag:datamanager_v1_generated_UserListGlobalLicenseService_CreateUserListGlobalLicense_async - */ + /** + * Creates a user list global license. + * + * This feature is only available to data partners. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account that owns the user list being licensed. Should be in + * the format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + * @param {google.ads.datamanager.v1.UserListGlobalLicense} request.userListGlobalLicense + * Required. The user list global license 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.ads.datamanager.v1.UserListGlobalLicense|UserListGlobalLicense}. + * 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/user_list_global_license_service.create_user_list_global_license.js + * region_tag:datamanager_v1_generated_UserListGlobalLicenseService_CreateUserListGlobalLicense_async + */ createUserListGlobalLicense( - request?: protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest, - options?: CallOptions): - Promise<[ - protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest|undefined, {}|undefined - ]>; + request?: protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + ( + | protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest + | undefined + ), + {} | undefined, + ] + >; createUserListGlobalLicense( - request: protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest, - options: CallOptions, - callback: Callback< - protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + | protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createUserListGlobalLicense( - request: protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest, - callback: Callback< - protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + | protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createUserListGlobalLicense( - request?: protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest|undefined, {}|undefined - ]>|void { + | protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + | protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + ( + | protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest + | 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('createUserListGlobalLicense request %j', request); - const wrappedCallback: Callback< - protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + | protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createUserListGlobalLicense response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createUserListGlobalLicense(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest|undefined, - {}|undefined - ]) => { - this._log.info('createUserListGlobalLicense response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createUserListGlobalLicense(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + ( + | protos.google.ads.datamanager.v1.ICreateUserListGlobalLicenseRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createUserListGlobalLicense response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a user list global license. - * - * This feature is only available to data partners. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ads.datamanager.v1.UserListGlobalLicense} request.userListGlobalLicense - * Required. The licenses' `name` field is used to identify the license to - * update. - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. The list of fields to update. The special character `*` is not - * supported and an `INVALID_UPDATE_MASK` error will be thrown if used. - * @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.ads.datamanager.v1.UserListGlobalLicense|UserListGlobalLicense}. - * 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/user_list_global_license_service.update_user_list_global_license.js - * region_tag:datamanager_v1_generated_UserListGlobalLicenseService_UpdateUserListGlobalLicense_async - */ + /** + * Updates a user list global license. + * + * This feature is only available to data partners. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ads.datamanager.v1.UserListGlobalLicense} request.userListGlobalLicense + * Required. The licenses' `name` field is used to identify the license to + * update. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. The list of fields to update. The special character `*` is not + * supported and an `INVALID_UPDATE_MASK` error will be thrown if used. + * @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.ads.datamanager.v1.UserListGlobalLicense|UserListGlobalLicense}. + * 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/user_list_global_license_service.update_user_list_global_license.js + * region_tag:datamanager_v1_generated_UserListGlobalLicenseService_UpdateUserListGlobalLicense_async + */ updateUserListGlobalLicense( - request?: protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest, - options?: CallOptions): - Promise<[ - protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest|undefined, {}|undefined - ]>; + request?: protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + ( + | protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest + | undefined + ), + {} | undefined, + ] + >; updateUserListGlobalLicense( - request: protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest, - options: CallOptions, - callback: Callback< - protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + | protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateUserListGlobalLicense( - request: protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest, - callback: Callback< - protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + | protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateUserListGlobalLicense( - request?: protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest|undefined, {}|undefined - ]>|void { + | protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + | protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + ( + | protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest + | 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({ - 'user_list_global_license.name': request.userListGlobalLicense!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'user_list_global_license.name': + request.userListGlobalLicense!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateUserListGlobalLicense request %j', request); - const wrappedCallback: Callback< - protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + | protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateUserListGlobalLicense response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateUserListGlobalLicense(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateUserListGlobalLicense response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateUserListGlobalLicense(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + ( + | protos.google.ads.datamanager.v1.IUpdateUserListGlobalLicenseRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateUserListGlobalLicense response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieves a user list global license. - * - * This feature is only available to data partners. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the user list global license. - * @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.ads.datamanager.v1.UserListGlobalLicense|UserListGlobalLicense}. - * 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/user_list_global_license_service.get_user_list_global_license.js - * region_tag:datamanager_v1_generated_UserListGlobalLicenseService_GetUserListGlobalLicense_async - */ + /** + * Retrieves a user list global license. + * + * This feature is only available to data partners. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the user list global license. + * @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.ads.datamanager.v1.UserListGlobalLicense|UserListGlobalLicense}. + * 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/user_list_global_license_service.get_user_list_global_license.js + * region_tag:datamanager_v1_generated_UserListGlobalLicenseService_GetUserListGlobalLicense_async + */ getUserListGlobalLicense( - request?: protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest, - options?: CallOptions): - Promise<[ - protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest|undefined, {}|undefined - ]>; + request?: protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + ( + | protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest + | undefined + ), + {} | undefined, + ] + >; getUserListGlobalLicense( - request: protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest, - options: CallOptions, - callback: Callback< - protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + | protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getUserListGlobalLicense( - request: protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest, - callback: Callback< - protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + | protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getUserListGlobalLicense( - request?: protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest|undefined, {}|undefined - ]>|void { + | protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + | protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + ( + | protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest + | 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('getUserListGlobalLicense request %j', request); - const wrappedCallback: Callback< - protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + | protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getUserListGlobalLicense response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getUserListGlobalLicense(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ads.datamanager.v1.IUserListGlobalLicense, - protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest|undefined, - {}|undefined - ]) => { - this._log.info('getUserListGlobalLicense response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getUserListGlobalLicense(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IUserListGlobalLicense, + ( + | protos.google.ads.datamanager.v1.IGetUserListGlobalLicenseRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getUserListGlobalLicense response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all user list global licenses owned by the parent account. - * - * This feature is only available to data partners. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The account whose licenses are being queried. Should be in the - * format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} - * @param {string} [request.filter] - * Optional. A [filter string](https://google.aip.dev/160) to apply to the - * list request. All fields need to be on the left hand side of each condition - * (for example: `user_list_id = 123`). Fields must be specified using either - * all [camel case](https://en.wikipedia.org/wiki/Camel_case) or all [snake - * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of - * camel case and snake case. - * - * **Supported Operations:** - * - * - `AND` - * - `=` - * - `!=` - * - `>` - * - `>=` - * - `<` - * - `<=` - * - * **Unsupported Fields:** - * - * - `name` (use get method instead) - * - `historical_pricings` and all its subfields - * - `pricing.start_time` - * - `pricing.end_time` - * @param {number} [request.pageSize] - * Optional. The maximum number of licenses to return. The service may return - * fewer than this value. If unspecified, at most 50 licenses will be - * returned. The maximum value is 1000; values above 1000 will be coerced to - * 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListUserListGlobalLicense` call. Provide this to retrieve the subsequent - * page. - * - * When paginating, all other parameters provided to - * `ListUserListDirectLicense` must match the call that provided the page - * token. - * @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.ads.datamanager.v1.UserListGlobalLicense|UserListGlobalLicense}. - * 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 `listUserListGlobalLicensesAsync()` - * 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 user list global licenses owned by the parent account. + * + * This feature is only available to data partners. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account whose licenses are being queried. Should be in the + * format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + * @param {string} [request.filter] + * Optional. A [filter string](https://google.aip.dev/160) to apply to the + * list request. All fields need to be on the left hand side of each condition + * (for example: `user_list_id = 123`). Fields must be specified using either + * all [camel case](https://en.wikipedia.org/wiki/Camel_case) or all [snake + * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of + * camel case and snake case. + * + * **Supported Operations:** + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * + * **Unsupported Fields:** + * + * - `name` (use get method instead) + * - `historical_pricings` and all its subfields + * - `pricing.start_time` + * - `pricing.end_time` + * @param {number} [request.pageSize] + * Optional. The maximum number of licenses to return. The service may return + * fewer than this value. If unspecified, at most 50 licenses will be + * returned. The maximum value is 1000; values above 1000 will be coerced to + * 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListUserListGlobalLicense` call. Provide this to retrieve the subsequent + * page. + * + * When paginating, all other parameters provided to + * `ListUserListDirectLicense` must match the call that provided the page + * token. + * @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.ads.datamanager.v1.UserListGlobalLicense|UserListGlobalLicense}. + * 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 `listUserListGlobalLicensesAsync()` + * 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. + */ listUserListGlobalLicenses( - request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, - options?: CallOptions): - Promise<[ - protos.google.ads.datamanager.v1.IUserListGlobalLicense[], - protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest|null, - protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse - ]>; + request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserListGlobalLicense[], + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest | null, + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse, + ] + >; listUserListGlobalLicenses( - request: protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, - protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse|null|undefined, - protos.google.ads.datamanager.v1.IUserListGlobalLicense>): void; + request: protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, + | protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IUserListGlobalLicense + >, + ): void; listUserListGlobalLicenses( - request: protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, - callback: PaginationCallback< - protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, - protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse|null|undefined, - protos.google.ads.datamanager.v1.IUserListGlobalLicense>): void; + request: protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, + callback: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, + | protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IUserListGlobalLicense + >, + ): void; listUserListGlobalLicenses( - request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, - protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse|null|undefined, - protos.google.ads.datamanager.v1.IUserListGlobalLicense>, - callback?: PaginationCallback< - protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, - protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse|null|undefined, - protos.google.ads.datamanager.v1.IUserListGlobalLicense>): - Promise<[ - protos.google.ads.datamanager.v1.IUserListGlobalLicense[], - protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest|null, - protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse - ]>|void { + | protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IUserListGlobalLicense + >, + callback?: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, + | protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IUserListGlobalLicense + >, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserListGlobalLicense[], + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest | null, + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse, + ] + > | 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.ads.datamanager.v1.IListUserListGlobalLicensesRequest, - protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse|null|undefined, - protos.google.ads.datamanager.v1.IUserListGlobalLicense>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, + | protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IUserListGlobalLicense + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listUserListGlobalLicenses values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -778,481 +1009,528 @@ export class UserListGlobalLicenseServiceClient { this._log.info('listUserListGlobalLicenses request %j', request); return this.innerApiCalls .listUserListGlobalLicenses(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ads.datamanager.v1.IUserListGlobalLicense[], - protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest|null, - protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse - ]) => { - this._log.info('listUserListGlobalLicenses values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ads.datamanager.v1.IUserListGlobalLicense[], + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest | null, + protos.google.ads.datamanager.v1.IListUserListGlobalLicensesResponse, + ]) => { + this._log.info('listUserListGlobalLicenses values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listUserListGlobalLicenses`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The account whose licenses are being queried. Should be in the - * format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} - * @param {string} [request.filter] - * Optional. A [filter string](https://google.aip.dev/160) to apply to the - * list request. All fields need to be on the left hand side of each condition - * (for example: `user_list_id = 123`). Fields must be specified using either - * all [camel case](https://en.wikipedia.org/wiki/Camel_case) or all [snake - * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of - * camel case and snake case. - * - * **Supported Operations:** - * - * - `AND` - * - `=` - * - `!=` - * - `>` - * - `>=` - * - `<` - * - `<=` - * - * **Unsupported Fields:** - * - * - `name` (use get method instead) - * - `historical_pricings` and all its subfields - * - `pricing.start_time` - * - `pricing.end_time` - * @param {number} [request.pageSize] - * Optional. The maximum number of licenses to return. The service may return - * fewer than this value. If unspecified, at most 50 licenses will be - * returned. The maximum value is 1000; values above 1000 will be coerced to - * 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListUserListGlobalLicense` call. Provide this to retrieve the subsequent - * page. - * - * When paginating, all other parameters provided to - * `ListUserListDirectLicense` must match the call that provided the page - * token. - * @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.ads.datamanager.v1.UserListGlobalLicense|UserListGlobalLicense} 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 `listUserListGlobalLicensesAsync()` - * 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 `listUserListGlobalLicenses`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account whose licenses are being queried. Should be in the + * format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + * @param {string} [request.filter] + * Optional. A [filter string](https://google.aip.dev/160) to apply to the + * list request. All fields need to be on the left hand side of each condition + * (for example: `user_list_id = 123`). Fields must be specified using either + * all [camel case](https://en.wikipedia.org/wiki/Camel_case) or all [snake + * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of + * camel case and snake case. + * + * **Supported Operations:** + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * + * **Unsupported Fields:** + * + * - `name` (use get method instead) + * - `historical_pricings` and all its subfields + * - `pricing.start_time` + * - `pricing.end_time` + * @param {number} [request.pageSize] + * Optional. The maximum number of licenses to return. The service may return + * fewer than this value. If unspecified, at most 50 licenses will be + * returned. The maximum value is 1000; values above 1000 will be coerced to + * 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListUserListGlobalLicense` call. Provide this to retrieve the subsequent + * page. + * + * When paginating, all other parameters provided to + * `ListUserListDirectLicense` must match the call that provided the page + * token. + * @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.ads.datamanager.v1.UserListGlobalLicense|UserListGlobalLicense} 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 `listUserListGlobalLicensesAsync()` + * 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. + */ listUserListGlobalLicensesStream( - request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, + 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['listUserListGlobalLicenses']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listUserListGlobalLicenses stream %j', request); return this.descriptors.page.listUserListGlobalLicenses.createStream( this.innerApiCalls.listUserListGlobalLicenses as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listUserListGlobalLicenses`, 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 account whose licenses are being queried. Should be in the - * format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} - * @param {string} [request.filter] - * Optional. A [filter string](https://google.aip.dev/160) to apply to the - * list request. All fields need to be on the left hand side of each condition - * (for example: `user_list_id = 123`). Fields must be specified using either - * all [camel case](https://en.wikipedia.org/wiki/Camel_case) or all [snake - * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of - * camel case and snake case. - * - * **Supported Operations:** - * - * - `AND` - * - `=` - * - `!=` - * - `>` - * - `>=` - * - `<` - * - `<=` - * - * **Unsupported Fields:** - * - * - `name` (use get method instead) - * - `historical_pricings` and all its subfields - * - `pricing.start_time` - * - `pricing.end_time` - * @param {number} [request.pageSize] - * Optional. The maximum number of licenses to return. The service may return - * fewer than this value. If unspecified, at most 50 licenses will be - * returned. The maximum value is 1000; values above 1000 will be coerced to - * 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListUserListGlobalLicense` call. Provide this to retrieve the subsequent - * page. - * - * When paginating, all other parameters provided to - * `ListUserListDirectLicense` must match the call that provided the 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 protos.google.ads.datamanager.v1.UserListGlobalLicense|UserListGlobalLicense}. 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 include:samples/generated/v1/user_list_global_license_service.list_user_list_global_licenses.js - * region_tag:datamanager_v1_generated_UserListGlobalLicenseService_ListUserListGlobalLicenses_async - */ + /** + * Equivalent to `listUserListGlobalLicenses`, 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 account whose licenses are being queried. Should be in the + * format accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID} + * @param {string} [request.filter] + * Optional. A [filter string](https://google.aip.dev/160) to apply to the + * list request. All fields need to be on the left hand side of each condition + * (for example: `user_list_id = 123`). Fields must be specified using either + * all [camel case](https://en.wikipedia.org/wiki/Camel_case) or all [snake + * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of + * camel case and snake case. + * + * **Supported Operations:** + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * + * **Unsupported Fields:** + * + * - `name` (use get method instead) + * - `historical_pricings` and all its subfields + * - `pricing.start_time` + * - `pricing.end_time` + * @param {number} [request.pageSize] + * Optional. The maximum number of licenses to return. The service may return + * fewer than this value. If unspecified, at most 50 licenses will be + * returned. The maximum value is 1000; values above 1000 will be coerced to + * 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListUserListGlobalLicense` call. Provide this to retrieve the subsequent + * page. + * + * When paginating, all other parameters provided to + * `ListUserListDirectLicense` must match the call that provided the 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 protos.google.ads.datamanager.v1.UserListGlobalLicense|UserListGlobalLicense}. 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 include:samples/generated/v1/user_list_global_license_service.list_user_list_global_licenses.js + * region_tag:datamanager_v1_generated_UserListGlobalLicenseService_ListUserListGlobalLicenses_async + */ listUserListGlobalLicensesAsync( - request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicensesRequest, + 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['listUserListGlobalLicenses']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listUserListGlobalLicenses iterate %j', request); return this.descriptors.page.listUserListGlobalLicenses.asyncIterate( this.innerApiCalls['listUserListGlobalLicenses'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists all customer info for a user list global license. - * - * This feature is only available to data partners. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The global license whose customer info are being queried. Should - * be in the format - * `accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID}/userListGlobalLicenses/{USER_LIST_GLOBAL_LICENSE_ID}`. - * To list all global license customer info under an account, replace the user - * list global license id with a '-' (for example, - * `accountTypes/DATA_PARTNER/accounts/123/userListGlobalLicenses/-`) - * @param {string} [request.filter] - * Optional. A [filter string](https://google.aip.dev/160) to apply to the - * list request. All fields need to be on the left hand side of each condition - * (for example: `user_list_id = 123`). Fields must be specified using either - * all [camel case](https://en.wikipedia.org/wiki/Camel_case) or all [snake - * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of - * camel case and snake case. - * - * **Supported Operations:** - * - * - `AND` - * - `=` - * - `!=` - * - `>` - * - `>=` - * - `<` - * - `<=` - * - * **Unsupported Fields:** - * - * - `name` (use get method instead) - * - `historical_pricings` and all its subfields - * - `pricing.start_time` - * - `pricing.end_time` - * @param {number} [request.pageSize] - * Optional. The maximum number of licenses to return. The service may return - * fewer than this value. If unspecified, at most 50 licenses will be - * returned. The maximum value is 1000; values above 1000 will be coerced to - * 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListUserListDirectLicense` call. Provide this to retrieve the subsequent - * page. - * - * When paginating, all other parameters provided to - * `ListUserListDirectLicense` must match the call that provided the page - * token. - * @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.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo|UserListGlobalLicenseCustomerInfo}. - * 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 `listUserListGlobalLicenseCustomerInfosAsync()` - * 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 customer info for a user list global license. + * + * This feature is only available to data partners. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The global license whose customer info are being queried. Should + * be in the format + * `accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID}/userListGlobalLicenses/{USER_LIST_GLOBAL_LICENSE_ID}`. + * To list all global license customer info under an account, replace the user + * list global license id with a '-' (for example, + * `accountTypes/DATA_PARTNER/accounts/123/userListGlobalLicenses/-`) + * @param {string} [request.filter] + * Optional. A [filter string](https://google.aip.dev/160) to apply to the + * list request. All fields need to be on the left hand side of each condition + * (for example: `user_list_id = 123`). Fields must be specified using either + * all [camel case](https://en.wikipedia.org/wiki/Camel_case) or all [snake + * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of + * camel case and snake case. + * + * **Supported Operations:** + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * + * **Unsupported Fields:** + * + * - `name` (use get method instead) + * - `historical_pricings` and all its subfields + * - `pricing.start_time` + * - `pricing.end_time` + * @param {number} [request.pageSize] + * Optional. The maximum number of licenses to return. The service may return + * fewer than this value. If unspecified, at most 50 licenses will be + * returned. The maximum value is 1000; values above 1000 will be coerced to + * 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListUserListDirectLicense` call. Provide this to retrieve the subsequent + * page. + * + * When paginating, all other parameters provided to + * `ListUserListDirectLicense` must match the call that provided the page + * token. + * @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.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo|UserListGlobalLicenseCustomerInfo}. + * 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 `listUserListGlobalLicenseCustomerInfosAsync()` + * 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. + */ listUserListGlobalLicenseCustomerInfos( - request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, - options?: CallOptions): - Promise<[ - protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo[], - protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest|null, - protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse - ]>; + request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo[], + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest | null, + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse, + ] + >; listUserListGlobalLicenseCustomerInfos( - request: protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, - protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse|null|undefined, - protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo>): void; + request: protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, + | protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo + >, + ): void; listUserListGlobalLicenseCustomerInfos( - request: protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, - callback: PaginationCallback< - protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, - protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse|null|undefined, - protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo>): void; + request: protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, + callback: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, + | protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo + >, + ): void; listUserListGlobalLicenseCustomerInfos( - request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, - protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse|null|undefined, - protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo>, - callback?: PaginationCallback< + request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, - protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse|null|undefined, - protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo>): - Promise<[ - protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo[], - protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest|null, - protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse - ]>|void { + | protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo + >, + callback?: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, + | protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo + >, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo[], + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest | null, + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse, + ] + > | 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.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, - protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse|null|undefined, - protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, + | protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { - this._log.info('listUserListGlobalLicenseCustomerInfos values %j', values); + this._log.info( + 'listUserListGlobalLicenseCustomerInfos values %j', + values, + ); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. } : undefined; - this._log.info('listUserListGlobalLicenseCustomerInfos request %j', request); + this._log.info( + 'listUserListGlobalLicenseCustomerInfos request %j', + request, + ); return this.innerApiCalls .listUserListGlobalLicenseCustomerInfos(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo[], - protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest|null, - protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse - ]) => { - this._log.info('listUserListGlobalLicenseCustomerInfos values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo[], + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest | null, + protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosResponse, + ]) => { + this._log.info( + 'listUserListGlobalLicenseCustomerInfos values %j', + response, + ); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listUserListGlobalLicenseCustomerInfos`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The global license whose customer info are being queried. Should - * be in the format - * `accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID}/userListGlobalLicenses/{USER_LIST_GLOBAL_LICENSE_ID}`. - * To list all global license customer info under an account, replace the user - * list global license id with a '-' (for example, - * `accountTypes/DATA_PARTNER/accounts/123/userListGlobalLicenses/-`) - * @param {string} [request.filter] - * Optional. A [filter string](https://google.aip.dev/160) to apply to the - * list request. All fields need to be on the left hand side of each condition - * (for example: `user_list_id = 123`). Fields must be specified using either - * all [camel case](https://en.wikipedia.org/wiki/Camel_case) or all [snake - * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of - * camel case and snake case. - * - * **Supported Operations:** - * - * - `AND` - * - `=` - * - `!=` - * - `>` - * - `>=` - * - `<` - * - `<=` - * - * **Unsupported Fields:** - * - * - `name` (use get method instead) - * - `historical_pricings` and all its subfields - * - `pricing.start_time` - * - `pricing.end_time` - * @param {number} [request.pageSize] - * Optional. The maximum number of licenses to return. The service may return - * fewer than this value. If unspecified, at most 50 licenses will be - * returned. The maximum value is 1000; values above 1000 will be coerced to - * 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListUserListDirectLicense` call. Provide this to retrieve the subsequent - * page. - * - * When paginating, all other parameters provided to - * `ListUserListDirectLicense` must match the call that provided the page - * token. - * @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.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo|UserListGlobalLicenseCustomerInfo} 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 `listUserListGlobalLicenseCustomerInfosAsync()` - * 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 `listUserListGlobalLicenseCustomerInfos`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The global license whose customer info are being queried. Should + * be in the format + * `accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID}/userListGlobalLicenses/{USER_LIST_GLOBAL_LICENSE_ID}`. + * To list all global license customer info under an account, replace the user + * list global license id with a '-' (for example, + * `accountTypes/DATA_PARTNER/accounts/123/userListGlobalLicenses/-`) + * @param {string} [request.filter] + * Optional. A [filter string](https://google.aip.dev/160) to apply to the + * list request. All fields need to be on the left hand side of each condition + * (for example: `user_list_id = 123`). Fields must be specified using either + * all [camel case](https://en.wikipedia.org/wiki/Camel_case) or all [snake + * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of + * camel case and snake case. + * + * **Supported Operations:** + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * + * **Unsupported Fields:** + * + * - `name` (use get method instead) + * - `historical_pricings` and all its subfields + * - `pricing.start_time` + * - `pricing.end_time` + * @param {number} [request.pageSize] + * Optional. The maximum number of licenses to return. The service may return + * fewer than this value. If unspecified, at most 50 licenses will be + * returned. The maximum value is 1000; values above 1000 will be coerced to + * 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListUserListDirectLicense` call. Provide this to retrieve the subsequent + * page. + * + * When paginating, all other parameters provided to + * `ListUserListDirectLicense` must match the call that provided the page + * token. + * @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.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo|UserListGlobalLicenseCustomerInfo} 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 `listUserListGlobalLicenseCustomerInfosAsync()` + * 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. + */ listUserListGlobalLicenseCustomerInfosStream( - request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, + 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 ?? '', - }); - const defaultCallSettings = this._defaults['listUserListGlobalLicenseCustomerInfos']; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = + this._defaults['listUserListGlobalLicenseCustomerInfos']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listUserListGlobalLicenseCustomerInfos stream %j', request); return this.descriptors.page.listUserListGlobalLicenseCustomerInfos.createStream( this.innerApiCalls.listUserListGlobalLicenseCustomerInfos as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listUserListGlobalLicenseCustomerInfos`, 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 global license whose customer info are being queried. Should - * be in the format - * `accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID}/userListGlobalLicenses/{USER_LIST_GLOBAL_LICENSE_ID}`. - * To list all global license customer info under an account, replace the user - * list global license id with a '-' (for example, - * `accountTypes/DATA_PARTNER/accounts/123/userListGlobalLicenses/-`) - * @param {string} [request.filter] - * Optional. A [filter string](https://google.aip.dev/160) to apply to the - * list request. All fields need to be on the left hand side of each condition - * (for example: `user_list_id = 123`). Fields must be specified using either - * all [camel case](https://en.wikipedia.org/wiki/Camel_case) or all [snake - * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of - * camel case and snake case. - * - * **Supported Operations:** - * - * - `AND` - * - `=` - * - `!=` - * - `>` - * - `>=` - * - `<` - * - `<=` - * - * **Unsupported Fields:** - * - * - `name` (use get method instead) - * - `historical_pricings` and all its subfields - * - `pricing.start_time` - * - `pricing.end_time` - * @param {number} [request.pageSize] - * Optional. The maximum number of licenses to return. The service may return - * fewer than this value. If unspecified, at most 50 licenses will be - * returned. The maximum value is 1000; values above 1000 will be coerced to - * 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListUserListDirectLicense` call. Provide this to retrieve the subsequent - * page. - * - * When paginating, all other parameters provided to - * `ListUserListDirectLicense` must match the call that provided the 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 protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo|UserListGlobalLicenseCustomerInfo}. 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 include:samples/generated/v1/user_list_global_license_service.list_user_list_global_license_customer_infos.js - * region_tag:datamanager_v1_generated_UserListGlobalLicenseService_ListUserListGlobalLicenseCustomerInfos_async - */ + /** + * Equivalent to `listUserListGlobalLicenseCustomerInfos`, 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 global license whose customer info are being queried. Should + * be in the format + * `accountTypes/{ACCOUNT_TYPE}/accounts/{ACCOUNT_ID}/userListGlobalLicenses/{USER_LIST_GLOBAL_LICENSE_ID}`. + * To list all global license customer info under an account, replace the user + * list global license id with a '-' (for example, + * `accountTypes/DATA_PARTNER/accounts/123/userListGlobalLicenses/-`) + * @param {string} [request.filter] + * Optional. A [filter string](https://google.aip.dev/160) to apply to the + * list request. All fields need to be on the left hand side of each condition + * (for example: `user_list_id = 123`). Fields must be specified using either + * all [camel case](https://en.wikipedia.org/wiki/Camel_case) or all [snake + * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of + * camel case and snake case. + * + * **Supported Operations:** + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * + * **Unsupported Fields:** + * + * - `name` (use get method instead) + * - `historical_pricings` and all its subfields + * - `pricing.start_time` + * - `pricing.end_time` + * @param {number} [request.pageSize] + * Optional. The maximum number of licenses to return. The service may return + * fewer than this value. If unspecified, at most 50 licenses will be + * returned. The maximum value is 1000; values above 1000 will be coerced to + * 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListUserListDirectLicense` call. Provide this to retrieve the subsequent + * page. + * + * When paginating, all other parameters provided to + * `ListUserListDirectLicense` must match the call that provided the 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 protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo|UserListGlobalLicenseCustomerInfo}. 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 include:samples/generated/v1/user_list_global_license_service.list_user_list_global_license_customer_infos.js + * region_tag:datamanager_v1_generated_UserListGlobalLicenseService_ListUserListGlobalLicenseCustomerInfos_async + */ listUserListGlobalLicenseCustomerInfosAsync( - request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ads.datamanager.v1.IListUserListGlobalLicenseCustomerInfosRequest, + 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 ?? '', - }); - const defaultCallSettings = this._defaults['listUserListGlobalLicenseCustomerInfos']; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = + this._defaults['listUserListGlobalLicenseCustomerInfos']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); - this._log.info('listUserListGlobalLicenseCustomerInfos iterate %j', request); + this.initialize().catch((err) => { + throw err; + }); + this._log.info( + 'listUserListGlobalLicenseCustomerInfos iterate %j', + request, + ); return this.descriptors.page.listUserListGlobalLicenseCustomerInfos.asyncIterate( this.innerApiCalls['listUserListGlobalLicenseCustomerInfos'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1266,7 +1544,7 @@ export class UserListGlobalLicenseServiceClient { * @param {string} account * @returns {string} Resource name string. */ - accountPath(accountType:string,account:string) { + accountPath(accountType: string, account: string) { return this.pathTemplates.accountPathTemplate.render({ account_type: accountType, account: account, @@ -1281,7 +1559,8 @@ export class UserListGlobalLicenseServiceClient { * @returns {string} A string representing the account_type. */ matchAccountTypeFromAccountName(accountName: string) { - return this.pathTemplates.accountPathTemplate.match(accountName).account_type; + return this.pathTemplates.accountPathTemplate.match(accountName) + .account_type; } /** @@ -1303,7 +1582,7 @@ export class UserListGlobalLicenseServiceClient { * @param {string} partner_link * @returns {string} Resource name string. */ - partnerLinkPath(accountType:string,account:string,partnerLink:string) { + partnerLinkPath(accountType: string, account: string, partnerLink: string) { return this.pathTemplates.partnerLinkPathTemplate.render({ account_type: accountType, account: account, @@ -1319,7 +1598,8 @@ export class UserListGlobalLicenseServiceClient { * @returns {string} A string representing the account_type. */ matchAccountTypeFromPartnerLinkName(partnerLinkName: string) { - return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account_type; + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName) + .account_type; } /** @@ -1330,7 +1610,8 @@ export class UserListGlobalLicenseServiceClient { * @returns {string} A string representing the account. */ matchAccountFromPartnerLinkName(partnerLinkName: string) { - return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account; + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName) + .account; } /** @@ -1341,7 +1622,8 @@ export class UserListGlobalLicenseServiceClient { * @returns {string} A string representing the partner_link. */ matchPartnerLinkFromPartnerLinkName(partnerLinkName: string) { - return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).partner_link; + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName) + .partner_link; } /** @@ -1352,7 +1634,7 @@ export class UserListGlobalLicenseServiceClient { * @param {string} user_list * @returns {string} Resource name string. */ - userListPath(accountType:string,account:string,userList:string) { + userListPath(accountType: string, account: string, userList: string) { return this.pathTemplates.userListPathTemplate.render({ account_type: accountType, account: account, @@ -1368,7 +1650,8 @@ export class UserListGlobalLicenseServiceClient { * @returns {string} A string representing the account_type. */ matchAccountTypeFromUserListName(userListName: string) { - return this.pathTemplates.userListPathTemplate.match(userListName).account_type; + return this.pathTemplates.userListPathTemplate.match(userListName) + .account_type; } /** @@ -1390,7 +1673,8 @@ export class UserListGlobalLicenseServiceClient { * @returns {string} A string representing the user_list. */ matchUserListFromUserListName(userListName: string) { - return this.pathTemplates.userListPathTemplate.match(userListName).user_list; + return this.pathTemplates.userListPathTemplate.match(userListName) + .user_list; } /** @@ -1401,7 +1685,11 @@ export class UserListGlobalLicenseServiceClient { * @param {string} user_list_direct_license * @returns {string} Resource name string. */ - userListDirectLicensePath(accountType:string,account:string,userListDirectLicense:string) { + userListDirectLicensePath( + accountType: string, + account: string, + userListDirectLicense: string, + ) { return this.pathTemplates.userListDirectLicensePathTemplate.render({ account_type: accountType, account: account, @@ -1416,8 +1704,12 @@ export class UserListGlobalLicenseServiceClient { * A fully-qualified path representing UserListDirectLicense resource. * @returns {string} A string representing the account_type. */ - matchAccountTypeFromUserListDirectLicenseName(userListDirectLicenseName: string) { - return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account_type; + matchAccountTypeFromUserListDirectLicenseName( + userListDirectLicenseName: string, + ) { + return this.pathTemplates.userListDirectLicensePathTemplate.match( + userListDirectLicenseName, + ).account_type; } /** @@ -1428,7 +1720,9 @@ export class UserListGlobalLicenseServiceClient { * @returns {string} A string representing the account. */ matchAccountFromUserListDirectLicenseName(userListDirectLicenseName: string) { - return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account; + return this.pathTemplates.userListDirectLicensePathTemplate.match( + userListDirectLicenseName, + ).account; } /** @@ -1438,8 +1732,12 @@ export class UserListGlobalLicenseServiceClient { * A fully-qualified path representing UserListDirectLicense resource. * @returns {string} A string representing the user_list_direct_license. */ - matchUserListDirectLicenseFromUserListDirectLicenseName(userListDirectLicenseName: string) { - return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).user_list_direct_license; + matchUserListDirectLicenseFromUserListDirectLicenseName( + userListDirectLicenseName: string, + ) { + return this.pathTemplates.userListDirectLicensePathTemplate.match( + userListDirectLicenseName, + ).user_list_direct_license; } /** @@ -1450,7 +1748,11 @@ export class UserListGlobalLicenseServiceClient { * @param {string} user_list_global_license * @returns {string} Resource name string. */ - userListGlobalLicensePath(accountType:string,account:string,userListGlobalLicense:string) { + userListGlobalLicensePath( + accountType: string, + account: string, + userListGlobalLicense: string, + ) { return this.pathTemplates.userListGlobalLicensePathTemplate.render({ account_type: accountType, account: account, @@ -1465,8 +1767,12 @@ export class UserListGlobalLicenseServiceClient { * A fully-qualified path representing UserListGlobalLicense resource. * @returns {string} A string representing the account_type. */ - matchAccountTypeFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { - return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account_type; + matchAccountTypeFromUserListGlobalLicenseName( + userListGlobalLicenseName: string, + ) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match( + userListGlobalLicenseName, + ).account_type; } /** @@ -1477,7 +1783,9 @@ export class UserListGlobalLicenseServiceClient { * @returns {string} A string representing the account. */ matchAccountFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { - return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account; + return this.pathTemplates.userListGlobalLicensePathTemplate.match( + userListGlobalLicenseName, + ).account; } /** @@ -1487,8 +1795,12 @@ export class UserListGlobalLicenseServiceClient { * A fully-qualified path representing UserListGlobalLicense resource. * @returns {string} A string representing the user_list_global_license. */ - matchUserListGlobalLicenseFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { - return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).user_list_global_license; + matchUserListGlobalLicenseFromUserListGlobalLicenseName( + userListGlobalLicenseName: string, + ) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match( + userListGlobalLicenseName, + ).user_list_global_license; } /** @@ -1500,13 +1812,20 @@ export class UserListGlobalLicenseServiceClient { * @param {string} license_customer_info * @returns {string} Resource name string. */ - userListGlobalLicenseCustomerInfoPath(accountType:string,account:string,userListGlobalLicense:string,licenseCustomerInfo:string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render({ - account_type: accountType, - account: account, - user_list_global_license: userListGlobalLicense, - license_customer_info: licenseCustomerInfo, - }); + userListGlobalLicenseCustomerInfoPath( + accountType: string, + account: string, + userListGlobalLicense: string, + licenseCustomerInfo: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render( + { + account_type: accountType, + account: account, + user_list_global_license: userListGlobalLicense, + license_customer_info: licenseCustomerInfo, + }, + ); } /** @@ -1516,8 +1835,12 @@ export class UserListGlobalLicenseServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the account_type. */ - matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account_type; + matchAccountTypeFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).account_type; } /** @@ -1527,8 +1850,12 @@ export class UserListGlobalLicenseServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the account. */ - matchAccountFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account; + matchAccountFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).account; } /** @@ -1538,8 +1865,12 @@ export class UserListGlobalLicenseServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the user_list_global_license. */ - matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).user_list_global_license; + matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).user_list_global_license; } /** @@ -1549,8 +1880,12 @@ export class UserListGlobalLicenseServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the license_customer_info. */ - matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).license_customer_info; + matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).license_customer_info; } /** @@ -1561,7 +1896,7 @@ export class UserListGlobalLicenseServiceClient { */ close(): Promise { if (this.userListGlobalLicenseServiceStub && !this._terminated) { - return this.userListGlobalLicenseServiceStub.then(stub => { + return this.userListGlobalLicenseServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1569,4 +1904,4 @@ export class UserListGlobalLicenseServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ads-datamanager/src/v1/user_list_service_client.ts b/packages/google-ads-datamanager/src/v1/user_list_service_client.ts index 6bdc92809b02..e5b30af5cfa2 100644 --- a/packages/google-ads-datamanager/src/v1/user_list_service_client.ts +++ b/packages/google-ads-datamanager/src/v1/user_list_service_client.ts @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class UserListServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('datamanager'); @@ -57,9 +64,9 @@ export class UserListServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - userListServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + userListServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of UserListServiceClient. @@ -100,21 +107,42 @@ export class UserListServiceClient { * const client = new UserListServiceClient({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 UserListServiceClient; - 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 = 'datamanager.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -139,7 +167,7 @@ export class UserListServiceClient { 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; @@ -153,10 +181,7 @@ export class UserListServiceClient { } // 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 { @@ -178,37 +203,44 @@ export class UserListServiceClient { // Create useful helper objects for these. this.pathTemplates = { accountPathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}' + 'accountTypes/{account_type}/accounts/{account}', ), partnerLinkPathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link}' + 'accountTypes/{account_type}/accounts/{account}/partnerLinks/{partner_link}', ), userListPathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userLists/{user_list}' + 'accountTypes/{account_type}/accounts/{account}/userLists/{user_list}', ), userListDirectLicensePathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userListDirectLicenses/{user_list_direct_license}' + 'accountTypes/{account_type}/accounts/{account}/userListDirectLicenses/{user_list_direct_license}', ), userListGlobalLicensePathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}' - ), - userListGlobalLicenseCustomerInfoPathTemplate: new this._gaxModule.PathTemplate( - 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}/customerInfos/{license_customer_info}' + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}', ), + userListGlobalLicenseCustomerInfoPathTemplate: + new this._gaxModule.PathTemplate( + 'accountTypes/{account_type}/accounts/{account}/userListGlobalLicenses/{user_list_global_license}/customerInfos/{license_customer_info}', + ), }; // 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 = { - listUserLists: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'userLists') + listUserLists: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'userLists', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ads.datamanager.v1.UserListService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ads.datamanager.v1.UserListService', + 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,37 +271,46 @@ export class UserListServiceClient { // Put together the "service stub" for // google.ads.datamanager.v1.UserListService. this.userListServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ads.datamanager.v1.UserListService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ads.datamanager.v1.UserListService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.ads.datamanager.v1.UserListService, - 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 userListServiceStubMethods = - ['getUserList', 'listUserLists', 'createUserList', 'updateUserList', 'deleteUserList']; + const userListServiceStubMethods = [ + 'getUserList', + 'listUserLists', + 'createUserList', + 'updateUserList', + 'deleteUserList', + ]; for (const methodName of userListServiceStubMethods) { const callPromise = this.userListServiceStub.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] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -284,8 +325,14 @@ export class UserListServiceClient { * @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 'datamanager.googleapis.com'; } @@ -296,8 +343,14 @@ export class UserListServiceClient { * @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 'datamanager.googleapis.com'; } @@ -328,9 +381,7 @@ export class UserListServiceClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/datamanager' - ]; + return ['https://www.googleapis.com/auth/datamanager']; } getProjectId(): Promise; @@ -339,8 +390,9 @@ export class UserListServiceClient { * 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; @@ -351,584 +403,763 @@ export class UserListServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets a UserList. - * - * Authorization Headers: - * - * This method supports the following optional headers to define how the API - * authorizes access for the request: - * - * * `login-account`: (Optional) The resource name of the account where the - * Google Account of the credentials is a user. If not set, defaults to the - * account of the request. Format: - * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` - * * `linked-account`: (Optional) The resource name of the account with an - * established product link to the `login-account`. Format: - * `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the UserList to retrieve. - * Format: - * accountTypes/{account_type}/accounts/{account}/userLists/{user_list} - * @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.ads.datamanager.v1.UserList|UserList}. - * 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/user_list_service.get_user_list.js - * region_tag:datamanager_v1_generated_UserListService_GetUserList_async - */ + /** + * Gets a UserList. + * + * Authorization Headers: + * + * This method supports the following optional headers to define how the API + * authorizes access for the request: + * + * * `login-account`: (Optional) The resource name of the account where the + * Google Account of the credentials is a user. If not set, defaults to the + * account of the request. Format: + * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + * * `linked-account`: (Optional) The resource name of the account with an + * established product link to the `login-account`. Format: + * `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the UserList to retrieve. + * Format: + * accountTypes/{account_type}/accounts/{account}/userLists/{user_list} + * @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.ads.datamanager.v1.UserList|UserList}. + * 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/user_list_service.get_user_list.js + * region_tag:datamanager_v1_generated_UserListService_GetUserList_async + */ getUserList( - request?: protos.google.ads.datamanager.v1.IGetUserListRequest, - options?: CallOptions): - Promise<[ - protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.IGetUserListRequest|undefined, {}|undefined - ]>; + request?: protos.google.ads.datamanager.v1.IGetUserListRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IGetUserListRequest | undefined, + {} | undefined, + ] + >; getUserList( - request: protos.google.ads.datamanager.v1.IGetUserListRequest, - options: CallOptions, - callback: Callback< - protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.IGetUserListRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IGetUserListRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IGetUserListRequest | null | undefined, + {} | null | undefined + >, + ): void; getUserList( - request: protos.google.ads.datamanager.v1.IGetUserListRequest, - callback: Callback< - protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.IGetUserListRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IGetUserListRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IGetUserListRequest | null | undefined, + {} | null | undefined + >, + ): void; getUserList( - request?: protos.google.ads.datamanager.v1.IGetUserListRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.IGetUserListRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ads.datamanager.v1.IGetUserListRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.IGetUserListRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.IGetUserListRequest|undefined, {}|undefined - ]>|void { + | protos.google.ads.datamanager.v1.IGetUserListRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IGetUserListRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IGetUserListRequest | 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('getUserList request %j', request); - const wrappedCallback: Callback< - protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.IGetUserListRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ads.datamanager.v1.IUserList, + | protos.google.ads.datamanager.v1.IGetUserListRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getUserList response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getUserList(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.IGetUserListRequest|undefined, - {}|undefined - ]) => { - this._log.info('getUserList response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getUserList(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IGetUserListRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getUserList response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a UserList. - * - * Authorization Headers: - * - * This method supports the following optional headers to define how the API - * authorizes access for the request: - * - * * `login-account`: (Optional) The resource name of the account where the - * Google Account of the credentials is a user. If not set, defaults to the - * account of the request. Format: - * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` - * * `linked-account`: (Optional) The resource name of the account with an - * established product link to the `login-account`. Format: - * `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent account where this user list will be created. - * Format: accountTypes/{account_type}/accounts/{account} - * @param {google.ads.datamanager.v1.UserList} request.userList - * Required. The user list to create. - * @param {boolean} [request.validateOnly] - * Optional. If true, the request is validated but not executed. - * @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.ads.datamanager.v1.UserList|UserList}. - * 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/user_list_service.create_user_list.js - * region_tag:datamanager_v1_generated_UserListService_CreateUserList_async - */ + /** + * Creates a UserList. + * + * Authorization Headers: + * + * This method supports the following optional headers to define how the API + * authorizes access for the request: + * + * * `login-account`: (Optional) The resource name of the account where the + * Google Account of the credentials is a user. If not set, defaults to the + * account of the request. Format: + * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + * * `linked-account`: (Optional) The resource name of the account with an + * established product link to the `login-account`. Format: + * `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent account where this user list will be created. + * Format: accountTypes/{account_type}/accounts/{account} + * @param {google.ads.datamanager.v1.UserList} request.userList + * Required. The user list to create. + * @param {boolean} [request.validateOnly] + * Optional. If true, the request is validated but not executed. + * @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.ads.datamanager.v1.UserList|UserList}. + * 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/user_list_service.create_user_list.js + * region_tag:datamanager_v1_generated_UserListService_CreateUserList_async + */ createUserList( - request?: protos.google.ads.datamanager.v1.ICreateUserListRequest, - options?: CallOptions): - Promise<[ - protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.ICreateUserListRequest|undefined, {}|undefined - ]>; + request?: protos.google.ads.datamanager.v1.ICreateUserListRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.ICreateUserListRequest | undefined, + {} | undefined, + ] + >; createUserList( - request: protos.google.ads.datamanager.v1.ICreateUserListRequest, - options: CallOptions, - callback: Callback< - protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.ICreateUserListRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.ICreateUserListRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IUserList, + | protos.google.ads.datamanager.v1.ICreateUserListRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createUserList( - request: protos.google.ads.datamanager.v1.ICreateUserListRequest, - callback: Callback< - protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.ICreateUserListRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.ICreateUserListRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IUserList, + | protos.google.ads.datamanager.v1.ICreateUserListRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createUserList( - request?: protos.google.ads.datamanager.v1.ICreateUserListRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ads.datamanager.v1.ICreateUserListRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.ICreateUserListRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.ICreateUserListRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.ICreateUserListRequest|undefined, {}|undefined - ]>|void { + | protos.google.ads.datamanager.v1.ICreateUserListRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ads.datamanager.v1.IUserList, + | protos.google.ads.datamanager.v1.ICreateUserListRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.ICreateUserListRequest | 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('createUserList request %j', request); - const wrappedCallback: Callback< - protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.ICreateUserListRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ads.datamanager.v1.IUserList, + | protos.google.ads.datamanager.v1.ICreateUserListRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createUserList response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createUserList(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.ICreateUserListRequest|undefined, - {}|undefined - ]) => { - this._log.info('createUserList response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createUserList(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.ICreateUserListRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createUserList response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a UserList. - * - * Authorization Headers: - * - * This method supports the following optional headers to define how the API - * authorizes access for the request: - * - * * `login-account`: (Optional) The resource name of the account where the - * Google Account of the credentials is a user. If not set, defaults to the - * account of the request. Format: - * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` - * * `linked-account`: (Optional) The resource name of the account with an - * established product link to the `login-account`. Format: - * `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ads.datamanager.v1.UserList} request.userList - * Required. The user list to update. - * - * The user list's `name` field is used to identify the user list to update. - * Format: - * accountTypes/{account_type}/accounts/{account}/userLists/{user_list} - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. The list of fields to update. - * @param {boolean} [request.validateOnly] - * Optional. If true, the request is validated but not executed. - * @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.ads.datamanager.v1.UserList|UserList}. - * 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/user_list_service.update_user_list.js - * region_tag:datamanager_v1_generated_UserListService_UpdateUserList_async - */ + /** + * Updates a UserList. + * + * Authorization Headers: + * + * This method supports the following optional headers to define how the API + * authorizes access for the request: + * + * * `login-account`: (Optional) The resource name of the account where the + * Google Account of the credentials is a user. If not set, defaults to the + * account of the request. Format: + * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + * * `linked-account`: (Optional) The resource name of the account with an + * established product link to the `login-account`. Format: + * `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ads.datamanager.v1.UserList} request.userList + * Required. The user list to update. + * + * The user list's `name` field is used to identify the user list to update. + * Format: + * accountTypes/{account_type}/accounts/{account}/userLists/{user_list} + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. The list of fields to update. + * @param {boolean} [request.validateOnly] + * Optional. If true, the request is validated but not executed. + * @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.ads.datamanager.v1.UserList|UserList}. + * 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/user_list_service.update_user_list.js + * region_tag:datamanager_v1_generated_UserListService_UpdateUserList_async + */ updateUserList( - request?: protos.google.ads.datamanager.v1.IUpdateUserListRequest, - options?: CallOptions): - Promise<[ - protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.IUpdateUserListRequest|undefined, {}|undefined - ]>; + request?: protos.google.ads.datamanager.v1.IUpdateUserListRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IUpdateUserListRequest | undefined, + {} | undefined, + ] + >; updateUserList( - request: protos.google.ads.datamanager.v1.IUpdateUserListRequest, - options: CallOptions, - callback: Callback< - protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.IUpdateUserListRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IUpdateUserListRequest, + options: CallOptions, + callback: Callback< + protos.google.ads.datamanager.v1.IUserList, + | protos.google.ads.datamanager.v1.IUpdateUserListRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateUserList( - request: protos.google.ads.datamanager.v1.IUpdateUserListRequest, - callback: Callback< - protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.IUpdateUserListRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IUpdateUserListRequest, + callback: Callback< + protos.google.ads.datamanager.v1.IUserList, + | protos.google.ads.datamanager.v1.IUpdateUserListRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateUserList( - request?: protos.google.ads.datamanager.v1.IUpdateUserListRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ads.datamanager.v1.IUpdateUserListRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.IUpdateUserListRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.IUpdateUserListRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.IUpdateUserListRequest|undefined, {}|undefined - ]>|void { + | protos.google.ads.datamanager.v1.IUpdateUserListRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ads.datamanager.v1.IUserList, + | protos.google.ads.datamanager.v1.IUpdateUserListRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IUpdateUserListRequest | 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({ - 'user_list.name': request.userList!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'user_list.name': request.userList!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateUserList request %j', request); - const wrappedCallback: Callback< - protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.IUpdateUserListRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ads.datamanager.v1.IUserList, + | protos.google.ads.datamanager.v1.IUpdateUserListRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateUserList response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateUserList(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ads.datamanager.v1.IUserList, - protos.google.ads.datamanager.v1.IUpdateUserListRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateUserList response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateUserList(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ads.datamanager.v1.IUserList, + protos.google.ads.datamanager.v1.IUpdateUserListRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateUserList response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a UserList. - * - * Authorization Headers: - * - * This method supports the following optional headers to define how the API - * authorizes access for the request: - * - * * `login-account`: (Optional) The resource name of the account where the - * Google Account of the credentials is a user. If not set, defaults to the - * account of the request. Format: - * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` - * * `linked-account`: (Optional) The resource name of the account with an - * established product link to the `login-account`. Format: - * `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the user list to delete. - * Format: - * accountTypes/{account_type}/accounts/{account}/userLists/{user_list} - * @param {boolean} [request.validateOnly] - * Optional. If true, the request is validated but not executed. - * @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/user_list_service.delete_user_list.js - * region_tag:datamanager_v1_generated_UserListService_DeleteUserList_async - */ + /** + * Deletes a UserList. + * + * Authorization Headers: + * + * This method supports the following optional headers to define how the API + * authorizes access for the request: + * + * * `login-account`: (Optional) The resource name of the account where the + * Google Account of the credentials is a user. If not set, defaults to the + * account of the request. Format: + * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + * * `linked-account`: (Optional) The resource name of the account with an + * established product link to the `login-account`. Format: + * `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the user list to delete. + * Format: + * accountTypes/{account_type}/accounts/{account}/userLists/{user_list} + * @param {boolean} [request.validateOnly] + * Optional. If true, the request is validated but not executed. + * @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/user_list_service.delete_user_list.js + * region_tag:datamanager_v1_generated_UserListService_DeleteUserList_async + */ deleteUserList( - request?: protos.google.ads.datamanager.v1.IDeleteUserListRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ads.datamanager.v1.IDeleteUserListRequest|undefined, {}|undefined - ]>; + request?: protos.google.ads.datamanager.v1.IDeleteUserListRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.ads.datamanager.v1.IDeleteUserListRequest | undefined, + {} | undefined, + ] + >; deleteUserList( - request: protos.google.ads.datamanager.v1.IDeleteUserListRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ads.datamanager.v1.IDeleteUserListRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IDeleteUserListRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ads.datamanager.v1.IDeleteUserListRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteUserList( - request: protos.google.ads.datamanager.v1.IDeleteUserListRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ads.datamanager.v1.IDeleteUserListRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ads.datamanager.v1.IDeleteUserListRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ads.datamanager.v1.IDeleteUserListRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteUserList( - request?: protos.google.ads.datamanager.v1.IDeleteUserListRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ads.datamanager.v1.IDeleteUserListRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.ads.datamanager.v1.IDeleteUserListRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.ads.datamanager.v1.IDeleteUserListRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ads.datamanager.v1.IDeleteUserListRequest|undefined, {}|undefined - ]>|void { + | protos.google.ads.datamanager.v1.IDeleteUserListRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ads.datamanager.v1.IDeleteUserListRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.ads.datamanager.v1.IDeleteUserListRequest | 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('deleteUserList request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ads.datamanager.v1.IDeleteUserListRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.ads.datamanager.v1.IDeleteUserListRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteUserList response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteUserList(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.ads.datamanager.v1.IDeleteUserListRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteUserList response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteUserList(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.ads.datamanager.v1.IDeleteUserListRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteUserList response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists UserLists. - * - * Authorization Headers: - * - * This method supports the following optional headers to define how the API - * authorizes access for the request: - * - * * `login-account`: (Optional) The resource name of the account where the - * Google Account of the credentials is a user. If not set, defaults to the - * account of the request. Format: - * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` - * * `linked-account`: (Optional) The resource name of the account with an - * established product link to the `login-account`. Format: - * `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent account which owns this collection of user lists. - * Format: accountTypes/{account_type}/accounts/{account} - * @param {number} [request.pageSize] - * Optional. The maximum number of user lists to return. The service may - * return fewer than this value. If unspecified, at most 50 user lists will be - * returned. The maximum value is 1000; values above 1000 will be coerced to - * 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListUserLists` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListUserLists` must - * match the call that provided the page token. - * @param {string} [request.filter] - * Optional. A [filter string](https://google.aip.dev/160). All fields need to - * be on the left hand side of each condition (for example: `display_name = - * "list 1"`). Fields must be specified using either all [camel - * case](https://en.wikipedia.org/wiki/Camel_case) or all [snake - * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of - * camel case and snake case. - * - * Supported operations: - * - * - `AND` - * - `=` - * - `!=` - * - `>` - * - `>=` - * - `<` - * - `<=` - * - `:` (has) - * - * Supported fields: - * - * - `id` - * - `display_name` - * - `description` - * - `membership_status` - * - `integration_code` - * - `access_reason` - * - `ingested_user_list_info.upload_key_types` - * @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.ads.datamanager.v1.UserList|UserList}. - * 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 `listUserListsAsync()` - * 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 UserLists. + * + * Authorization Headers: + * + * This method supports the following optional headers to define how the API + * authorizes access for the request: + * + * * `login-account`: (Optional) The resource name of the account where the + * Google Account of the credentials is a user. If not set, defaults to the + * account of the request. Format: + * `accountTypes/{loginAccountType}/accounts/{loginAccountId}` + * * `linked-account`: (Optional) The resource name of the account with an + * established product link to the `login-account`. Format: + * `accountTypes/{linkedAccountType}/accounts/{linkedAccountId}` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent account which owns this collection of user lists. + * Format: accountTypes/{account_type}/accounts/{account} + * @param {number} [request.pageSize] + * Optional. The maximum number of user lists to return. The service may + * return fewer than this value. If unspecified, at most 50 user lists will be + * returned. The maximum value is 1000; values above 1000 will be coerced to + * 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListUserLists` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListUserLists` must + * match the call that provided the page token. + * @param {string} [request.filter] + * Optional. A [filter string](https://google.aip.dev/160). All fields need to + * be on the left hand side of each condition (for example: `display_name = + * "list 1"`). Fields must be specified using either all [camel + * case](https://en.wikipedia.org/wiki/Camel_case) or all [snake + * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of + * camel case and snake case. + * + * Supported operations: + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * - `:` (has) + * + * Supported fields: + * + * - `id` + * - `display_name` + * - `description` + * - `membership_status` + * - `integration_code` + * - `access_reason` + * - `ingested_user_list_info.upload_key_types` + * @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.ads.datamanager.v1.UserList|UserList}. + * 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 `listUserListsAsync()` + * 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. + */ listUserLists( - request?: protos.google.ads.datamanager.v1.IListUserListsRequest, - options?: CallOptions): - Promise<[ - protos.google.ads.datamanager.v1.IUserList[], - protos.google.ads.datamanager.v1.IListUserListsRequest|null, - protos.google.ads.datamanager.v1.IListUserListsResponse - ]>; + request?: protos.google.ads.datamanager.v1.IListUserListsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserList[], + protos.google.ads.datamanager.v1.IListUserListsRequest | null, + protos.google.ads.datamanager.v1.IListUserListsResponse, + ] + >; listUserLists( - request: protos.google.ads.datamanager.v1.IListUserListsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ads.datamanager.v1.IListUserListsRequest, - protos.google.ads.datamanager.v1.IListUserListsResponse|null|undefined, - protos.google.ads.datamanager.v1.IUserList>): void; + request: protos.google.ads.datamanager.v1.IListUserListsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListsRequest, + | protos.google.ads.datamanager.v1.IListUserListsResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IUserList + >, + ): void; listUserLists( - request: protos.google.ads.datamanager.v1.IListUserListsRequest, - callback: PaginationCallback< - protos.google.ads.datamanager.v1.IListUserListsRequest, - protos.google.ads.datamanager.v1.IListUserListsResponse|null|undefined, - protos.google.ads.datamanager.v1.IUserList>): void; + request: protos.google.ads.datamanager.v1.IListUserListsRequest, + callback: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListsRequest, + | protos.google.ads.datamanager.v1.IListUserListsResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IUserList + >, + ): void; listUserLists( - request?: protos.google.ads.datamanager.v1.IListUserListsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.ads.datamanager.v1.IListUserListsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ads.datamanager.v1.IListUserListsRequest, - protos.google.ads.datamanager.v1.IListUserListsResponse|null|undefined, - protos.google.ads.datamanager.v1.IUserList>, - callback?: PaginationCallback< - protos.google.ads.datamanager.v1.IListUserListsRequest, - protos.google.ads.datamanager.v1.IListUserListsResponse|null|undefined, - protos.google.ads.datamanager.v1.IUserList>): - Promise<[ - protos.google.ads.datamanager.v1.IUserList[], - protos.google.ads.datamanager.v1.IListUserListsRequest|null, - protos.google.ads.datamanager.v1.IListUserListsResponse - ]>|void { + | protos.google.ads.datamanager.v1.IListUserListsResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IUserList + >, + callback?: PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListsRequest, + | protos.google.ads.datamanager.v1.IListUserListsResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IUserList + >, + ): Promise< + [ + protos.google.ads.datamanager.v1.IUserList[], + protos.google.ads.datamanager.v1.IListUserListsRequest | null, + protos.google.ads.datamanager.v1.IListUserListsResponse, + ] + > | 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.ads.datamanager.v1.IListUserListsRequest, - protos.google.ads.datamanager.v1.IListUserListsResponse|null|undefined, - protos.google.ads.datamanager.v1.IUserList>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.ads.datamanager.v1.IListUserListsRequest, + | protos.google.ads.datamanager.v1.IListUserListsResponse + | null + | undefined, + protos.google.ads.datamanager.v1.IUserList + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listUserLists values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -937,178 +1168,182 @@ export class UserListServiceClient { this._log.info('listUserLists request %j', request); return this.innerApiCalls .listUserLists(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ads.datamanager.v1.IUserList[], - protos.google.ads.datamanager.v1.IListUserListsRequest|null, - protos.google.ads.datamanager.v1.IListUserListsResponse - ]) => { - this._log.info('listUserLists values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ads.datamanager.v1.IUserList[], + protos.google.ads.datamanager.v1.IListUserListsRequest | null, + protos.google.ads.datamanager.v1.IListUserListsResponse, + ]) => { + this._log.info('listUserLists values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listUserLists`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent account which owns this collection of user lists. - * Format: accountTypes/{account_type}/accounts/{account} - * @param {number} [request.pageSize] - * Optional. The maximum number of user lists to return. The service may - * return fewer than this value. If unspecified, at most 50 user lists will be - * returned. The maximum value is 1000; values above 1000 will be coerced to - * 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListUserLists` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListUserLists` must - * match the call that provided the page token. - * @param {string} [request.filter] - * Optional. A [filter string](https://google.aip.dev/160). All fields need to - * be on the left hand side of each condition (for example: `display_name = - * "list 1"`). Fields must be specified using either all [camel - * case](https://en.wikipedia.org/wiki/Camel_case) or all [snake - * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of - * camel case and snake case. - * - * Supported operations: - * - * - `AND` - * - `=` - * - `!=` - * - `>` - * - `>=` - * - `<` - * - `<=` - * - `:` (has) - * - * Supported fields: - * - * - `id` - * - `display_name` - * - `description` - * - `membership_status` - * - `integration_code` - * - `access_reason` - * - `ingested_user_list_info.upload_key_types` - * @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.ads.datamanager.v1.UserList|UserList} 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 `listUserListsAsync()` - * 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 `listUserLists`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent account which owns this collection of user lists. + * Format: accountTypes/{account_type}/accounts/{account} + * @param {number} [request.pageSize] + * Optional. The maximum number of user lists to return. The service may + * return fewer than this value. If unspecified, at most 50 user lists will be + * returned. The maximum value is 1000; values above 1000 will be coerced to + * 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListUserLists` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListUserLists` must + * match the call that provided the page token. + * @param {string} [request.filter] + * Optional. A [filter string](https://google.aip.dev/160). All fields need to + * be on the left hand side of each condition (for example: `display_name = + * "list 1"`). Fields must be specified using either all [camel + * case](https://en.wikipedia.org/wiki/Camel_case) or all [snake + * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of + * camel case and snake case. + * + * Supported operations: + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * - `:` (has) + * + * Supported fields: + * + * - `id` + * - `display_name` + * - `description` + * - `membership_status` + * - `integration_code` + * - `access_reason` + * - `ingested_user_list_info.upload_key_types` + * @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.ads.datamanager.v1.UserList|UserList} 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 `listUserListsAsync()` + * 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. + */ listUserListsStream( - request?: protos.google.ads.datamanager.v1.IListUserListsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ads.datamanager.v1.IListUserListsRequest, + 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['listUserLists']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listUserLists stream %j', request); return this.descriptors.page.listUserLists.createStream( this.innerApiCalls.listUserLists as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listUserLists`, 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 account which owns this collection of user lists. - * Format: accountTypes/{account_type}/accounts/{account} - * @param {number} [request.pageSize] - * Optional. The maximum number of user lists to return. The service may - * return fewer than this value. If unspecified, at most 50 user lists will be - * returned. The maximum value is 1000; values above 1000 will be coerced to - * 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListUserLists` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListUserLists` must - * match the call that provided the page token. - * @param {string} [request.filter] - * Optional. A [filter string](https://google.aip.dev/160). All fields need to - * be on the left hand side of each condition (for example: `display_name = - * "list 1"`). Fields must be specified using either all [camel - * case](https://en.wikipedia.org/wiki/Camel_case) or all [snake - * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of - * camel case and snake case. - * - * Supported operations: - * - * - `AND` - * - `=` - * - `!=` - * - `>` - * - `>=` - * - `<` - * - `<=` - * - `:` (has) - * - * Supported fields: - * - * - `id` - * - `display_name` - * - `description` - * - `membership_status` - * - `integration_code` - * - `access_reason` - * - `ingested_user_list_info.upload_key_types` - * @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.ads.datamanager.v1.UserList|UserList}. 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 include:samples/generated/v1/user_list_service.list_user_lists.js - * region_tag:datamanager_v1_generated_UserListService_ListUserLists_async - */ + /** + * Equivalent to `listUserLists`, 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 account which owns this collection of user lists. + * Format: accountTypes/{account_type}/accounts/{account} + * @param {number} [request.pageSize] + * Optional. The maximum number of user lists to return. The service may + * return fewer than this value. If unspecified, at most 50 user lists will be + * returned. The maximum value is 1000; values above 1000 will be coerced to + * 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListUserLists` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListUserLists` must + * match the call that provided the page token. + * @param {string} [request.filter] + * Optional. A [filter string](https://google.aip.dev/160). All fields need to + * be on the left hand side of each condition (for example: `display_name = + * "list 1"`). Fields must be specified using either all [camel + * case](https://en.wikipedia.org/wiki/Camel_case) or all [snake + * case](https://en.wikipedia.org/wiki/Snake_case). Don't use a combination of + * camel case and snake case. + * + * Supported operations: + * + * - `AND` + * - `=` + * - `!=` + * - `>` + * - `>=` + * - `<` + * - `<=` + * - `:` (has) + * + * Supported fields: + * + * - `id` + * - `display_name` + * - `description` + * - `membership_status` + * - `integration_code` + * - `access_reason` + * - `ingested_user_list_info.upload_key_types` + * @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.ads.datamanager.v1.UserList|UserList}. 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 include:samples/generated/v1/user_list_service.list_user_lists.js + * region_tag:datamanager_v1_generated_UserListService_ListUserLists_async + */ listUserListsAsync( - request?: protos.google.ads.datamanager.v1.IListUserListsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ads.datamanager.v1.IListUserListsRequest, + 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['listUserLists']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listUserLists iterate %j', request); return this.descriptors.page.listUserLists.asyncIterate( this.innerApiCalls['listUserLists'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1122,7 +1357,7 @@ export class UserListServiceClient { * @param {string} account * @returns {string} Resource name string. */ - accountPath(accountType:string,account:string) { + accountPath(accountType: string, account: string) { return this.pathTemplates.accountPathTemplate.render({ account_type: accountType, account: account, @@ -1137,7 +1372,8 @@ export class UserListServiceClient { * @returns {string} A string representing the account_type. */ matchAccountTypeFromAccountName(accountName: string) { - return this.pathTemplates.accountPathTemplate.match(accountName).account_type; + return this.pathTemplates.accountPathTemplate.match(accountName) + .account_type; } /** @@ -1159,7 +1395,7 @@ export class UserListServiceClient { * @param {string} partner_link * @returns {string} Resource name string. */ - partnerLinkPath(accountType:string,account:string,partnerLink:string) { + partnerLinkPath(accountType: string, account: string, partnerLink: string) { return this.pathTemplates.partnerLinkPathTemplate.render({ account_type: accountType, account: account, @@ -1175,7 +1411,8 @@ export class UserListServiceClient { * @returns {string} A string representing the account_type. */ matchAccountTypeFromPartnerLinkName(partnerLinkName: string) { - return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account_type; + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName) + .account_type; } /** @@ -1186,7 +1423,8 @@ export class UserListServiceClient { * @returns {string} A string representing the account. */ matchAccountFromPartnerLinkName(partnerLinkName: string) { - return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).account; + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName) + .account; } /** @@ -1197,7 +1435,8 @@ export class UserListServiceClient { * @returns {string} A string representing the partner_link. */ matchPartnerLinkFromPartnerLinkName(partnerLinkName: string) { - return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName).partner_link; + return this.pathTemplates.partnerLinkPathTemplate.match(partnerLinkName) + .partner_link; } /** @@ -1208,7 +1447,7 @@ export class UserListServiceClient { * @param {string} user_list * @returns {string} Resource name string. */ - userListPath(accountType:string,account:string,userList:string) { + userListPath(accountType: string, account: string, userList: string) { return this.pathTemplates.userListPathTemplate.render({ account_type: accountType, account: account, @@ -1224,7 +1463,8 @@ export class UserListServiceClient { * @returns {string} A string representing the account_type. */ matchAccountTypeFromUserListName(userListName: string) { - return this.pathTemplates.userListPathTemplate.match(userListName).account_type; + return this.pathTemplates.userListPathTemplate.match(userListName) + .account_type; } /** @@ -1246,7 +1486,8 @@ export class UserListServiceClient { * @returns {string} A string representing the user_list. */ matchUserListFromUserListName(userListName: string) { - return this.pathTemplates.userListPathTemplate.match(userListName).user_list; + return this.pathTemplates.userListPathTemplate.match(userListName) + .user_list; } /** @@ -1257,7 +1498,11 @@ export class UserListServiceClient { * @param {string} user_list_direct_license * @returns {string} Resource name string. */ - userListDirectLicensePath(accountType:string,account:string,userListDirectLicense:string) { + userListDirectLicensePath( + accountType: string, + account: string, + userListDirectLicense: string, + ) { return this.pathTemplates.userListDirectLicensePathTemplate.render({ account_type: accountType, account: account, @@ -1272,8 +1517,12 @@ export class UserListServiceClient { * A fully-qualified path representing UserListDirectLicense resource. * @returns {string} A string representing the account_type. */ - matchAccountTypeFromUserListDirectLicenseName(userListDirectLicenseName: string) { - return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account_type; + matchAccountTypeFromUserListDirectLicenseName( + userListDirectLicenseName: string, + ) { + return this.pathTemplates.userListDirectLicensePathTemplate.match( + userListDirectLicenseName, + ).account_type; } /** @@ -1284,7 +1533,9 @@ export class UserListServiceClient { * @returns {string} A string representing the account. */ matchAccountFromUserListDirectLicenseName(userListDirectLicenseName: string) { - return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).account; + return this.pathTemplates.userListDirectLicensePathTemplate.match( + userListDirectLicenseName, + ).account; } /** @@ -1294,8 +1545,12 @@ export class UserListServiceClient { * A fully-qualified path representing UserListDirectLicense resource. * @returns {string} A string representing the user_list_direct_license. */ - matchUserListDirectLicenseFromUserListDirectLicenseName(userListDirectLicenseName: string) { - return this.pathTemplates.userListDirectLicensePathTemplate.match(userListDirectLicenseName).user_list_direct_license; + matchUserListDirectLicenseFromUserListDirectLicenseName( + userListDirectLicenseName: string, + ) { + return this.pathTemplates.userListDirectLicensePathTemplate.match( + userListDirectLicenseName, + ).user_list_direct_license; } /** @@ -1306,7 +1561,11 @@ export class UserListServiceClient { * @param {string} user_list_global_license * @returns {string} Resource name string. */ - userListGlobalLicensePath(accountType:string,account:string,userListGlobalLicense:string) { + userListGlobalLicensePath( + accountType: string, + account: string, + userListGlobalLicense: string, + ) { return this.pathTemplates.userListGlobalLicensePathTemplate.render({ account_type: accountType, account: account, @@ -1321,8 +1580,12 @@ export class UserListServiceClient { * A fully-qualified path representing UserListGlobalLicense resource. * @returns {string} A string representing the account_type. */ - matchAccountTypeFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { - return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account_type; + matchAccountTypeFromUserListGlobalLicenseName( + userListGlobalLicenseName: string, + ) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match( + userListGlobalLicenseName, + ).account_type; } /** @@ -1333,7 +1596,9 @@ export class UserListServiceClient { * @returns {string} A string representing the account. */ matchAccountFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { - return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).account; + return this.pathTemplates.userListGlobalLicensePathTemplate.match( + userListGlobalLicenseName, + ).account; } /** @@ -1343,8 +1608,12 @@ export class UserListServiceClient { * A fully-qualified path representing UserListGlobalLicense resource. * @returns {string} A string representing the user_list_global_license. */ - matchUserListGlobalLicenseFromUserListGlobalLicenseName(userListGlobalLicenseName: string) { - return this.pathTemplates.userListGlobalLicensePathTemplate.match(userListGlobalLicenseName).user_list_global_license; + matchUserListGlobalLicenseFromUserListGlobalLicenseName( + userListGlobalLicenseName: string, + ) { + return this.pathTemplates.userListGlobalLicensePathTemplate.match( + userListGlobalLicenseName, + ).user_list_global_license; } /** @@ -1356,13 +1625,20 @@ export class UserListServiceClient { * @param {string} license_customer_info * @returns {string} Resource name string. */ - userListGlobalLicenseCustomerInfoPath(accountType:string,account:string,userListGlobalLicense:string,licenseCustomerInfo:string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render({ - account_type: accountType, - account: account, - user_list_global_license: userListGlobalLicense, - license_customer_info: licenseCustomerInfo, - }); + userListGlobalLicenseCustomerInfoPath( + accountType: string, + account: string, + userListGlobalLicense: string, + licenseCustomerInfo: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render( + { + account_type: accountType, + account: account, + user_list_global_license: userListGlobalLicense, + license_customer_info: licenseCustomerInfo, + }, + ); } /** @@ -1372,8 +1648,12 @@ export class UserListServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the account_type. */ - matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account_type; + matchAccountTypeFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).account_type; } /** @@ -1383,8 +1663,12 @@ export class UserListServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the account. */ - matchAccountFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).account; + matchAccountFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).account; } /** @@ -1394,8 +1678,12 @@ export class UserListServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the user_list_global_license. */ - matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).user_list_global_license; + matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).user_list_global_license; } /** @@ -1405,8 +1693,12 @@ export class UserListServiceClient { * A fully-qualified path representing UserListGlobalLicenseCustomerInfo resource. * @returns {string} A string representing the license_customer_info. */ - matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(userListGlobalLicenseCustomerInfoName: string) { - return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match(userListGlobalLicenseCustomerInfoName).license_customer_info; + matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName( + userListGlobalLicenseCustomerInfoName: string, + ) { + return this.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match( + userListGlobalLicenseCustomerInfoName, + ).license_customer_info; } /** @@ -1417,7 +1709,7 @@ export class UserListServiceClient { */ close(): Promise { if (this.userListServiceStub && !this._terminated) { - return this.userListServiceStub.then(stub => { + return this.userListServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1425,4 +1717,4 @@ export class UserListServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ads-datamanager/system-test/fixtures/sample/src/index.ts b/packages/google-ads-datamanager/system-test/fixtures/sample/src/index.ts index 2e2810220aef..91884de94386 100644 --- a/packages/google-ads-datamanager/system-test/fixtures/sample/src/index.ts +++ b/packages/google-ads-datamanager/system-test/fixtures/sample/src/index.ts @@ -16,22 +16,35 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {IngestionServiceClient, MarketingDataInsightsServiceClient, PartnerLinkServiceClient, UserListDirectLicenseServiceClient, UserListGlobalLicenseServiceClient, UserListServiceClient} from '@google-ads/datamanager'; +import { + IngestionServiceClient, + MarketingDataInsightsServiceClient, + PartnerLinkServiceClient, + UserListDirectLicenseServiceClient, + UserListGlobalLicenseServiceClient, + UserListServiceClient, +} from '@google-ads/datamanager'; // check that the client class type name can be used function doStuffWithIngestionServiceClient(client: IngestionServiceClient) { client.close(); } -function doStuffWithMarketingDataInsightsServiceClient(client: MarketingDataInsightsServiceClient) { +function doStuffWithMarketingDataInsightsServiceClient( + client: MarketingDataInsightsServiceClient, +) { client.close(); } function doStuffWithPartnerLinkServiceClient(client: PartnerLinkServiceClient) { client.close(); } -function doStuffWithUserListDirectLicenseServiceClient(client: UserListDirectLicenseServiceClient) { +function doStuffWithUserListDirectLicenseServiceClient( + client: UserListDirectLicenseServiceClient, +) { client.close(); } -function doStuffWithUserListGlobalLicenseServiceClient(client: UserListGlobalLicenseServiceClient) { +function doStuffWithUserListGlobalLicenseServiceClient( + client: UserListGlobalLicenseServiceClient, +) { client.close(); } function doStuffWithUserListServiceClient(client: UserListServiceClient) { @@ -43,17 +56,26 @@ function main() { const ingestionServiceClient = new IngestionServiceClient(); doStuffWithIngestionServiceClient(ingestionServiceClient); // check that the client instance can be created - const marketingDataInsightsServiceClient = new MarketingDataInsightsServiceClient(); - doStuffWithMarketingDataInsightsServiceClient(marketingDataInsightsServiceClient); + const marketingDataInsightsServiceClient = + new MarketingDataInsightsServiceClient(); + doStuffWithMarketingDataInsightsServiceClient( + marketingDataInsightsServiceClient, + ); // check that the client instance can be created const partnerLinkServiceClient = new PartnerLinkServiceClient(); doStuffWithPartnerLinkServiceClient(partnerLinkServiceClient); // check that the client instance can be created - const userListDirectLicenseServiceClient = new UserListDirectLicenseServiceClient(); - doStuffWithUserListDirectLicenseServiceClient(userListDirectLicenseServiceClient); + const userListDirectLicenseServiceClient = + new UserListDirectLicenseServiceClient(); + doStuffWithUserListDirectLicenseServiceClient( + userListDirectLicenseServiceClient, + ); // check that the client instance can be created - const userListGlobalLicenseServiceClient = new UserListGlobalLicenseServiceClient(); - doStuffWithUserListGlobalLicenseServiceClient(userListGlobalLicenseServiceClient); + const userListGlobalLicenseServiceClient = + new UserListGlobalLicenseServiceClient(); + doStuffWithUserListGlobalLicenseServiceClient( + userListGlobalLicenseServiceClient, + ); // check that the client instance can be created const userListServiceClient = new UserListServiceClient(); doStuffWithUserListServiceClient(userListServiceClient); diff --git a/packages/google-ads-datamanager/system-test/install.ts b/packages/google-ads-datamanager/system-test/install.ts index f66069aa3940..ccf167042d2e 100644 --- a/packages/google-ads-datamanager/system-test/install.ts +++ b/packages/google-ads-datamanager/system-test/install.ts @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - cjs: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/packages/google-ads-datamanager/test/gapic_ingestion_service_v1.ts b/packages/google-ads-datamanager/test/gapic_ingestion_service_v1.ts index ab31bea65b7c..dd889380df64 100644 --- a/packages/google-ads-datamanager/test/gapic_ingestion_service_v1.ts +++ b/packages/google-ads-datamanager/test/gapic_ingestion_service_v1.ts @@ -19,737 +19,992 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as ingestionserviceModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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); } describe('v1.IngestionServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new ingestionserviceModule.v1.IngestionServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new ingestionserviceModule.v1.IngestionServiceClient(); - 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 = ingestionserviceModule.v1.IngestionServiceClient.servicePath; - assert.strictEqual(servicePath, 'datamanager.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = ingestionserviceModule.v1.IngestionServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new ingestionserviceModule.v1.IngestionServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new ingestionserviceModule.v1.IngestionServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.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 ingestionserviceModule.v1.IngestionServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.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 ingestionserviceModule.v1.IngestionServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.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 ingestionserviceModule.v1.IngestionServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = ingestionserviceModule.v1.IngestionServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new ingestionserviceModule.v1.IngestionServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); + }); - it('should create a client with no option', () => { - const client = new ingestionserviceModule.v1.IngestionServiceClient(); - assert(client); - }); + it('has universeDomain', () => { + const client = new ingestionserviceModule.v1.IngestionServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - fallback: true, - }); - assert(client); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + ingestionserviceModule.v1.IngestionServiceClient.servicePath; + assert.strictEqual(servicePath, 'datamanager.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + ingestionserviceModule.v1.IngestionServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.ingestionServiceStub, undefined); - await client.initialize(); - assert(client.ingestionServiceStub); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + }); - it('has close method for the initialized client', done => { - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.ingestionServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + 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 ingestionserviceModule.v1.IngestionServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.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 ingestionserviceModule.v1.IngestionServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.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 ingestionserviceModule.v1.IngestionServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has close method for the non-initialized client', done => { - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.ingestionServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = ingestionserviceModule.v1.IngestionServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - 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('should create a client with no option', () => { + const client = new ingestionserviceModule.v1.IngestionServiceClient(); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - 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('should create a client with gRPC fallback', () => { + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + fallback: true, + }); + assert(client); }); - describe('ingestAudienceMembers', () => { - it('invokes ingestAudienceMembers without error', async () => { - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.IngestAudienceMembersRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.IngestAudienceMembersResponse() - ); - client.innerApiCalls.ingestAudienceMembers = stubSimpleCall(expectedResponse); - const [response] = await client.ingestAudienceMembers(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.ingestionServiceStub, undefined); + await client.initialize(); + assert(client.ingestionServiceStub); + }); - it('invokes ingestAudienceMembers without error using callback', async () => { - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.IngestAudienceMembersRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.IngestAudienceMembersResponse() - ); - client.innerApiCalls.ingestAudienceMembers = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.ingestAudienceMembers( - request, - (err?: Error|null, result?: protos.google.ads.datamanager.v1.IIngestAudienceMembersResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the initialized client', (done) => { + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.ingestionServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes ingestAudienceMembers with error', async () => { - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.IngestAudienceMembersRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.ingestAudienceMembers = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.ingestAudienceMembers(request), expectedError); + it('has close method for the non-initialized client', (done) => { + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.ingestionServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes ingestAudienceMembers with closed client', async () => { - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.IngestAudienceMembersRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.ingestAudienceMembers(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + 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('removeAudienceMembers', () => { - it('invokes removeAudienceMembers without error', async () => { - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.RemoveAudienceMembersRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.RemoveAudienceMembersResponse() - ); - client.innerApiCalls.removeAudienceMembers = stubSimpleCall(expectedResponse); - const [response] = await client.removeAudienceMembers(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + 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('ingestAudienceMembers', () => { + it('invokes ingestAudienceMembers without error', async () => { + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.IngestAudienceMembersRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.IngestAudienceMembersResponse(), + ); + client.innerApiCalls.ingestAudienceMembers = + stubSimpleCall(expectedResponse); + const [response] = await client.ingestAudienceMembers(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes removeAudienceMembers without error using callback', async () => { - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.RemoveAudienceMembersRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.RemoveAudienceMembersResponse() - ); - client.innerApiCalls.removeAudienceMembers = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.removeAudienceMembers( - request, - (err?: Error|null, result?: protos.google.ads.datamanager.v1.IRemoveAudienceMembersResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes ingestAudienceMembers without error using callback', async () => { + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.IngestAudienceMembersRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.IngestAudienceMembersResponse(), + ); + client.innerApiCalls.ingestAudienceMembers = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.ingestAudienceMembers( + request, + ( + err?: Error | null, + result?: protos.google.ads.datamanager.v1.IIngestAudienceMembersResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes removeAudienceMembers with error', async () => { - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.RemoveAudienceMembersRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.removeAudienceMembers = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.removeAudienceMembers(request), expectedError); - }); + it('invokes ingestAudienceMembers with error', async () => { + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.IngestAudienceMembersRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.ingestAudienceMembers = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.ingestAudienceMembers(request), + expectedError, + ); + }); - it('invokes removeAudienceMembers with closed client', async () => { - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.RemoveAudienceMembersRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.removeAudienceMembers(request), expectedError); - }); + it('invokes ingestAudienceMembers with closed client', async () => { + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.IngestAudienceMembersRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.ingestAudienceMembers(request), + expectedError, + ); + }); + }); + + describe('removeAudienceMembers', () => { + it('invokes removeAudienceMembers without error', async () => { + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.RemoveAudienceMembersRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.RemoveAudienceMembersResponse(), + ); + client.innerApiCalls.removeAudienceMembers = + stubSimpleCall(expectedResponse); + const [response] = await client.removeAudienceMembers(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('ingestEvents', () => { - it('invokes ingestEvents without error', async () => { - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.IngestEventsRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.IngestEventsResponse() - ); - client.innerApiCalls.ingestEvents = stubSimpleCall(expectedResponse); - const [response] = await client.ingestEvents(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes removeAudienceMembers without error using callback', async () => { + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.RemoveAudienceMembersRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.RemoveAudienceMembersResponse(), + ); + client.innerApiCalls.removeAudienceMembers = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.removeAudienceMembers( + request, + ( + err?: Error | null, + result?: protos.google.ads.datamanager.v1.IRemoveAudienceMembersResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes ingestEvents without error using callback', async () => { - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.IngestEventsRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.IngestEventsResponse() - ); - client.innerApiCalls.ingestEvents = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.ingestEvents( - request, - (err?: Error|null, result?: protos.google.ads.datamanager.v1.IIngestEventsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes removeAudienceMembers with error', async () => { + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.RemoveAudienceMembersRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.removeAudienceMembers = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.removeAudienceMembers(request), + expectedError, + ); + }); - it('invokes ingestEvents with error', async () => { - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.IngestEventsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.ingestEvents = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.ingestEvents(request), expectedError); - }); + it('invokes removeAudienceMembers with closed client', async () => { + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.RemoveAudienceMembersRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.removeAudienceMembers(request), + expectedError, + ); + }); + }); + + describe('ingestEvents', () => { + it('invokes ingestEvents without error', async () => { + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.IngestEventsRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.IngestEventsResponse(), + ); + client.innerApiCalls.ingestEvents = stubSimpleCall(expectedResponse); + const [response] = await client.ingestEvents(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes ingestEvents with closed client', async () => { - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.IngestEventsRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.ingestEvents(request), expectedError); - }); + it('invokes ingestEvents without error using callback', async () => { + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.IngestEventsRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.IngestEventsResponse(), + ); + client.innerApiCalls.ingestEvents = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.ingestEvents( + request, + ( + err?: Error | null, + result?: protos.google.ads.datamanager.v1.IIngestEventsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('retrieveRequestStatus', () => { - it('invokes retrieveRequestStatus without error', async () => { - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.RetrieveRequestStatusRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.RetrieveRequestStatusResponse() - ); - client.innerApiCalls.retrieveRequestStatus = stubSimpleCall(expectedResponse); - const [response] = await client.retrieveRequestStatus(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes ingestEvents with error', async () => { + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.IngestEventsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.ingestEvents = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.ingestEvents(request), expectedError); + }); - it('invokes retrieveRequestStatus without error using callback', async () => { - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.RetrieveRequestStatusRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.RetrieveRequestStatusResponse() - ); - client.innerApiCalls.retrieveRequestStatus = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.retrieveRequestStatus( - request, - (err?: Error|null, result?: protos.google.ads.datamanager.v1.IRetrieveRequestStatusResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes ingestEvents with closed client', async () => { + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.IngestEventsRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.ingestEvents(request), expectedError); + }); + }); + + describe('retrieveRequestStatus', () => { + it('invokes retrieveRequestStatus without error', async () => { + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.RetrieveRequestStatusRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.RetrieveRequestStatusResponse(), + ); + client.innerApiCalls.retrieveRequestStatus = + stubSimpleCall(expectedResponse); + const [response] = await client.retrieveRequestStatus(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes retrieveRequestStatus with error', async () => { - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.RetrieveRequestStatusRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.retrieveRequestStatus = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.retrieveRequestStatus(request), expectedError); - }); + it('invokes retrieveRequestStatus without error using callback', async () => { + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.RetrieveRequestStatusRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.RetrieveRequestStatusResponse(), + ); + client.innerApiCalls.retrieveRequestStatus = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.retrieveRequestStatus( + request, + ( + err?: Error | null, + result?: protos.google.ads.datamanager.v1.IRetrieveRequestStatusResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes retrieveRequestStatus with closed client', async () => { - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.RetrieveRequestStatusRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.retrieveRequestStatus(request), expectedError); - }); + it('invokes retrieveRequestStatus with error', async () => { + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.RetrieveRequestStatusRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.retrieveRequestStatus = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.retrieveRequestStatus(request), + expectedError, + ); }); - describe('Path templates', () => { - - describe('partnerLink', async () => { - const fakePath = "/rendered/path/partnerLink"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - partner_link: "partnerLinkValue", - }; - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.partnerLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.partnerLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('partnerLinkPath', () => { - const result = client.partnerLinkPath("accountTypeValue", "accountValue", "partnerLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.partnerLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromPartnerLinkName', () => { - const result = client.matchAccountTypeFromPartnerLinkName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromPartnerLinkName', () => { - const result = client.matchAccountFromPartnerLinkName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPartnerLinkFromPartnerLinkName', () => { - const result = client.matchPartnerLinkFromPartnerLinkName(fakePath); - assert.strictEqual(result, "partnerLinkValue"); - assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes retrieveRequestStatus with closed client', async () => { + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.RetrieveRequestStatusRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.retrieveRequestStatus(request), + expectedError, + ); + }); + }); + + describe('Path templates', () => { + describe('partnerLink', async () => { + const fakePath = '/rendered/path/partnerLink'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + partner_link: 'partnerLinkValue', + }; + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.partnerLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.partnerLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('partnerLinkPath', () => { + const result = client.partnerLinkPath( + 'accountTypeValue', + 'accountValue', + 'partnerLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.partnerLinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromPartnerLinkName', () => { + const result = client.matchAccountTypeFromPartnerLinkName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + (client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromPartnerLinkName', () => { + const result = client.matchAccountFromPartnerLinkName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + (client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPartnerLinkFromPartnerLinkName', () => { + const result = client.matchPartnerLinkFromPartnerLinkName(fakePath); + assert.strictEqual(result, 'partnerLinkValue'); + assert( + (client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userList', async () => { - const fakePath = "/rendered/path/userList"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list: "userListValue", - }; - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListPath', () => { - const result = client.userListPath("accountTypeValue", "accountValue", "userListValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromUserListName', () => { - const result = client.matchAccountTypeFromUserListName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromUserListName', () => { - const result = client.matchAccountFromUserListName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUserListFromUserListName', () => { - const result = client.matchUserListFromUserListName(fakePath); - assert.strictEqual(result, "userListValue"); - assert((client.pathTemplates.userListPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userList', async () => { + const fakePath = '/rendered/path/userList'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list: 'userListValue', + }; + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userListPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userListPath', () => { + const result = client.userListPath( + 'accountTypeValue', + 'accountValue', + 'userListValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userListPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListName', () => { + const result = client.matchAccountTypeFromUserListName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + (client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListName', () => { + const result = client.matchAccountFromUserListName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + (client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListFromUserListName', () => { + const result = client.matchUserListFromUserListName(fakePath); + assert.strictEqual(result, 'userListValue'); + assert( + (client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userListDirectLicense', async () => { - const fakePath = "/rendered/path/userListDirectLicense"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list_direct_license: "userListDirectLicenseValue", - }; - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListDirectLicensePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListDirectLicensePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListDirectLicensePath', () => { - const result = client.userListDirectLicensePath("accountTypeValue", "accountValue", "userListDirectLicenseValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListDirectLicensePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromUserListDirectLicenseName', () => { - const result = client.matchAccountTypeFromUserListDirectLicenseName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromUserListDirectLicenseName', () => { - const result = client.matchAccountFromUserListDirectLicenseName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUserListDirectLicenseFromUserListDirectLicenseName', () => { - const result = client.matchUserListDirectLicenseFromUserListDirectLicenseName(fakePath); - assert.strictEqual(result, "userListDirectLicenseValue"); - assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userListDirectLicense', async () => { + const fakePath = '/rendered/path/userListDirectLicense'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list_direct_license: 'userListDirectLicenseValue', + }; + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListDirectLicensePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userListDirectLicensePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userListDirectLicensePath', () => { + const result = client.userListDirectLicensePath( + 'accountTypeValue', + 'accountValue', + 'userListDirectLicenseValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListDirectLicenseName', () => { + const result = + client.matchAccountTypeFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListDirectLicenseName', () => { + const result = + client.matchAccountFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListDirectLicenseFromUserListDirectLicenseName', () => { + const result = + client.matchUserListDirectLicenseFromUserListDirectLicenseName( + fakePath, + ); + assert.strictEqual(result, 'userListDirectLicenseValue'); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userListGlobalLicense', async () => { - const fakePath = "/rendered/path/userListGlobalLicense"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list_global_license: "userListGlobalLicenseValue", - }; - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListGlobalLicensePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListGlobalLicensePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListGlobalLicensePath', () => { - const result = client.userListGlobalLicensePath("accountTypeValue", "accountValue", "userListGlobalLicenseValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromUserListGlobalLicenseName', () => { - const result = client.matchAccountTypeFromUserListGlobalLicenseName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromUserListGlobalLicenseName', () => { - const result = client.matchAccountFromUserListGlobalLicenseName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUserListGlobalLicenseFromUserListGlobalLicenseName', () => { - const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseName(fakePath); - assert.strictEqual(result, "userListGlobalLicenseValue"); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userListGlobalLicense', async () => { + const fakePath = '/rendered/path/userListGlobalLicense'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list_global_license: 'userListGlobalLicenseValue', + }; + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListGlobalLicensePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userListGlobalLicensePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userListGlobalLicensePath', () => { + const result = client.userListGlobalLicensePath( + 'accountTypeValue', + 'accountValue', + 'userListGlobalLicenseValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListGlobalLicenseName', () => { + const result = + client.matchAccountTypeFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListGlobalLicenseName', () => { + const result = + client.matchAccountFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseName', () => { + const result = + client.matchUserListGlobalLicenseFromUserListGlobalLicenseName( + fakePath, + ); + assert.strictEqual(result, 'userListGlobalLicenseValue'); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userListGlobalLicenseCustomerInfo', async () => { - const fakePath = "/rendered/path/userListGlobalLicenseCustomerInfo"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list_global_license: "userListGlobalLicenseValue", - license_customer_info: "licenseCustomerInfoValue", - }; - const client = new ingestionserviceModule.v1.IngestionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListGlobalLicenseCustomerInfoPath', () => { - const result = client.userListGlobalLicenseCustomerInfoPath("accountTypeValue", "accountValue", "userListGlobalLicenseValue", "licenseCustomerInfoValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchAccountFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "userListGlobalLicenseValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "licenseCustomerInfoValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userListGlobalLicenseCustomerInfo', async () => { + const fakePath = '/rendered/path/userListGlobalLicenseCustomerInfo'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list_global_license: 'userListGlobalLicenseValue', + license_customer_info: 'licenseCustomerInfoValue', + }; + const client = new ingestionserviceModule.v1.IngestionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListGlobalLicenseCustomerInfoPath', () => { + const result = client.userListGlobalLicenseCustomerInfoPath( + 'accountTypeValue', + 'accountValue', + 'userListGlobalLicenseValue', + 'licenseCustomerInfoValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchAccountTypeFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'accountTypeValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchAccountFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'accountValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'userListGlobalLicenseValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'licenseCustomerInfoValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ads-datamanager/test/gapic_marketing_data_insights_service_v1.ts b/packages/google-ads-datamanager/test/gapic_marketing_data_insights_service_v1.ts index eabc01fa8659..330317774bba 100644 --- a/packages/google-ads-datamanager/test/gapic_marketing_data_insights_service_v1.ts +++ b/packages/google-ads-datamanager/test/gapic_marketing_data_insights_service_v1.ts @@ -19,545 +19,818 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as marketingdatainsightsserviceModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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); } describe('v1.MarketingDataInsightsServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'datamanager.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 = marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient.servicePath; - assert.strictEqual(servicePath, 'datamanager.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.example.com'); - }); + it('has universeDomain', () => { + const client = + new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.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 = + marketingdatainsightsserviceModule.v1 + .MarketingDataInsightsServiceClient.servicePath; + assert.strictEqual(servicePath, 'datamanager.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + marketingdatainsightsserviceModule.v1 + .MarketingDataInsightsServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient( + { universeDomain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.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 marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.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 marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.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 marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient( + { universe_domain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + }); - it('has port', () => { - const port = marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient.port; - assert(port); - assert(typeof port === 'number'); + 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 marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with no option', () => { - const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient(); - assert(client); + 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 marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient( + { universeDomain: 'configured.example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.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 marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient( + { universe_domain: 'example.com', universeDomain: 'example.net' }, + ); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = + marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient + .port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.marketingDataInsightsServiceStub, undefined); - await client.initialize(); - assert(client.marketingDataInsightsServiceStub); - }); + it('should create a client with no option', () => { + const client = + new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.marketingDataInsightsServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = + new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient( + { + fallback: true, + }, + ); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.marketingDataInsightsServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = + new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.marketingDataInsightsServiceStub, undefined); + await client.initialize(); + assert(client.marketingDataInsightsServiceStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ - 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 close method for the initialized client', (done) => { + const client = + new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + assert(client.marketingDataInsightsServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ - 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('has close method for the non-initialized client', (done) => { + const client = + new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.marketingDataInsightsServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('retrieveInsights', () => { - it('invokes retrieveInsights without error', async () => { - const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.RetrieveInsightsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.RetrieveInsightsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.RetrieveInsightsResponse() - ); - client.innerApiCalls.retrieveInsights = stubSimpleCall(expectedResponse); - const [response] = await client.retrieveInsights(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.retrieveInsights as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.retrieveInsights 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 marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient( + { + 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 retrieveInsights without error using callback', async () => { - const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.RetrieveInsightsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.RetrieveInsightsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.RetrieveInsightsResponse() - ); - client.innerApiCalls.retrieveInsights = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.retrieveInsights( - request, - (err?: Error|null, result?: protos.google.ads.datamanager.v1.IRetrieveInsightsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.retrieveInsights as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.retrieveInsights 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 marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient( + { + 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('retrieveInsights', () => { + it('invokes retrieveInsights without error', async () => { + const client = + new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.RetrieveInsightsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.RetrieveInsightsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.RetrieveInsightsResponse(), + ); + client.innerApiCalls.retrieveInsights = stubSimpleCall(expectedResponse); + const [response] = await client.retrieveInsights(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.retrieveInsights as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.retrieveInsights as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes retrieveInsights with error', async () => { - const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.RetrieveInsightsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.RetrieveInsightsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.retrieveInsights = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.retrieveInsights(request), expectedError); - const actualRequest = (client.innerApiCalls.retrieveInsights as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.retrieveInsights as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes retrieveInsights without error using callback', async () => { + const client = + new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.RetrieveInsightsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.RetrieveInsightsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.RetrieveInsightsResponse(), + ); + client.innerApiCalls.retrieveInsights = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.retrieveInsights( + request, + ( + err?: Error | null, + result?: protos.google.ads.datamanager.v1.IRetrieveInsightsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.retrieveInsights as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.retrieveInsights as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes retrieveInsights with closed client', async () => { - const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.RetrieveInsightsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.RetrieveInsightsRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.retrieveInsights(request), expectedError); - }); + it('invokes retrieveInsights with error', async () => { + const client = + new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.RetrieveInsightsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.RetrieveInsightsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.retrieveInsights = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.retrieveInsights(request), expectedError); + const actualRequest = ( + client.innerApiCalls.retrieveInsights as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.retrieveInsights as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('partnerLink', async () => { - const fakePath = "/rendered/path/partnerLink"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - partner_link: "partnerLinkValue", - }; - const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.partnerLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.partnerLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('partnerLinkPath', () => { - const result = client.partnerLinkPath("accountTypeValue", "accountValue", "partnerLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.partnerLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromPartnerLinkName', () => { - const result = client.matchAccountTypeFromPartnerLinkName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromPartnerLinkName', () => { - const result = client.matchAccountFromPartnerLinkName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPartnerLinkFromPartnerLinkName', () => { - const result = client.matchPartnerLinkFromPartnerLinkName(fakePath); - assert.strictEqual(result, "partnerLinkValue"); - assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes retrieveInsights with closed client', async () => { + const client = + new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.RetrieveInsightsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.RetrieveInsightsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.retrieveInsights(request), expectedError); + }); + }); + + describe('Path templates', () => { + describe('partnerLink', async () => { + const fakePath = '/rendered/path/partnerLink'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + partner_link: 'partnerLinkValue', + }; + const client = + new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.partnerLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.partnerLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('partnerLinkPath', () => { + const result = client.partnerLinkPath( + 'accountTypeValue', + 'accountValue', + 'partnerLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.partnerLinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromPartnerLinkName', () => { + const result = client.matchAccountTypeFromPartnerLinkName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + (client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromPartnerLinkName', () => { + const result = client.matchAccountFromPartnerLinkName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + (client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPartnerLinkFromPartnerLinkName', () => { + const result = client.matchPartnerLinkFromPartnerLinkName(fakePath); + assert.strictEqual(result, 'partnerLinkValue'); + assert( + (client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userList', async () => { - const fakePath = "/rendered/path/userList"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list: "userListValue", - }; - const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListPath', () => { - const result = client.userListPath("accountTypeValue", "accountValue", "userListValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromUserListName', () => { - const result = client.matchAccountTypeFromUserListName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromUserListName', () => { - const result = client.matchAccountFromUserListName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUserListFromUserListName', () => { - const result = client.matchUserListFromUserListName(fakePath); - assert.strictEqual(result, "userListValue"); - assert((client.pathTemplates.userListPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userList', async () => { + const fakePath = '/rendered/path/userList'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list: 'userListValue', + }; + const client = + new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.userListPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userListPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userListPath', () => { + const result = client.userListPath( + 'accountTypeValue', + 'accountValue', + 'userListValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userListPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListName', () => { + const result = client.matchAccountTypeFromUserListName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + (client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListName', () => { + const result = client.matchAccountFromUserListName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + (client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListFromUserListName', () => { + const result = client.matchUserListFromUserListName(fakePath); + assert.strictEqual(result, 'userListValue'); + assert( + (client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userListDirectLicense', async () => { - const fakePath = "/rendered/path/userListDirectLicense"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list_direct_license: "userListDirectLicenseValue", - }; - const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListDirectLicensePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListDirectLicensePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListDirectLicensePath', () => { - const result = client.userListDirectLicensePath("accountTypeValue", "accountValue", "userListDirectLicenseValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListDirectLicensePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromUserListDirectLicenseName', () => { - const result = client.matchAccountTypeFromUserListDirectLicenseName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromUserListDirectLicenseName', () => { - const result = client.matchAccountFromUserListDirectLicenseName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUserListDirectLicenseFromUserListDirectLicenseName', () => { - const result = client.matchUserListDirectLicenseFromUserListDirectLicenseName(fakePath); - assert.strictEqual(result, "userListDirectLicenseValue"); - assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userListDirectLicense', async () => { + const fakePath = '/rendered/path/userListDirectLicense'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list_direct_license: 'userListDirectLicenseValue', + }; + const client = + new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.userListDirectLicensePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userListDirectLicensePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userListDirectLicensePath', () => { + const result = client.userListDirectLicensePath( + 'accountTypeValue', + 'accountValue', + 'userListDirectLicenseValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListDirectLicenseName', () => { + const result = + client.matchAccountTypeFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListDirectLicenseName', () => { + const result = + client.matchAccountFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListDirectLicenseFromUserListDirectLicenseName', () => { + const result = + client.matchUserListDirectLicenseFromUserListDirectLicenseName( + fakePath, + ); + assert.strictEqual(result, 'userListDirectLicenseValue'); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userListGlobalLicense', async () => { - const fakePath = "/rendered/path/userListGlobalLicense"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list_global_license: "userListGlobalLicenseValue", - }; - const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListGlobalLicensePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListGlobalLicensePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListGlobalLicensePath', () => { - const result = client.userListGlobalLicensePath("accountTypeValue", "accountValue", "userListGlobalLicenseValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromUserListGlobalLicenseName', () => { - const result = client.matchAccountTypeFromUserListGlobalLicenseName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromUserListGlobalLicenseName', () => { - const result = client.matchAccountFromUserListGlobalLicenseName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUserListGlobalLicenseFromUserListGlobalLicenseName', () => { - const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseName(fakePath); - assert.strictEqual(result, "userListGlobalLicenseValue"); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userListGlobalLicense', async () => { + const fakePath = '/rendered/path/userListGlobalLicense'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list_global_license: 'userListGlobalLicenseValue', + }; + const client = + new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.userListGlobalLicensePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userListGlobalLicensePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userListGlobalLicensePath', () => { + const result = client.userListGlobalLicensePath( + 'accountTypeValue', + 'accountValue', + 'userListGlobalLicenseValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListGlobalLicenseName', () => { + const result = + client.matchAccountTypeFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListGlobalLicenseName', () => { + const result = + client.matchAccountFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseName', () => { + const result = + client.matchUserListGlobalLicenseFromUserListGlobalLicenseName( + fakePath, + ); + assert.strictEqual(result, 'userListGlobalLicenseValue'); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userListGlobalLicenseCustomerInfo', async () => { - const fakePath = "/rendered/path/userListGlobalLicenseCustomerInfo"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list_global_license: "userListGlobalLicenseValue", - license_customer_info: "licenseCustomerInfoValue", - }; - const client = new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListGlobalLicenseCustomerInfoPath', () => { - const result = client.userListGlobalLicenseCustomerInfoPath("accountTypeValue", "accountValue", "userListGlobalLicenseValue", "licenseCustomerInfoValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchAccountFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "userListGlobalLicenseValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "licenseCustomerInfoValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userListGlobalLicenseCustomerInfo', async () => { + const fakePath = '/rendered/path/userListGlobalLicenseCustomerInfo'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list_global_license: 'userListGlobalLicenseValue', + license_customer_info: 'licenseCustomerInfoValue', + }; + const client = + new marketingdatainsightsserviceModule.v1.MarketingDataInsightsServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListGlobalLicenseCustomerInfoPath', () => { + const result = client.userListGlobalLicenseCustomerInfoPath( + 'accountTypeValue', + 'accountValue', + 'userListGlobalLicenseValue', + 'licenseCustomerInfoValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchAccountTypeFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'accountTypeValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchAccountFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'accountValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'userListGlobalLicenseValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'licenseCustomerInfoValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ads-datamanager/test/gapic_partner_link_service_v1.ts b/packages/google-ads-datamanager/test/gapic_partner_link_service_v1.ts index d279f6e51bd9..322bb47bfff6 100644 --- a/packages/google-ads-datamanager/test/gapic_partner_link_service_v1.ts +++ b/packages/google-ads-datamanager/test/gapic_partner_link_service_v1.ts @@ -19,983 +19,1335 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as partnerlinkserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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 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.PartnerLinkServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient(); - 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 = partnerlinkserviceModule.v1.PartnerLinkServiceClient.servicePath; - assert.strictEqual(servicePath, 'datamanager.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = partnerlinkserviceModule.v1.PartnerLinkServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.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 partnerlinkserviceModule.v1.PartnerLinkServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.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 partnerlinkserviceModule.v1.PartnerLinkServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.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 partnerlinkserviceModule.v1.PartnerLinkServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = partnerlinkserviceModule.v1.PartnerLinkServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient(); - assert(client); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has universeDomain', () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.partnerLinkServiceStub, undefined); - await client.initialize(); - assert(client.partnerLinkServiceStub); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + partnerlinkserviceModule.v1.PartnerLinkServiceClient.servicePath; + assert.strictEqual(servicePath, 'datamanager.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + partnerlinkserviceModule.v1.PartnerLinkServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + }); - it('has close method for the initialized client', done => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.partnerLinkServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + }); - it('has close method for the non-initialized client', done => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.partnerLinkServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + 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 partnerlinkserviceModule.v1.PartnerLinkServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', + 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 partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + universeDomain: 'configured.example.com', }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - 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('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('createPartnerLink', () => { - it('invokes createPartnerLink without error', async () => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.CreatePartnerLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.CreatePartnerLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.PartnerLink() - ); - client.innerApiCalls.createPartnerLink = stubSimpleCall(expectedResponse); - const [response] = await client.createPartnerLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createPartnerLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createPartnerLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createPartnerLink without error using callback', async () => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.CreatePartnerLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.CreatePartnerLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.PartnerLink() - ); - client.innerApiCalls.createPartnerLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createPartnerLink( - request, - (err?: Error|null, result?: protos.google.ads.datamanager.v1.IPartnerLink|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createPartnerLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createPartnerLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createPartnerLink with error', async () => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.CreatePartnerLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.CreatePartnerLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createPartnerLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createPartnerLink(request), expectedError); - const actualRequest = (client.innerApiCalls.createPartnerLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createPartnerLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = partnerlinkserviceModule.v1.PartnerLinkServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes createPartnerLink with closed client', async () => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.CreatePartnerLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.CreatePartnerLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createPartnerLink(request), expectedError); - }); + it('should create a client with no option', () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient(); + assert(client); }); - describe('deletePartnerLink', () => { - it('invokes deletePartnerLink without error', async () => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.DeletePartnerLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.DeletePartnerLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deletePartnerLink = stubSimpleCall(expectedResponse); - const [response] = await client.deletePartnerLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deletePartnerLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deletePartnerLink 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 partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + fallback: true, + }); + assert(client); + }); - it('invokes deletePartnerLink without error using callback', async () => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.DeletePartnerLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.DeletePartnerLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deletePartnerLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deletePartnerLink( - 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.deletePartnerLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deletePartnerLink 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 partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.partnerLinkServiceStub, undefined); + await client.initialize(); + assert(client.partnerLinkServiceStub); + }); - it('invokes deletePartnerLink with error', async () => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.DeletePartnerLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.DeletePartnerLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deletePartnerLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deletePartnerLink(request), expectedError); - const actualRequest = (client.innerApiCalls.deletePartnerLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deletePartnerLink 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 partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.partnerLinkServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes deletePartnerLink with closed client', async () => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.DeletePartnerLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.DeletePartnerLinkRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deletePartnerLink(request), expectedError); + it('has close method for the non-initialized client', (done) => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.partnerLinkServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('searchPartnerLinks', () => { - it('invokes searchPartnerLinks without error', async () => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.SearchPartnerLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.SearchPartnerLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), - generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), - generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), - ]; - client.innerApiCalls.searchPartnerLinks = stubSimpleCall(expectedResponse); - const [response] = await client.searchPartnerLinks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.searchPartnerLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchPartnerLinks 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 partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + 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 searchPartnerLinks without error using callback', async () => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.SearchPartnerLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.SearchPartnerLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), - generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), - generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), - ]; - client.innerApiCalls.searchPartnerLinks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.searchPartnerLinks( - request, - (err?: Error|null, result?: protos.google.ads.datamanager.v1.IPartnerLink[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.searchPartnerLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchPartnerLinks 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 partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + 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('createPartnerLink', () => { + it('invokes createPartnerLink without error', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreatePartnerLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.CreatePartnerLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.PartnerLink(), + ); + client.innerApiCalls.createPartnerLink = stubSimpleCall(expectedResponse); + const [response] = await client.createPartnerLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createPartnerLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createPartnerLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes searchPartnerLinks with error', async () => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.SearchPartnerLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.SearchPartnerLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.searchPartnerLinks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.searchPartnerLinks(request), expectedError); - const actualRequest = (client.innerApiCalls.searchPartnerLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchPartnerLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createPartnerLink without error using callback', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreatePartnerLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.CreatePartnerLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.PartnerLink(), + ); + client.innerApiCalls.createPartnerLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createPartnerLink( + request, + ( + err?: Error | null, + result?: protos.google.ads.datamanager.v1.IPartnerLink | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createPartnerLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createPartnerLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes searchPartnerLinksStream without error', async () => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.SearchPartnerLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.SearchPartnerLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), - generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), - generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), - ]; - client.descriptors.page.searchPartnerLinks.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.searchPartnerLinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ads.datamanager.v1.PartnerLink[] = []; - stream.on('data', (response: protos.google.ads.datamanager.v1.PartnerLink) => { - 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.searchPartnerLinks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.searchPartnerLinks, request)); - assert( - (client.descriptors.page.searchPartnerLinks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes createPartnerLink with error', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreatePartnerLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.CreatePartnerLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createPartnerLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createPartnerLink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createPartnerLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createPartnerLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes searchPartnerLinksStream with error', async () => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.SearchPartnerLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.SearchPartnerLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.searchPartnerLinks.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.searchPartnerLinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ads.datamanager.v1.PartnerLink[] = []; - stream.on('data', (response: protos.google.ads.datamanager.v1.PartnerLink) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.searchPartnerLinks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.searchPartnerLinks, request)); - assert( - (client.descriptors.page.searchPartnerLinks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes createPartnerLink with closed client', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreatePartnerLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.CreatePartnerLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createPartnerLink(request), expectedError); + }); + }); + + describe('deletePartnerLink', () => { + it('invokes deletePartnerLink without error', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.DeletePartnerLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.DeletePartnerLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deletePartnerLink = stubSimpleCall(expectedResponse); + const [response] = await client.deletePartnerLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deletePartnerLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deletePartnerLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with searchPartnerLinks without error', async () => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.SearchPartnerLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.SearchPartnerLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), - generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), - generateSampleMessage(new protos.google.ads.datamanager.v1.PartnerLink()), - ]; - client.descriptors.page.searchPartnerLinks.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ads.datamanager.v1.IPartnerLink[] = []; - const iterable = client.searchPartnerLinksAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes deletePartnerLink without error using callback', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.DeletePartnerLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.DeletePartnerLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deletePartnerLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deletePartnerLink( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.searchPartnerLinks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.searchPartnerLinks.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.deletePartnerLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deletePartnerLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with searchPartnerLinks with error', async () => { - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.SearchPartnerLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.SearchPartnerLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.searchPartnerLinks.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.searchPartnerLinksAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ads.datamanager.v1.IPartnerLink[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.searchPartnerLinks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.searchPartnerLinks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes deletePartnerLink with error', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.DeletePartnerLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.DeletePartnerLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deletePartnerLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deletePartnerLink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deletePartnerLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deletePartnerLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { + it('invokes deletePartnerLink with closed client', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.DeletePartnerLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.DeletePartnerLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deletePartnerLink(request), expectedError); + }); + }); + + describe('searchPartnerLinks', () => { + it('invokes searchPartnerLinks without error', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.SearchPartnerLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.SearchPartnerLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ads.datamanager.v1.PartnerLink(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.PartnerLink(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.PartnerLink(), + ), + ]; + client.innerApiCalls.searchPartnerLinks = + stubSimpleCall(expectedResponse); + const [response] = await client.searchPartnerLinks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.searchPartnerLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchPartnerLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('account', async () => { - const fakePath = "/rendered/path/account"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - }; - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.accountPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.accountPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('accountPath', () => { - const result = client.accountPath("accountTypeValue", "accountValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.accountPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes searchPartnerLinks without error using callback', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.SearchPartnerLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.SearchPartnerLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ads.datamanager.v1.PartnerLink(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.PartnerLink(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.PartnerLink(), + ), + ]; + client.innerApiCalls.searchPartnerLinks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.searchPartnerLinks( + request, + ( + err?: Error | null, + result?: protos.google.ads.datamanager.v1.IPartnerLink[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.searchPartnerLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchPartnerLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchAccountTypeFromAccountName', () => { - const result = client.matchAccountTypeFromAccountName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.accountPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes searchPartnerLinks with error', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.SearchPartnerLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.SearchPartnerLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.searchPartnerLinks = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.searchPartnerLinks(request), expectedError); + const actualRequest = ( + client.innerApiCalls.searchPartnerLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchPartnerLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchAccountFromAccountName', () => { - const result = client.matchAccountFromAccountName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.accountPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes searchPartnerLinksStream without error', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.SearchPartnerLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.SearchPartnerLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ads.datamanager.v1.PartnerLink(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.PartnerLink(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.PartnerLink(), + ), + ]; + client.descriptors.page.searchPartnerLinks.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.searchPartnerLinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ads.datamanager.v1.PartnerLink[] = []; + stream.on( + 'data', + (response: protos.google.ads.datamanager.v1.PartnerLink) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - describe('partnerLink', async () => { - const fakePath = "/rendered/path/partnerLink"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - partner_link: "partnerLinkValue", - }; - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.partnerLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.partnerLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('partnerLinkPath', () => { - const result = client.partnerLinkPath("accountTypeValue", "accountValue", "partnerLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.partnerLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromPartnerLinkName', () => { - const result = client.matchAccountTypeFromPartnerLinkName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromPartnerLinkName', () => { - const result = client.matchAccountFromPartnerLinkName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPartnerLinkFromPartnerLinkName', () => { - const result = client.matchPartnerLinkFromPartnerLinkName(fakePath); - assert.strictEqual(result, "partnerLinkValue"); - assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.searchPartnerLinks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.searchPartnerLinks, request), + ); + assert( + (client.descriptors.page.searchPartnerLinks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('userList', async () => { - const fakePath = "/rendered/path/userList"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list: "userListValue", - }; - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListPath', () => { - const result = client.userListPath("accountTypeValue", "accountValue", "userListValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromUserListName', () => { - const result = client.matchAccountTypeFromUserListName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromUserListName', () => { - const result = client.matchAccountFromUserListName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUserListFromUserListName', () => { - const result = client.matchUserListFromUserListName(fakePath); - assert.strictEqual(result, "userListValue"); - assert((client.pathTemplates.userListPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes searchPartnerLinksStream with error', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.SearchPartnerLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.SearchPartnerLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.searchPartnerLinks.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.searchPartnerLinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ads.datamanager.v1.PartnerLink[] = []; + stream.on( + 'data', + (response: protos.google.ads.datamanager.v1.PartnerLink) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - describe('userListDirectLicense', async () => { - const fakePath = "/rendered/path/userListDirectLicense"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list_direct_license: "userListDirectLicenseValue", - }; - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListDirectLicensePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListDirectLicensePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListDirectLicensePath', () => { - const result = client.userListDirectLicensePath("accountTypeValue", "accountValue", "userListDirectLicenseValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListDirectLicensePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromUserListDirectLicenseName', () => { - const result = client.matchAccountTypeFromUserListDirectLicenseName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromUserListDirectLicenseName', () => { - const result = client.matchAccountFromUserListDirectLicenseName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUserListDirectLicenseFromUserListDirectLicenseName', () => { - const result = client.matchUserListDirectLicenseFromUserListDirectLicenseName(fakePath); - assert.strictEqual(result, "userListDirectLicenseValue"); - assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.searchPartnerLinks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.searchPartnerLinks, request), + ); + assert( + (client.descriptors.page.searchPartnerLinks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('userListGlobalLicense', async () => { - const fakePath = "/rendered/path/userListGlobalLicense"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list_global_license: "userListGlobalLicenseValue", - }; - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListGlobalLicensePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListGlobalLicensePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListGlobalLicensePath', () => { - const result = client.userListGlobalLicensePath("accountTypeValue", "accountValue", "userListGlobalLicenseValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromUserListGlobalLicenseName', () => { - const result = client.matchAccountTypeFromUserListGlobalLicenseName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromUserListGlobalLicenseName', () => { - const result = client.matchAccountFromUserListGlobalLicenseName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('uses async iteration with searchPartnerLinks without error', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.SearchPartnerLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.SearchPartnerLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ads.datamanager.v1.PartnerLink(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.PartnerLink(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.PartnerLink(), + ), + ]; + client.descriptors.page.searchPartnerLinks.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ads.datamanager.v1.IPartnerLink[] = []; + const iterable = client.searchPartnerLinksAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.searchPartnerLinks.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.searchPartnerLinks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('matchUserListGlobalLicenseFromUserListGlobalLicenseName', () => { - const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseName(fakePath); - assert.strictEqual(result, "userListGlobalLicenseValue"); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with searchPartnerLinks with error', async () => { + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.SearchPartnerLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.SearchPartnerLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.searchPartnerLinks.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.searchPartnerLinksAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ads.datamanager.v1.IPartnerLink[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.searchPartnerLinks.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.searchPartnerLinks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('account', async () => { + const fakePath = '/rendered/path/account'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + }; + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.accountPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.accountPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('accountPath', () => { + const result = client.accountPath('accountTypeValue', 'accountValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.accountPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromAccountName', () => { + const result = client.matchAccountTypeFromAccountName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + (client.pathTemplates.accountPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromAccountName', () => { + const result = client.matchAccountFromAccountName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + (client.pathTemplates.accountPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userListGlobalLicenseCustomerInfo', async () => { - const fakePath = "/rendered/path/userListGlobalLicenseCustomerInfo"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list_global_license: "userListGlobalLicenseValue", - license_customer_info: "licenseCustomerInfoValue", - }; - const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListGlobalLicenseCustomerInfoPath', () => { - const result = client.userListGlobalLicenseCustomerInfoPath("accountTypeValue", "accountValue", "userListGlobalLicenseValue", "licenseCustomerInfoValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('partnerLink', async () => { + const fakePath = '/rendered/path/partnerLink'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + partner_link: 'partnerLinkValue', + }; + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.partnerLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.partnerLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('partnerLinkPath', () => { + const result = client.partnerLinkPath( + 'accountTypeValue', + 'accountValue', + 'partnerLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.partnerLinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromPartnerLinkName', () => { + const result = client.matchAccountTypeFromPartnerLinkName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + (client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromPartnerLinkName', () => { + const result = client.matchAccountFromPartnerLinkName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + (client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPartnerLinkFromPartnerLinkName', () => { + const result = client.matchPartnerLinkFromPartnerLinkName(fakePath); + assert.strictEqual(result, 'partnerLinkValue'); + assert( + (client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchAccountTypeFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('userList', async () => { + const fakePath = '/rendered/path/userList'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list: 'userListValue', + }; + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userListPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userListPath', () => { + const result = client.userListPath( + 'accountTypeValue', + 'accountValue', + 'userListValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userListPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListName', () => { + const result = client.matchAccountTypeFromUserListName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + (client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListName', () => { + const result = client.matchAccountFromUserListName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + (client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListFromUserListName', () => { + const result = client.matchUserListFromUserListName(fakePath); + assert.strictEqual(result, 'userListValue'); + assert( + (client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchAccountFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchAccountFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('userListDirectLicense', async () => { + const fakePath = '/rendered/path/userListDirectLicense'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list_direct_license: 'userListDirectLicenseValue', + }; + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListDirectLicensePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userListDirectLicensePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userListDirectLicensePath', () => { + const result = client.userListDirectLicensePath( + 'accountTypeValue', + 'accountValue', + 'userListDirectLicenseValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListDirectLicenseName', () => { + const result = + client.matchAccountTypeFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListDirectLicenseName', () => { + const result = + client.matchAccountFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListDirectLicenseFromUserListDirectLicenseName', () => { + const result = + client.matchUserListDirectLicenseFromUserListDirectLicenseName( + fakePath, + ); + assert.strictEqual(result, 'userListDirectLicenseValue'); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "userListGlobalLicenseValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('userListGlobalLicense', async () => { + const fakePath = '/rendered/path/userListGlobalLicense'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list_global_license: 'userListGlobalLicenseValue', + }; + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListGlobalLicensePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userListGlobalLicensePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userListGlobalLicensePath', () => { + const result = client.userListGlobalLicensePath( + 'accountTypeValue', + 'accountValue', + 'userListGlobalLicenseValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListGlobalLicenseName', () => { + const result = + client.matchAccountTypeFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListGlobalLicenseName', () => { + const result = + client.matchAccountFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseName', () => { + const result = + client.matchUserListGlobalLicenseFromUserListGlobalLicenseName( + fakePath, + ); + assert.strictEqual(result, 'userListGlobalLicenseValue'); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "licenseCustomerInfoValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userListGlobalLicenseCustomerInfo', async () => { + const fakePath = '/rendered/path/userListGlobalLicenseCustomerInfo'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list_global_license: 'userListGlobalLicenseValue', + license_customer_info: 'licenseCustomerInfoValue', + }; + const client = new partnerlinkserviceModule.v1.PartnerLinkServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListGlobalLicenseCustomerInfoPath', () => { + const result = client.userListGlobalLicenseCustomerInfoPath( + 'accountTypeValue', + 'accountValue', + 'userListGlobalLicenseValue', + 'licenseCustomerInfoValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchAccountTypeFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'accountTypeValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchAccountFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'accountValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'userListGlobalLicenseValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'licenseCustomerInfoValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ads-datamanager/test/gapic_user_list_direct_license_service_v1.ts b/packages/google-ads-datamanager/test/gapic_user_list_direct_license_service_v1.ts index 7a0268de80fd..38f0f8a29a5c 100644 --- a/packages/google-ads-datamanager/test/gapic_user_list_direct_license_service_v1.ts +++ b/packages/google-ads-datamanager/test/gapic_user_list_direct_license_service_v1.ts @@ -19,1095 +19,1626 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as userlistdirectlicenseserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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 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.UserListDirectLicenseServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient(); - 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 = userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient.servicePath; - assert.strictEqual(servicePath, 'datamanager.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.example.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.example.com'); - }); + it('has universeDomain', () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.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 userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.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 userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.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 userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + userlistdirectlicenseserviceModule.v1 + .UserListDirectLicenseServiceClient.servicePath; + assert.strictEqual(servicePath, 'datamanager.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + userlistdirectlicenseserviceModule.v1 + .UserListDirectLicenseServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { universeDomain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + }); - it('has port', () => { - const port = userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { universe_domain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + }); - it('should create a client with no option', () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient(); - assert(client); + 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 userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with gRPC fallback', () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - fallback: true, - }); - assert(client); + 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 userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { universeDomain: 'configured.example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.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 userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { universe_domain: 'example.com', universeDomain: 'example.net' }, + ); + }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.userListDirectLicenseServiceStub, undefined); - await client.initialize(); - assert(client.userListDirectLicenseServiceStub); - }); + it('has port', () => { + const port = + userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient + .port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the initialized client', done => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.userListDirectLicenseServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient(); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.userListDirectLicenseServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + fallback: true, + }, + ); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - 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 initialize method and supports deferred initialization', async () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.userListDirectLicenseServiceStub, undefined); + await client.initialize(); + assert(client.userListDirectLicenseServiceStub); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - 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('has close method for the initialized client', (done) => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + assert(client.userListDirectLicenseServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('createUserListDirectLicense', () => { - it('invokes createUserListDirectLicense without error', async () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.UserListDirectLicense() - ); - client.innerApiCalls.createUserListDirectLicense = stubSimpleCall(expectedResponse); - const [response] = await client.createUserListDirectLicense(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createUserListDirectLicense as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createUserListDirectLicense 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 userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.userListDirectLicenseServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createUserListDirectLicense without error using callback', async () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.UserListDirectLicense() - ); - client.innerApiCalls.createUserListDirectLicense = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createUserListDirectLicense( - request, - (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserListDirectLicense|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createUserListDirectLicense as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createUserListDirectLicense 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 userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + 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 createUserListDirectLicense with error', async () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createUserListDirectLicense = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createUserListDirectLicense(request), expectedError); - const actualRequest = (client.innerApiCalls.createUserListDirectLicense as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createUserListDirectLicense 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 userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + 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('createUserListDirectLicense', () => { + it('invokes createUserListDirectLicense without error', async () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense(), + ); + client.innerApiCalls.createUserListDirectLicense = + stubSimpleCall(expectedResponse); + const [response] = await client.createUserListDirectLicense(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createUserListDirectLicense as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createUserListDirectLicense as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createUserListDirectLicense with closed client', async () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createUserListDirectLicense(request), expectedError); - }); + it('invokes createUserListDirectLicense without error using callback', async () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense(), + ); + client.innerApiCalls.createUserListDirectLicense = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createUserListDirectLicense( + request, + ( + err?: Error | null, + result?: protos.google.ads.datamanager.v1.IUserListDirectLicense | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createUserListDirectLicense as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createUserListDirectLicense as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getUserListDirectLicense', () => { - it('invokes getUserListDirectLicense without error', async () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.GetUserListDirectLicenseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListDirectLicenseRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.UserListDirectLicense() - ); - client.innerApiCalls.getUserListDirectLicense = stubSimpleCall(expectedResponse); - const [response] = await client.getUserListDirectLicense(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getUserListDirectLicense as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUserListDirectLicense as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createUserListDirectLicense with error', async () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createUserListDirectLicense = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createUserListDirectLicense(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createUserListDirectLicense as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createUserListDirectLicense as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getUserListDirectLicense without error using callback', async () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.GetUserListDirectLicenseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListDirectLicenseRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.UserListDirectLicense() - ); - client.innerApiCalls.getUserListDirectLicense = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getUserListDirectLicense( - request, - (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserListDirectLicense|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getUserListDirectLicense as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUserListDirectLicense as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createUserListDirectLicense with closed client', async () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.CreateUserListDirectLicenseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createUserListDirectLicense(request), + expectedError, + ); + }); + }); + + describe('getUserListDirectLicense', () => { + it('invokes getUserListDirectLicense without error', async () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListDirectLicenseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.GetUserListDirectLicenseRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense(), + ); + client.innerApiCalls.getUserListDirectLicense = + stubSimpleCall(expectedResponse); + const [response] = await client.getUserListDirectLicense(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getUserListDirectLicense as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUserListDirectLicense as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getUserListDirectLicense with error', async () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.GetUserListDirectLicenseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListDirectLicenseRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getUserListDirectLicense = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getUserListDirectLicense(request), expectedError); - const actualRequest = (client.innerApiCalls.getUserListDirectLicense as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUserListDirectLicense as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getUserListDirectLicense without error using callback', async () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListDirectLicenseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.GetUserListDirectLicenseRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense(), + ); + client.innerApiCalls.getUserListDirectLicense = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getUserListDirectLicense( + request, + ( + err?: Error | null, + result?: protos.google.ads.datamanager.v1.IUserListDirectLicense | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getUserListDirectLicense as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUserListDirectLicense as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getUserListDirectLicense with closed client', async () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.GetUserListDirectLicenseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListDirectLicenseRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getUserListDirectLicense(request), expectedError); - }); + it('invokes getUserListDirectLicense with error', async () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListDirectLicenseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.GetUserListDirectLicenseRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getUserListDirectLicense = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getUserListDirectLicense(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getUserListDirectLicense as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUserListDirectLicense as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateUserListDirectLicense', () => { - it('invokes updateUserListDirectLicense without error', async () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest() - ); - request.userListDirectLicense ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest', ['userListDirectLicense', 'name']); - request.userListDirectLicense.name = defaultValue1; - const expectedHeaderRequestParams = `user_list_direct_license.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.UserListDirectLicense() - ); - client.innerApiCalls.updateUserListDirectLicense = stubSimpleCall(expectedResponse); - const [response] = await client.updateUserListDirectLicense(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateUserListDirectLicense as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUserListDirectLicense as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getUserListDirectLicense with closed client', async () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListDirectLicenseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.GetUserListDirectLicenseRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getUserListDirectLicense(request), + expectedError, + ); + }); + }); + + describe('updateUserListDirectLicense', () => { + it('invokes updateUserListDirectLicense without error', async () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest(), + ); + request.userListDirectLicense ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest', + ['userListDirectLicense', 'name'], + ); + request.userListDirectLicense.name = defaultValue1; + const expectedHeaderRequestParams = `user_list_direct_license.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense(), + ); + client.innerApiCalls.updateUserListDirectLicense = + stubSimpleCall(expectedResponse); + const [response] = await client.updateUserListDirectLicense(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateUserListDirectLicense as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUserListDirectLicense as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateUserListDirectLicense without error using callback', async () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest() - ); - request.userListDirectLicense ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest', ['userListDirectLicense', 'name']); - request.userListDirectLicense.name = defaultValue1; - const expectedHeaderRequestParams = `user_list_direct_license.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.UserListDirectLicense() - ); - client.innerApiCalls.updateUserListDirectLicense = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateUserListDirectLicense( - request, - (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserListDirectLicense|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateUserListDirectLicense as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUserListDirectLicense as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateUserListDirectLicense without error using callback', async () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest(), + ); + request.userListDirectLicense ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest', + ['userListDirectLicense', 'name'], + ); + request.userListDirectLicense.name = defaultValue1; + const expectedHeaderRequestParams = `user_list_direct_license.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense(), + ); + client.innerApiCalls.updateUserListDirectLicense = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateUserListDirectLicense( + request, + ( + err?: Error | null, + result?: protos.google.ads.datamanager.v1.IUserListDirectLicense | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateUserListDirectLicense as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUserListDirectLicense as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateUserListDirectLicense with error', async () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest() - ); - request.userListDirectLicense ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest', ['userListDirectLicense', 'name']); - request.userListDirectLicense.name = defaultValue1; - const expectedHeaderRequestParams = `user_list_direct_license.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateUserListDirectLicense = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateUserListDirectLicense(request), expectedError); - const actualRequest = (client.innerApiCalls.updateUserListDirectLicense as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUserListDirectLicense as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateUserListDirectLicense with error', async () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest(), + ); + request.userListDirectLicense ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest', + ['userListDirectLicense', 'name'], + ); + request.userListDirectLicense.name = defaultValue1; + const expectedHeaderRequestParams = `user_list_direct_license.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateUserListDirectLicense = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateUserListDirectLicense(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateUserListDirectLicense as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUserListDirectLicense as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateUserListDirectLicense with closed client', async () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest() - ); - request.userListDirectLicense ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest', ['userListDirectLicense', 'name']); - request.userListDirectLicense.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateUserListDirectLicense(request), expectedError); - }); + it('invokes updateUserListDirectLicense with closed client', async () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest(), + ); + request.userListDirectLicense ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.UpdateUserListDirectLicenseRequest', + ['userListDirectLicense', 'name'], + ); + request.userListDirectLicense.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateUserListDirectLicense(request), + expectedError, + ); + }); + }); + + describe('listUserListDirectLicenses', () => { + it('invokes listUserListDirectLicenses without error', async () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListDirectLicensesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListDirectLicensesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense(), + ), + ]; + client.innerApiCalls.listUserListDirectLicenses = + stubSimpleCall(expectedResponse); + const [response] = await client.listUserListDirectLicenses(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listUserListDirectLicenses as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUserListDirectLicenses as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listUserListDirectLicenses', () => { - it('invokes listUserListDirectLicenses without error', async () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListDirectLicensesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListDirectLicensesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), - ]; - client.innerApiCalls.listUserListDirectLicenses = stubSimpleCall(expectedResponse); - const [response] = await client.listUserListDirectLicenses(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listUserListDirectLicenses as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listUserListDirectLicenses as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listUserListDirectLicenses without error using callback', async () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListDirectLicensesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListDirectLicensesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense(), + ), + ]; + client.innerApiCalls.listUserListDirectLicenses = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listUserListDirectLicenses( + request, + ( + err?: Error | null, + result?: + | protos.google.ads.datamanager.v1.IUserListDirectLicense[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listUserListDirectLicenses as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUserListDirectLicenses as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listUserListDirectLicenses without error using callback', async () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListDirectLicensesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListDirectLicensesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), - ]; - client.innerApiCalls.listUserListDirectLicenses = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listUserListDirectLicenses( - request, - (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserListDirectLicense[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listUserListDirectLicenses as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listUserListDirectLicenses as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listUserListDirectLicenses with error', async () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListDirectLicensesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListDirectLicensesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listUserListDirectLicenses = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listUserListDirectLicenses(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listUserListDirectLicenses as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUserListDirectLicenses as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listUserListDirectLicenses with error', async () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListDirectLicensesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListDirectLicensesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listUserListDirectLicenses = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listUserListDirectLicenses(request), expectedError); - const actualRequest = (client.innerApiCalls.listUserListDirectLicenses as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listUserListDirectLicenses as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listUserListDirectLicensesStream without error', async () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListDirectLicensesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListDirectLicensesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense(), + ), + ]; + client.descriptors.page.listUserListDirectLicenses.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listUserListDirectLicensesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ads.datamanager.v1.UserListDirectLicense[] = + []; + stream.on( + 'data', + ( + response: protos.google.ads.datamanager.v1.UserListDirectLicense, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listUserListDirectLicensesStream without error', async () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListDirectLicensesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListDirectLicensesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), - ]; - client.descriptors.page.listUserListDirectLicenses.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listUserListDirectLicensesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ads.datamanager.v1.UserListDirectLicense[] = []; - stream.on('data', (response: protos.google.ads.datamanager.v1.UserListDirectLicense) => { - 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.listUserListDirectLicenses.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUserListDirectLicenses, request)); - assert( - (client.descriptors.page.listUserListDirectLicenses.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listUserListDirectLicenses + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listUserListDirectLicenses, request), + ); + assert( + ( + client.descriptors.page.listUserListDirectLicenses + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listUserListDirectLicensesStream with error', async () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListDirectLicensesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListDirectLicensesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listUserListDirectLicenses.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listUserListDirectLicensesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ads.datamanager.v1.UserListDirectLicense[] = []; - stream.on('data', (response: protos.google.ads.datamanager.v1.UserListDirectLicense) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listUserListDirectLicenses.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUserListDirectLicenses, request)); - assert( - (client.descriptors.page.listUserListDirectLicenses.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listUserListDirectLicensesStream with error', async () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListDirectLicensesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListDirectLicensesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listUserListDirectLicenses.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listUserListDirectLicensesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ads.datamanager.v1.UserListDirectLicense[] = + []; + stream.on( + 'data', + ( + response: protos.google.ads.datamanager.v1.UserListDirectLicense, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with listUserListDirectLicenses without error', async () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListDirectLicensesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListDirectLicensesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListDirectLicense()), - ]; - client.descriptors.page.listUserListDirectLicenses.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ads.datamanager.v1.IUserListDirectLicense[] = []; - const iterable = client.listUserListDirectLicensesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listUserListDirectLicenses.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listUserListDirectLicenses.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listUserListDirectLicenses + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listUserListDirectLicenses, request), + ); + assert( + ( + client.descriptors.page.listUserListDirectLicenses + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('uses async iteration with listUserListDirectLicenses with error', async () => { - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListDirectLicensesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListDirectLicensesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listUserListDirectLicenses.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listUserListDirectLicensesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ads.datamanager.v1.IUserListDirectLicense[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listUserListDirectLicenses.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listUserListDirectLicenses.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listUserListDirectLicenses without error', async () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListDirectLicensesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListDirectLicensesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListDirectLicense(), + ), + ]; + client.descriptors.page.listUserListDirectLicenses.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ads.datamanager.v1.IUserListDirectLicense[] = + []; + const iterable = client.listUserListDirectLicensesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listUserListDirectLicenses + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listUserListDirectLicenses + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); }); - describe('Path templates', () => { - - describe('account', async () => { - const fakePath = "/rendered/path/account"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - }; - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.accountPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.accountPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('accountPath', () => { - const result = client.accountPath("accountTypeValue", "accountValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.accountPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromAccountName', () => { - const result = client.matchAccountTypeFromAccountName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.accountPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromAccountName', () => { - const result = client.matchAccountFromAccountName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.accountPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listUserListDirectLicenses with error', async () => { + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListDirectLicensesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListDirectLicensesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listUserListDirectLicenses.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listUserListDirectLicensesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ads.datamanager.v1.IUserListDirectLicense[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listUserListDirectLicenses + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listUserListDirectLicenses + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('Path templates', () => { + describe('account', async () => { + const fakePath = '/rendered/path/account'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + }; + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.accountPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.accountPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('accountPath', () => { + const result = client.accountPath('accountTypeValue', 'accountValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.accountPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromAccountName', () => { + const result = client.matchAccountTypeFromAccountName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + (client.pathTemplates.accountPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromAccountName', () => { + const result = client.matchAccountFromAccountName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + (client.pathTemplates.accountPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('partnerLink', async () => { - const fakePath = "/rendered/path/partnerLink"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - partner_link: "partnerLinkValue", - }; - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.partnerLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.partnerLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('partnerLinkPath', () => { - const result = client.partnerLinkPath("accountTypeValue", "accountValue", "partnerLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.partnerLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromPartnerLinkName', () => { - const result = client.matchAccountTypeFromPartnerLinkName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromPartnerLinkName', () => { - const result = client.matchAccountFromPartnerLinkName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPartnerLinkFromPartnerLinkName', () => { - const result = client.matchPartnerLinkFromPartnerLinkName(fakePath); - assert.strictEqual(result, "partnerLinkValue"); - assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('partnerLink', async () => { + const fakePath = '/rendered/path/partnerLink'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + partner_link: 'partnerLinkValue', + }; + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.partnerLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.partnerLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('partnerLinkPath', () => { + const result = client.partnerLinkPath( + 'accountTypeValue', + 'accountValue', + 'partnerLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.partnerLinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromPartnerLinkName', () => { + const result = client.matchAccountTypeFromPartnerLinkName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + (client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromPartnerLinkName', () => { + const result = client.matchAccountFromPartnerLinkName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + (client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPartnerLinkFromPartnerLinkName', () => { + const result = client.matchPartnerLinkFromPartnerLinkName(fakePath); + assert.strictEqual(result, 'partnerLinkValue'); + assert( + (client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userList', async () => { - const fakePath = "/rendered/path/userList"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list: "userListValue", - }; - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListPath', () => { - const result = client.userListPath("accountTypeValue", "accountValue", "userListValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromUserListName', () => { - const result = client.matchAccountTypeFromUserListName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromUserListName', () => { - const result = client.matchAccountFromUserListName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUserListFromUserListName', () => { - const result = client.matchUserListFromUserListName(fakePath); - assert.strictEqual(result, "userListValue"); - assert((client.pathTemplates.userListPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userList', async () => { + const fakePath = '/rendered/path/userList'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list: 'userListValue', + }; + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.userListPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userListPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userListPath', () => { + const result = client.userListPath( + 'accountTypeValue', + 'accountValue', + 'userListValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userListPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListName', () => { + const result = client.matchAccountTypeFromUserListName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + (client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListName', () => { + const result = client.matchAccountFromUserListName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + (client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListFromUserListName', () => { + const result = client.matchUserListFromUserListName(fakePath); + assert.strictEqual(result, 'userListValue'); + assert( + (client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userListDirectLicense', async () => { - const fakePath = "/rendered/path/userListDirectLicense"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list_direct_license: "userListDirectLicenseValue", - }; - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListDirectLicensePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListDirectLicensePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListDirectLicensePath', () => { - const result = client.userListDirectLicensePath("accountTypeValue", "accountValue", "userListDirectLicenseValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListDirectLicensePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromUserListDirectLicenseName', () => { - const result = client.matchAccountTypeFromUserListDirectLicenseName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromUserListDirectLicenseName', () => { - const result = client.matchAccountFromUserListDirectLicenseName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUserListDirectLicenseFromUserListDirectLicenseName', () => { - const result = client.matchUserListDirectLicenseFromUserListDirectLicenseName(fakePath); - assert.strictEqual(result, "userListDirectLicenseValue"); - assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userListDirectLicense', async () => { + const fakePath = '/rendered/path/userListDirectLicense'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list_direct_license: 'userListDirectLicenseValue', + }; + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.userListDirectLicensePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userListDirectLicensePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userListDirectLicensePath', () => { + const result = client.userListDirectLicensePath( + 'accountTypeValue', + 'accountValue', + 'userListDirectLicenseValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListDirectLicenseName', () => { + const result = + client.matchAccountTypeFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListDirectLicenseName', () => { + const result = + client.matchAccountFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListDirectLicenseFromUserListDirectLicenseName', () => { + const result = + client.matchUserListDirectLicenseFromUserListDirectLicenseName( + fakePath, + ); + assert.strictEqual(result, 'userListDirectLicenseValue'); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userListGlobalLicense', async () => { - const fakePath = "/rendered/path/userListGlobalLicense"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list_global_license: "userListGlobalLicenseValue", - }; - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListGlobalLicensePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListGlobalLicensePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListGlobalLicensePath', () => { - const result = client.userListGlobalLicensePath("accountTypeValue", "accountValue", "userListGlobalLicenseValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromUserListGlobalLicenseName', () => { - const result = client.matchAccountTypeFromUserListGlobalLicenseName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromUserListGlobalLicenseName', () => { - const result = client.matchAccountFromUserListGlobalLicenseName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUserListGlobalLicenseFromUserListGlobalLicenseName', () => { - const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseName(fakePath); - assert.strictEqual(result, "userListGlobalLicenseValue"); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userListGlobalLicense', async () => { + const fakePath = '/rendered/path/userListGlobalLicense'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list_global_license: 'userListGlobalLicenseValue', + }; + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.userListGlobalLicensePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userListGlobalLicensePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userListGlobalLicensePath', () => { + const result = client.userListGlobalLicensePath( + 'accountTypeValue', + 'accountValue', + 'userListGlobalLicenseValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListGlobalLicenseName', () => { + const result = + client.matchAccountTypeFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListGlobalLicenseName', () => { + const result = + client.matchAccountFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseName', () => { + const result = + client.matchUserListGlobalLicenseFromUserListGlobalLicenseName( + fakePath, + ); + assert.strictEqual(result, 'userListGlobalLicenseValue'); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userListGlobalLicenseCustomerInfo', async () => { - const fakePath = "/rendered/path/userListGlobalLicenseCustomerInfo"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list_global_license: "userListGlobalLicenseValue", - license_customer_info: "licenseCustomerInfoValue", - }; - const client = new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListGlobalLicenseCustomerInfoPath', () => { - const result = client.userListGlobalLicenseCustomerInfoPath("accountTypeValue", "accountValue", "userListGlobalLicenseValue", "licenseCustomerInfoValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchAccountFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "userListGlobalLicenseValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "licenseCustomerInfoValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userListGlobalLicenseCustomerInfo', async () => { + const fakePath = '/rendered/path/userListGlobalLicenseCustomerInfo'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list_global_license: 'userListGlobalLicenseValue', + license_customer_info: 'licenseCustomerInfoValue', + }; + const client = + new userlistdirectlicenseserviceModule.v1.UserListDirectLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListGlobalLicenseCustomerInfoPath', () => { + const result = client.userListGlobalLicenseCustomerInfoPath( + 'accountTypeValue', + 'accountValue', + 'userListGlobalLicenseValue', + 'licenseCustomerInfoValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchAccountTypeFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'accountTypeValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchAccountFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'accountValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'userListGlobalLicenseValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'licenseCustomerInfoValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ads-datamanager/test/gapic_user_list_global_license_service_v1.ts b/packages/google-ads-datamanager/test/gapic_user_list_global_license_service_v1.ts index 22cc88ec5fb9..e8b60698217e 100644 --- a/packages/google-ads-datamanager/test/gapic_user_list_global_license_service_v1.ts +++ b/packages/google-ads-datamanager/test/gapic_user_list_global_license_service_v1.ts @@ -19,1340 +19,2015 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as userlistgloballicenseserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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 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.UserListGlobalLicenseServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'datamanager.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 = userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient.servicePath; - assert.strictEqual(servicePath, 'datamanager.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.example.com'); - }); + it('has universeDomain', () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.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 = + userlistgloballicenseserviceModule.v1 + .UserListGlobalLicenseServiceClient.servicePath; + assert.strictEqual(servicePath, 'datamanager.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + userlistgloballicenseserviceModule.v1 + .UserListGlobalLicenseServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { universeDomain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.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 userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.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 userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.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 userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { universe_domain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + }); - it('has port', () => { - const port = userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient.port; - assert(port); - assert(typeof port === 'number'); + 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 userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with no option', () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient(); - assert(client); + 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 userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { universeDomain: 'configured.example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.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 userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { universe_domain: 'example.com', universeDomain: 'example.net' }, + ); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = + userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient + .port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.userListGlobalLicenseServiceStub, undefined); - await client.initialize(); - assert(client.userListGlobalLicenseServiceStub); - }); + it('should create a client with no option', () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.userListGlobalLicenseServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + fallback: true, + }, + ); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.userListGlobalLicenseServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.userListGlobalLicenseServiceStub, undefined); + await client.initialize(); + assert(client.userListGlobalLicenseServiceStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - 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 close method for the initialized client', (done) => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + assert(client.userListGlobalLicenseServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - 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('has close method for the non-initialized client', (done) => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.userListGlobalLicenseServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('createUserListGlobalLicense', () => { - it('invokes createUserListGlobalLicense without error', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.UserListGlobalLicense() - ); - client.innerApiCalls.createUserListGlobalLicense = stubSimpleCall(expectedResponse); - const [response] = await client.createUserListGlobalLicense(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createUserListGlobalLicense as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createUserListGlobalLicense 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 userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + 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 createUserListGlobalLicense without error using callback', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.UserListGlobalLicense() - ); - client.innerApiCalls.createUserListGlobalLicense = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createUserListGlobalLicense( - request, - (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserListGlobalLicense|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createUserListGlobalLicense as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createUserListGlobalLicense 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 userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + 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('createUserListGlobalLicense', () => { + it('invokes createUserListGlobalLicense without error', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense(), + ); + client.innerApiCalls.createUserListGlobalLicense = + stubSimpleCall(expectedResponse); + const [response] = await client.createUserListGlobalLicense(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createUserListGlobalLicense as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createUserListGlobalLicense as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createUserListGlobalLicense with error', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createUserListGlobalLicense = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createUserListGlobalLicense(request), expectedError); - const actualRequest = (client.innerApiCalls.createUserListGlobalLicense as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createUserListGlobalLicense as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createUserListGlobalLicense without error using callback', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense(), + ); + client.innerApiCalls.createUserListGlobalLicense = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createUserListGlobalLicense( + request, + ( + err?: Error | null, + result?: protos.google.ads.datamanager.v1.IUserListGlobalLicense | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createUserListGlobalLicense as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createUserListGlobalLicense as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createUserListGlobalLicense with closed client', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createUserListGlobalLicense(request), expectedError); - }); + it('invokes createUserListGlobalLicense with error', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createUserListGlobalLicense = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createUserListGlobalLicense(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createUserListGlobalLicense as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createUserListGlobalLicense as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateUserListGlobalLicense', () => { - it('invokes updateUserListGlobalLicense without error', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest() - ); - request.userListGlobalLicense ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest', ['userListGlobalLicense', 'name']); - request.userListGlobalLicense.name = defaultValue1; - const expectedHeaderRequestParams = `user_list_global_license.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.UserListGlobalLicense() - ); - client.innerApiCalls.updateUserListGlobalLicense = stubSimpleCall(expectedResponse); - const [response] = await client.updateUserListGlobalLicense(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateUserListGlobalLicense as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUserListGlobalLicense as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createUserListGlobalLicense with closed client', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.CreateUserListGlobalLicenseRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createUserListGlobalLicense(request), + expectedError, + ); + }); + }); + + describe('updateUserListGlobalLicense', () => { + it('invokes updateUserListGlobalLicense without error', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest(), + ); + request.userListGlobalLicense ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest', + ['userListGlobalLicense', 'name'], + ); + request.userListGlobalLicense.name = defaultValue1; + const expectedHeaderRequestParams = `user_list_global_license.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense(), + ); + client.innerApiCalls.updateUserListGlobalLicense = + stubSimpleCall(expectedResponse); + const [response] = await client.updateUserListGlobalLicense(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateUserListGlobalLicense as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUserListGlobalLicense as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateUserListGlobalLicense without error using callback', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest() - ); - request.userListGlobalLicense ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest', ['userListGlobalLicense', 'name']); - request.userListGlobalLicense.name = defaultValue1; - const expectedHeaderRequestParams = `user_list_global_license.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.UserListGlobalLicense() - ); - client.innerApiCalls.updateUserListGlobalLicense = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateUserListGlobalLicense( - request, - (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserListGlobalLicense|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateUserListGlobalLicense as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUserListGlobalLicense as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateUserListGlobalLicense without error using callback', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest(), + ); + request.userListGlobalLicense ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest', + ['userListGlobalLicense', 'name'], + ); + request.userListGlobalLicense.name = defaultValue1; + const expectedHeaderRequestParams = `user_list_global_license.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense(), + ); + client.innerApiCalls.updateUserListGlobalLicense = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateUserListGlobalLicense( + request, + ( + err?: Error | null, + result?: protos.google.ads.datamanager.v1.IUserListGlobalLicense | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateUserListGlobalLicense as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUserListGlobalLicense as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateUserListGlobalLicense with error', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest() - ); - request.userListGlobalLicense ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest', ['userListGlobalLicense', 'name']); - request.userListGlobalLicense.name = defaultValue1; - const expectedHeaderRequestParams = `user_list_global_license.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateUserListGlobalLicense = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateUserListGlobalLicense(request), expectedError); - const actualRequest = (client.innerApiCalls.updateUserListGlobalLicense as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUserListGlobalLicense as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateUserListGlobalLicense with error', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest(), + ); + request.userListGlobalLicense ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest', + ['userListGlobalLicense', 'name'], + ); + request.userListGlobalLicense.name = defaultValue1; + const expectedHeaderRequestParams = `user_list_global_license.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateUserListGlobalLicense = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateUserListGlobalLicense(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateUserListGlobalLicense as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUserListGlobalLicense as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateUserListGlobalLicense with closed client', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest() - ); - request.userListGlobalLicense ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest', ['userListGlobalLicense', 'name']); - request.userListGlobalLicense.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateUserListGlobalLicense(request), expectedError); - }); + it('invokes updateUserListGlobalLicense with closed client', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest(), + ); + request.userListGlobalLicense ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.UpdateUserListGlobalLicenseRequest', + ['userListGlobalLicense', 'name'], + ); + request.userListGlobalLicense.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateUserListGlobalLicense(request), + expectedError, + ); + }); + }); + + describe('getUserListGlobalLicense', () => { + it('invokes getUserListGlobalLicense without error', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense(), + ); + client.innerApiCalls.getUserListGlobalLicense = + stubSimpleCall(expectedResponse); + const [response] = await client.getUserListGlobalLicense(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getUserListGlobalLicense as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUserListGlobalLicense as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getUserListGlobalLicense', () => { - it('invokes getUserListGlobalLicense without error', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.UserListGlobalLicense() - ); - client.innerApiCalls.getUserListGlobalLicense = stubSimpleCall(expectedResponse); - const [response] = await client.getUserListGlobalLicense(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getUserListGlobalLicense as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUserListGlobalLicense as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getUserListGlobalLicense without error using callback', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense(), + ); + client.innerApiCalls.getUserListGlobalLicense = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getUserListGlobalLicense( + request, + ( + err?: Error | null, + result?: protos.google.ads.datamanager.v1.IUserListGlobalLicense | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getUserListGlobalLicense as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUserListGlobalLicense as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getUserListGlobalLicense without error using callback', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.UserListGlobalLicense() - ); - client.innerApiCalls.getUserListGlobalLicense = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getUserListGlobalLicense( - request, - (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserListGlobalLicense|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getUserListGlobalLicense as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUserListGlobalLicense as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getUserListGlobalLicense with error', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getUserListGlobalLicense = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getUserListGlobalLicense(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getUserListGlobalLicense as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUserListGlobalLicense as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getUserListGlobalLicense with error', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getUserListGlobalLicense = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getUserListGlobalLicense(request), expectedError); - const actualRequest = (client.innerApiCalls.getUserListGlobalLicense as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUserListGlobalLicense as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getUserListGlobalLicense with closed client', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getUserListGlobalLicense(request), + expectedError, + ); + }); + }); + + describe('listUserListGlobalLicenses', () => { + it('invokes listUserListGlobalLicenses without error', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense(), + ), + ]; + client.innerApiCalls.listUserListGlobalLicenses = + stubSimpleCall(expectedResponse); + const [response] = await client.listUserListGlobalLicenses(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listUserListGlobalLicenses as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUserListGlobalLicenses as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getUserListGlobalLicense with closed client', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListGlobalLicenseRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getUserListGlobalLicense(request), expectedError); - }); + it('invokes listUserListGlobalLicenses without error using callback', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense(), + ), + ]; + client.innerApiCalls.listUserListGlobalLicenses = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listUserListGlobalLicenses( + request, + ( + err?: Error | null, + result?: + | protos.google.ads.datamanager.v1.IUserListGlobalLicense[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listUserListGlobalLicenses as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUserListGlobalLicenses as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listUserListGlobalLicenses', () => { - it('invokes listUserListGlobalLicenses without error', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), - ]; - client.innerApiCalls.listUserListGlobalLicenses = stubSimpleCall(expectedResponse); - const [response] = await client.listUserListGlobalLicenses(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listUserListGlobalLicenses as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listUserListGlobalLicenses as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listUserListGlobalLicenses with error', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listUserListGlobalLicenses = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listUserListGlobalLicenses(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listUserListGlobalLicenses as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUserListGlobalLicenses as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listUserListGlobalLicenses without error using callback', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), - ]; - client.innerApiCalls.listUserListGlobalLicenses = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listUserListGlobalLicenses( - request, - (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserListGlobalLicense[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listUserListGlobalLicenses as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listUserListGlobalLicenses as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listUserListGlobalLicensesStream without error', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense(), + ), + ]; + client.descriptors.page.listUserListGlobalLicenses.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listUserListGlobalLicensesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ads.datamanager.v1.UserListGlobalLicense[] = + []; + stream.on( + 'data', + ( + response: protos.google.ads.datamanager.v1.UserListGlobalLicense, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listUserListGlobalLicenses with error', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listUserListGlobalLicenses = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listUserListGlobalLicenses(request), expectedError); - const actualRequest = (client.innerApiCalls.listUserListGlobalLicenses as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listUserListGlobalLicenses as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listUserListGlobalLicenses + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listUserListGlobalLicenses, request), + ); + assert( + ( + client.descriptors.page.listUserListGlobalLicenses + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listUserListGlobalLicensesStream without error', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), - ]; - client.descriptors.page.listUserListGlobalLicenses.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listUserListGlobalLicensesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ads.datamanager.v1.UserListGlobalLicense[] = []; - stream.on('data', (response: protos.google.ads.datamanager.v1.UserListGlobalLicense) => { - 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.listUserListGlobalLicenses.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUserListGlobalLicenses, request)); - assert( - (client.descriptors.page.listUserListGlobalLicenses.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listUserListGlobalLicensesStream with error', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listUserListGlobalLicenses.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listUserListGlobalLicensesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ads.datamanager.v1.UserListGlobalLicense[] = + []; + stream.on( + 'data', + ( + response: protos.google.ads.datamanager.v1.UserListGlobalLicense, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listUserListGlobalLicensesStream with error', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listUserListGlobalLicenses.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listUserListGlobalLicensesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ads.datamanager.v1.UserListGlobalLicense[] = []; - stream.on('data', (response: protos.google.ads.datamanager.v1.UserListGlobalLicense) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listUserListGlobalLicenses.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUserListGlobalLicenses, request)); - assert( - (client.descriptors.page.listUserListGlobalLicenses.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listUserListGlobalLicenses + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listUserListGlobalLicenses, request), + ); + assert( + ( + client.descriptors.page.listUserListGlobalLicenses + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('uses async iteration with listUserListGlobalLicenses without error', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicense()), - ]; - client.descriptors.page.listUserListGlobalLicenses.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ads.datamanager.v1.IUserListGlobalLicense[] = []; - const iterable = client.listUserListGlobalLicensesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listUserListGlobalLicenses.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listUserListGlobalLicenses.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listUserListGlobalLicenses without error', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicense(), + ), + ]; + client.descriptors.page.listUserListGlobalLicenses.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ads.datamanager.v1.IUserListGlobalLicense[] = + []; + const iterable = client.listUserListGlobalLicensesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listUserListGlobalLicenses + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listUserListGlobalLicenses + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('uses async iteration with listUserListGlobalLicenses with error', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listUserListGlobalLicenses.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listUserListGlobalLicensesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ads.datamanager.v1.IUserListGlobalLicense[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listUserListGlobalLicenses.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listUserListGlobalLicenses.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listUserListGlobalLicenses with error', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListGlobalLicensesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listUserListGlobalLicenses.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listUserListGlobalLicensesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ads.datamanager.v1.IUserListGlobalLicense[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listUserListGlobalLicenses + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listUserListGlobalLicenses + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listUserListGlobalLicenseCustomerInfos', () => { + it('invokes listUserListGlobalLicenseCustomerInfos without error', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo(), + ), + ]; + client.innerApiCalls.listUserListGlobalLicenseCustomerInfos = + stubSimpleCall(expectedResponse); + const [response] = + await client.listUserListGlobalLicenseCustomerInfos(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listUserListGlobalLicenseCustomerInfos as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUserListGlobalLicenseCustomerInfos as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listUserListGlobalLicenseCustomerInfos', () => { - it('invokes listUserListGlobalLicenseCustomerInfos without error', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), - ]; - client.innerApiCalls.listUserListGlobalLicenseCustomerInfos = stubSimpleCall(expectedResponse); - const [response] = await client.listUserListGlobalLicenseCustomerInfos(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listUserListGlobalLicenseCustomerInfos as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listUserListGlobalLicenseCustomerInfos as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listUserListGlobalLicenseCustomerInfos without error using callback', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo(), + ), + ]; + client.innerApiCalls.listUserListGlobalLicenseCustomerInfos = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listUserListGlobalLicenseCustomerInfos( + request, + ( + err?: Error | null, + result?: + | protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listUserListGlobalLicenseCustomerInfos as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUserListGlobalLicenseCustomerInfos as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listUserListGlobalLicenseCustomerInfos without error using callback', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), - ]; - client.innerApiCalls.listUserListGlobalLicenseCustomerInfos = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listUserListGlobalLicenseCustomerInfos( - request, - (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listUserListGlobalLicenseCustomerInfos as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listUserListGlobalLicenseCustomerInfos as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listUserListGlobalLicenseCustomerInfos with error', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listUserListGlobalLicenseCustomerInfos = + stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.listUserListGlobalLicenseCustomerInfos(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listUserListGlobalLicenseCustomerInfos as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUserListGlobalLicenseCustomerInfos as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listUserListGlobalLicenseCustomerInfos with error', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listUserListGlobalLicenseCustomerInfos = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listUserListGlobalLicenseCustomerInfos(request), expectedError); - const actualRequest = (client.innerApiCalls.listUserListGlobalLicenseCustomerInfos as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listUserListGlobalLicenseCustomerInfos as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listUserListGlobalLicenseCustomerInfosStream without error', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo(), + ), + ]; + client.descriptors.page.listUserListGlobalLicenseCustomerInfos.createStream = + stubPageStreamingCall(expectedResponse); + const stream = + client.listUserListGlobalLicenseCustomerInfosStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo[] = + []; + stream.on( + 'data', + ( + response: protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listUserListGlobalLicenseCustomerInfosStream without error', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), - ]; - client.descriptors.page.listUserListGlobalLicenseCustomerInfos.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listUserListGlobalLicenseCustomerInfosStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo[] = []; - stream.on('data', (response: protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo) => { - 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.listUserListGlobalLicenseCustomerInfos.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUserListGlobalLicenseCustomerInfos, request)); - assert( - (client.descriptors.page.listUserListGlobalLicenseCustomerInfos.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + ( + client.descriptors.page.listUserListGlobalLicenseCustomerInfos + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listUserListGlobalLicenseCustomerInfos, + request, + ), + ); + assert( + ( + client.descriptors.page.listUserListGlobalLicenseCustomerInfos + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listUserListGlobalLicenseCustomerInfosStream with error', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listUserListGlobalLicenseCustomerInfos.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listUserListGlobalLicenseCustomerInfosStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo[] = []; - stream.on('data', (response: protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listUserListGlobalLicenseCustomerInfos.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUserListGlobalLicenseCustomerInfos, request)); - assert( - (client.descriptors.page.listUserListGlobalLicenseCustomerInfos.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listUserListGlobalLicenseCustomerInfosStream with error', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listUserListGlobalLicenseCustomerInfos.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = + client.listUserListGlobalLicenseCustomerInfosStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo[] = + []; + stream.on( + 'data', + ( + response: protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with listUserListGlobalLicenseCustomerInfos without error', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo()), - ]; - client.descriptors.page.listUserListGlobalLicenseCustomerInfos.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo[] = []; - const iterable = client.listUserListGlobalLicenseCustomerInfosAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listUserListGlobalLicenseCustomerInfos.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listUserListGlobalLicenseCustomerInfos.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listUserListGlobalLicenseCustomerInfos + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listUserListGlobalLicenseCustomerInfos, + request, + ), + ); + assert( + ( + client.descriptors.page.listUserListGlobalLicenseCustomerInfos + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('uses async iteration with listUserListGlobalLicenseCustomerInfos with error', async () => { - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listUserListGlobalLicenseCustomerInfos.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listUserListGlobalLicenseCustomerInfosAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listUserListGlobalLicenseCustomerInfos.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listUserListGlobalLicenseCustomerInfos.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listUserListGlobalLicenseCustomerInfos without error', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo(), + ), + generateSampleMessage( + new protos.google.ads.datamanager.v1.UserListGlobalLicenseCustomerInfo(), + ), + ]; + client.descriptors.page.listUserListGlobalLicenseCustomerInfos.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo[] = + []; + const iterable = + client.listUserListGlobalLicenseCustomerInfosAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listUserListGlobalLicenseCustomerInfos + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listUserListGlobalLicenseCustomerInfos + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); }); - describe('Path templates', () => { - - describe('account', async () => { - const fakePath = "/rendered/path/account"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - }; - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.accountPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.accountPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('accountPath', () => { - const result = client.accountPath("accountTypeValue", "accountValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.accountPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromAccountName', () => { - const result = client.matchAccountTypeFromAccountName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.accountPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromAccountName', () => { - const result = client.matchAccountFromAccountName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.accountPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listUserListGlobalLicenseCustomerInfos with error', async () => { + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListGlobalLicenseCustomerInfosRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listUserListGlobalLicenseCustomerInfos.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = + client.listUserListGlobalLicenseCustomerInfosAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ads.datamanager.v1.IUserListGlobalLicenseCustomerInfo[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listUserListGlobalLicenseCustomerInfos + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listUserListGlobalLicenseCustomerInfos + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('Path templates', () => { + describe('account', async () => { + const fakePath = '/rendered/path/account'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + }; + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.accountPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.accountPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('accountPath', () => { + const result = client.accountPath('accountTypeValue', 'accountValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.accountPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromAccountName', () => { + const result = client.matchAccountTypeFromAccountName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + (client.pathTemplates.accountPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromAccountName', () => { + const result = client.matchAccountFromAccountName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + (client.pathTemplates.accountPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('partnerLink', async () => { - const fakePath = "/rendered/path/partnerLink"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - partner_link: "partnerLinkValue", - }; - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.partnerLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.partnerLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('partnerLinkPath', () => { - const result = client.partnerLinkPath("accountTypeValue", "accountValue", "partnerLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.partnerLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromPartnerLinkName', () => { - const result = client.matchAccountTypeFromPartnerLinkName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromPartnerLinkName', () => { - const result = client.matchAccountFromPartnerLinkName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPartnerLinkFromPartnerLinkName', () => { - const result = client.matchPartnerLinkFromPartnerLinkName(fakePath); - assert.strictEqual(result, "partnerLinkValue"); - assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('partnerLink', async () => { + const fakePath = '/rendered/path/partnerLink'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + partner_link: 'partnerLinkValue', + }; + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.partnerLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.partnerLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('partnerLinkPath', () => { + const result = client.partnerLinkPath( + 'accountTypeValue', + 'accountValue', + 'partnerLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.partnerLinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromPartnerLinkName', () => { + const result = client.matchAccountTypeFromPartnerLinkName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + (client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromPartnerLinkName', () => { + const result = client.matchAccountFromPartnerLinkName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + (client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPartnerLinkFromPartnerLinkName', () => { + const result = client.matchPartnerLinkFromPartnerLinkName(fakePath); + assert.strictEqual(result, 'partnerLinkValue'); + assert( + (client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userList', async () => { - const fakePath = "/rendered/path/userList"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list: "userListValue", - }; - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListPath', () => { - const result = client.userListPath("accountTypeValue", "accountValue", "userListValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromUserListName', () => { - const result = client.matchAccountTypeFromUserListName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromUserListName', () => { - const result = client.matchAccountFromUserListName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUserListFromUserListName', () => { - const result = client.matchUserListFromUserListName(fakePath); - assert.strictEqual(result, "userListValue"); - assert((client.pathTemplates.userListPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userList', async () => { + const fakePath = '/rendered/path/userList'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list: 'userListValue', + }; + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.userListPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userListPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userListPath', () => { + const result = client.userListPath( + 'accountTypeValue', + 'accountValue', + 'userListValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userListPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListName', () => { + const result = client.matchAccountTypeFromUserListName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + (client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListName', () => { + const result = client.matchAccountFromUserListName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + (client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListFromUserListName', () => { + const result = client.matchUserListFromUserListName(fakePath); + assert.strictEqual(result, 'userListValue'); + assert( + (client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userListDirectLicense', async () => { - const fakePath = "/rendered/path/userListDirectLicense"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list_direct_license: "userListDirectLicenseValue", - }; - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListDirectLicensePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListDirectLicensePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListDirectLicensePath', () => { - const result = client.userListDirectLicensePath("accountTypeValue", "accountValue", "userListDirectLicenseValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListDirectLicensePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromUserListDirectLicenseName', () => { - const result = client.matchAccountTypeFromUserListDirectLicenseName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromUserListDirectLicenseName', () => { - const result = client.matchAccountFromUserListDirectLicenseName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUserListDirectLicenseFromUserListDirectLicenseName', () => { - const result = client.matchUserListDirectLicenseFromUserListDirectLicenseName(fakePath); - assert.strictEqual(result, "userListDirectLicenseValue"); - assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userListDirectLicense', async () => { + const fakePath = '/rendered/path/userListDirectLicense'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list_direct_license: 'userListDirectLicenseValue', + }; + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.userListDirectLicensePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userListDirectLicensePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userListDirectLicensePath', () => { + const result = client.userListDirectLicensePath( + 'accountTypeValue', + 'accountValue', + 'userListDirectLicenseValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListDirectLicenseName', () => { + const result = + client.matchAccountTypeFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListDirectLicenseName', () => { + const result = + client.matchAccountFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListDirectLicenseFromUserListDirectLicenseName', () => { + const result = + client.matchUserListDirectLicenseFromUserListDirectLicenseName( + fakePath, + ); + assert.strictEqual(result, 'userListDirectLicenseValue'); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userListGlobalLicense', async () => { - const fakePath = "/rendered/path/userListGlobalLicense"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list_global_license: "userListGlobalLicenseValue", - }; - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListGlobalLicensePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListGlobalLicensePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListGlobalLicensePath', () => { - const result = client.userListGlobalLicensePath("accountTypeValue", "accountValue", "userListGlobalLicenseValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromUserListGlobalLicenseName', () => { - const result = client.matchAccountTypeFromUserListGlobalLicenseName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromUserListGlobalLicenseName', () => { - const result = client.matchAccountFromUserListGlobalLicenseName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUserListGlobalLicenseFromUserListGlobalLicenseName', () => { - const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseName(fakePath); - assert.strictEqual(result, "userListGlobalLicenseValue"); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userListGlobalLicense', async () => { + const fakePath = '/rendered/path/userListGlobalLicense'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list_global_license: 'userListGlobalLicenseValue', + }; + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.userListGlobalLicensePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userListGlobalLicensePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userListGlobalLicensePath', () => { + const result = client.userListGlobalLicensePath( + 'accountTypeValue', + 'accountValue', + 'userListGlobalLicenseValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListGlobalLicenseName', () => { + const result = + client.matchAccountTypeFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListGlobalLicenseName', () => { + const result = + client.matchAccountFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseName', () => { + const result = + client.matchUserListGlobalLicenseFromUserListGlobalLicenseName( + fakePath, + ); + assert.strictEqual(result, 'userListGlobalLicenseValue'); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userListGlobalLicenseCustomerInfo', async () => { - const fakePath = "/rendered/path/userListGlobalLicenseCustomerInfo"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list_global_license: "userListGlobalLicenseValue", - license_customer_info: "licenseCustomerInfoValue", - }; - const client = new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListGlobalLicenseCustomerInfoPath', () => { - const result = client.userListGlobalLicenseCustomerInfoPath("accountTypeValue", "accountValue", "userListGlobalLicenseValue", "licenseCustomerInfoValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchAccountFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "userListGlobalLicenseValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "licenseCustomerInfoValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userListGlobalLicenseCustomerInfo', async () => { + const fakePath = '/rendered/path/userListGlobalLicenseCustomerInfo'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list_global_license: 'userListGlobalLicenseValue', + license_customer_info: 'licenseCustomerInfoValue', + }; + const client = + new userlistgloballicenseserviceModule.v1.UserListGlobalLicenseServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListGlobalLicenseCustomerInfoPath', () => { + const result = client.userListGlobalLicenseCustomerInfoPath( + 'accountTypeValue', + 'accountValue', + 'userListGlobalLicenseValue', + 'licenseCustomerInfoValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchAccountTypeFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'accountTypeValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchAccountFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'accountValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'userListGlobalLicenseValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'licenseCustomerInfoValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ads-datamanager/test/gapic_user_list_service_v1.ts b/packages/google-ads-datamanager/test/gapic_user_list_service_v1.ts index be3072a90ac6..7fa6c45069d4 100644 --- a/packages/google-ads-datamanager/test/gapic_user_list_service_v1.ts +++ b/packages/google-ads-datamanager/test/gapic_user_list_service_v1.ts @@ -19,1203 +19,1576 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as userlistserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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 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.UserListServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new userlistserviceModule.v1.UserListServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new userlistserviceModule.v1.UserListServiceClient(); - 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 = userlistserviceModule.v1.UserListServiceClient.servicePath; - assert.strictEqual(servicePath, 'datamanager.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = userlistserviceModule.v1.UserListServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new userlistserviceModule.v1.UserListServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.example.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new userlistserviceModule.v1.UserListServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new userlistserviceModule.v1.UserListServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.example.com'); - }); + it('has universeDomain', () => { + const client = new userlistserviceModule.v1.UserListServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.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 userlistserviceModule.v1.UserListServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.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 userlistserviceModule.v1.UserListServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'datamanager.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 userlistserviceModule.v1.UserListServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + userlistserviceModule.v1.UserListServiceClient.servicePath; + assert.strictEqual(servicePath, 'datamanager.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + userlistserviceModule.v1.UserListServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'datamanager.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + }); - it('has port', () => { - const port = userlistserviceModule.v1.UserListServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + }); - it('should create a client with no option', () => { - const client = new userlistserviceModule.v1.UserListServiceClient(); - assert(client); + 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 userlistserviceModule.v1.UserListServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with gRPC fallback', () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - fallback: true, - }); - assert(client); + 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 userlistserviceModule.v1.UserListServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'datamanager.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.userListServiceStub, undefined); - await client.initialize(); - assert(client.userListServiceStub); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new userlistserviceModule.v1.UserListServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has close method for the initialized client', done => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.userListServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = userlistserviceModule.v1.UserListServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the non-initialized client', done => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.userListServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new userlistserviceModule.v1.UserListServiceClient(); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new userlistserviceModule.v1.UserListServiceClient({ - 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('should create a client with gRPC fallback', () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new userlistserviceModule.v1.UserListServiceClient({ - 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('has initialize method and supports deferred initialization', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.userListServiceStub, undefined); + await client.initialize(); + assert(client.userListServiceStub); }); - describe('getUserList', () => { - it('invokes getUserList without error', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.GetUserListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.UserList() - ); - client.innerApiCalls.getUserList = stubSimpleCall(expectedResponse); - const [response] = await client.getUserList(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getUserList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUserList 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 userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.userListServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getUserList without error using callback', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.GetUserListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.UserList() - ); - client.innerApiCalls.getUserList = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getUserList( - request, - (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserList|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getUserList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUserList 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 userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.userListServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getUserList with error', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.GetUserListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getUserList = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getUserList(request), expectedError); - const actualRequest = (client.innerApiCalls.getUserList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUserList 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 userlistserviceModule.v1.UserListServiceClient({ + 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 getUserList with closed client', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.GetUserListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.GetUserListRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getUserList(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new userlistserviceModule.v1.UserListServiceClient({ + 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('getUserList', () => { + it('invokes getUserList without error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.GetUserListRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserList(), + ); + client.innerApiCalls.getUserList = stubSimpleCall(expectedResponse); + const [response] = await client.getUserList(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getUserList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUserList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createUserList', () => { - it('invokes createUserList without error', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.CreateUserListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.UserList() - ); - client.innerApiCalls.createUserList = stubSimpleCall(expectedResponse); - const [response] = await client.createUserList(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createUserList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createUserList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getUserList without error using callback', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.GetUserListRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserList(), + ); + client.innerApiCalls.getUserList = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getUserList( + request, + ( + err?: Error | null, + result?: protos.google.ads.datamanager.v1.IUserList | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getUserList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUserList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createUserList without error using callback', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.CreateUserListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.UserList() - ); - client.innerApiCalls.createUserList = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createUserList( - request, - (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserList|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createUserList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createUserList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getUserList with error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.GetUserListRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getUserList = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getUserList(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getUserList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUserList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createUserList with error', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.CreateUserListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createUserList = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createUserList(request), expectedError); - const actualRequest = (client.innerApiCalls.createUserList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createUserList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getUserList with closed client', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.GetUserListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.GetUserListRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getUserList(request), expectedError); + }); + }); + + describe('createUserList', () => { + it('invokes createUserList without error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.CreateUserListRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserList(), + ); + client.innerApiCalls.createUserList = stubSimpleCall(expectedResponse); + const [response] = await client.createUserList(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createUserList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createUserList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createUserList with closed client', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.CreateUserListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.CreateUserListRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createUserList(request), expectedError); - }); + it('invokes createUserList without error using callback', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.CreateUserListRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserList(), + ); + client.innerApiCalls.createUserList = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createUserList( + request, + ( + err?: Error | null, + result?: protos.google.ads.datamanager.v1.IUserList | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createUserList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createUserList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateUserList', () => { - it('invokes updateUserList without error', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.UpdateUserListRequest() - ); - request.userList ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListRequest', ['userList', 'name']); - request.userList.name = defaultValue1; - const expectedHeaderRequestParams = `user_list.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.UserList() - ); - client.innerApiCalls.updateUserList = stubSimpleCall(expectedResponse); - const [response] = await client.updateUserList(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateUserList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUserList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createUserList with error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.CreateUserListRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createUserList = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createUserList(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createUserList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createUserList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateUserList without error using callback', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.UpdateUserListRequest() - ); - request.userList ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListRequest', ['userList', 'name']); - request.userList.name = defaultValue1; - const expectedHeaderRequestParams = `user_list.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ads.datamanager.v1.UserList() - ); - client.innerApiCalls.updateUserList = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateUserList( - request, - (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserList|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateUserList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUserList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createUserList with closed client', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.CreateUserListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.CreateUserListRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createUserList(request), expectedError); + }); + }); + + describe('updateUserList', () => { + it('invokes updateUserList without error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListRequest(), + ); + request.userList ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.UpdateUserListRequest', + ['userList', 'name'], + ); + request.userList.name = defaultValue1; + const expectedHeaderRequestParams = `user_list.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserList(), + ); + client.innerApiCalls.updateUserList = stubSimpleCall(expectedResponse); + const [response] = await client.updateUserList(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateUserList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUserList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateUserList with error', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.UpdateUserListRequest() - ); - request.userList ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListRequest', ['userList', 'name']); - request.userList.name = defaultValue1; - const expectedHeaderRequestParams = `user_list.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateUserList = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateUserList(request), expectedError); - const actualRequest = (client.innerApiCalls.updateUserList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateUserList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateUserList without error using callback', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListRequest(), + ); + request.userList ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.UpdateUserListRequest', + ['userList', 'name'], + ); + request.userList.name = defaultValue1; + const expectedHeaderRequestParams = `user_list.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ads.datamanager.v1.UserList(), + ); + client.innerApiCalls.updateUserList = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateUserList( + request, + ( + err?: Error | null, + result?: protos.google.ads.datamanager.v1.IUserList | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateUserList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUserList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateUserList with closed client', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.UpdateUserListRequest() - ); - request.userList ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.UpdateUserListRequest', ['userList', 'name']); - request.userList.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateUserList(request), expectedError); - }); + it('invokes updateUserList with error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListRequest(), + ); + request.userList ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.UpdateUserListRequest', + ['userList', 'name'], + ); + request.userList.name = defaultValue1; + const expectedHeaderRequestParams = `user_list.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateUserList = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateUserList(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateUserList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateUserList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteUserList', () => { - it('invokes deleteUserList without error', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.DeleteUserListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.DeleteUserListRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteUserList = stubSimpleCall(expectedResponse); - const [response] = await client.deleteUserList(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteUserList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUserList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateUserList with closed client', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.UpdateUserListRequest(), + ); + request.userList ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.UpdateUserListRequest', + ['userList', 'name'], + ); + request.userList.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateUserList(request), expectedError); + }); + }); + + describe('deleteUserList', () => { + it('invokes deleteUserList without error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.DeleteUserListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.DeleteUserListRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteUserList = stubSimpleCall(expectedResponse); + const [response] = await client.deleteUserList(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteUserList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUserList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteUserList without error using callback', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.DeleteUserListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.DeleteUserListRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteUserList = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteUserList( - 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.deleteUserList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUserList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteUserList without error using callback', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.DeleteUserListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.DeleteUserListRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteUserList = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteUserList( + 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.deleteUserList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUserList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteUserList with error', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.DeleteUserListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.DeleteUserListRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteUserList = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteUserList(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteUserList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUserList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteUserList with error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.DeleteUserListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.DeleteUserListRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteUserList = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteUserList(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteUserList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUserList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteUserList with closed client', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.DeleteUserListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.DeleteUserListRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteUserList(request), expectedError); - }); + it('invokes deleteUserList with closed client', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.DeleteUserListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.DeleteUserListRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteUserList(request), expectedError); + }); + }); + + describe('listUserLists', () => { + it('invokes listUserLists without error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + ]; + client.innerApiCalls.listUserLists = stubSimpleCall(expectedResponse); + const [response] = await client.listUserLists(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listUserLists as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUserLists as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listUserLists', () => { - it('invokes listUserLists without error', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), - ]; - client.innerApiCalls.listUserLists = stubSimpleCall(expectedResponse); - const [response] = await client.listUserLists(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listUserLists as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listUserLists as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listUserLists without error using callback', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + ]; + client.innerApiCalls.listUserLists = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listUserLists( + request, + ( + err?: Error | null, + result?: protos.google.ads.datamanager.v1.IUserList[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listUserLists as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUserLists as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listUserLists without error using callback', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), - ]; - client.innerApiCalls.listUserLists = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listUserLists( - request, - (err?: Error|null, result?: protos.google.ads.datamanager.v1.IUserList[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listUserLists as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listUserLists as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listUserLists with error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listUserLists = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listUserLists(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listUserLists as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUserLists as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listUserLists with error', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listUserLists = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listUserLists(request), expectedError); - const actualRequest = (client.innerApiCalls.listUserLists as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listUserLists as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listUserListsStream without error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + ]; + client.descriptors.page.listUserLists.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listUserListsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ads.datamanager.v1.UserList[] = []; + stream.on( + 'data', + (response: protos.google.ads.datamanager.v1.UserList) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listUserListsStream without error', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), - ]; - client.descriptors.page.listUserLists.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listUserListsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ads.datamanager.v1.UserList[] = []; - stream.on('data', (response: protos.google.ads.datamanager.v1.UserList) => { - 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.listUserLists.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUserLists, request)); - assert( - (client.descriptors.page.listUserLists.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listUserLists.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listUserLists, request), + ); + assert( + (client.descriptors.page.listUserLists.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listUserListsStream with error', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listUserLists.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listUserListsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ads.datamanager.v1.UserList[] = []; - stream.on('data', (response: protos.google.ads.datamanager.v1.UserList) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listUserLists.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listUserLists, request)); - assert( - (client.descriptors.page.listUserLists.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listUserListsStream with error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listUserLists.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listUserListsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ads.datamanager.v1.UserList[] = []; + stream.on( + 'data', + (response: protos.google.ads.datamanager.v1.UserList) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with listUserLists without error', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), - generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), - ]; - client.descriptors.page.listUserLists.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ads.datamanager.v1.IUserList[] = []; - const iterable = client.listUserListsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listUserLists.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listUserLists.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listUserLists.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listUserLists, request), + ); + assert( + (client.descriptors.page.listUserLists.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listUserLists with error', async () => { - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ads.datamanager.v1.ListUserListsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ads.datamanager.v1.ListUserListsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listUserLists.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listUserListsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ads.datamanager.v1.IUserList[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listUserLists.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listUserLists.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listUserLists without error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + generateSampleMessage(new protos.google.ads.datamanager.v1.UserList()), + ]; + client.descriptors.page.listUserLists.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ads.datamanager.v1.IUserList[] = []; + const iterable = client.listUserListsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listUserLists.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listUserLists.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('account', async () => { - const fakePath = "/rendered/path/account"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - }; - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.accountPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.accountPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('accountPath', () => { - const result = client.accountPath("accountTypeValue", "accountValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.accountPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromAccountName', () => { - const result = client.matchAccountTypeFromAccountName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.accountPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromAccountName', () => { - const result = client.matchAccountFromAccountName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.accountPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listUserLists with error', async () => { + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ads.datamanager.v1.ListUserListsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ads.datamanager.v1.ListUserListsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listUserLists.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listUserListsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ads.datamanager.v1.IUserList[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listUserLists.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listUserLists.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('account', async () => { + const fakePath = '/rendered/path/account'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + }; + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.accountPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.accountPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('accountPath', () => { + const result = client.accountPath('accountTypeValue', 'accountValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.accountPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromAccountName', () => { + const result = client.matchAccountTypeFromAccountName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + (client.pathTemplates.accountPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromAccountName', () => { + const result = client.matchAccountFromAccountName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + (client.pathTemplates.accountPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('partnerLink', async () => { - const fakePath = "/rendered/path/partnerLink"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - partner_link: "partnerLinkValue", - }; - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.partnerLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.partnerLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('partnerLinkPath', () => { - const result = client.partnerLinkPath("accountTypeValue", "accountValue", "partnerLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.partnerLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromPartnerLinkName', () => { - const result = client.matchAccountTypeFromPartnerLinkName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromPartnerLinkName', () => { - const result = client.matchAccountFromPartnerLinkName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPartnerLinkFromPartnerLinkName', () => { - const result = client.matchPartnerLinkFromPartnerLinkName(fakePath); - assert.strictEqual(result, "partnerLinkValue"); - assert((client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('partnerLink', async () => { + const fakePath = '/rendered/path/partnerLink'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + partner_link: 'partnerLinkValue', + }; + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.partnerLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.partnerLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('partnerLinkPath', () => { + const result = client.partnerLinkPath( + 'accountTypeValue', + 'accountValue', + 'partnerLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.partnerLinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromPartnerLinkName', () => { + const result = client.matchAccountTypeFromPartnerLinkName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + (client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromPartnerLinkName', () => { + const result = client.matchAccountFromPartnerLinkName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + (client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPartnerLinkFromPartnerLinkName', () => { + const result = client.matchPartnerLinkFromPartnerLinkName(fakePath); + assert.strictEqual(result, 'partnerLinkValue'); + assert( + (client.pathTemplates.partnerLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userList', async () => { - const fakePath = "/rendered/path/userList"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list: "userListValue", - }; - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListPath', () => { - const result = client.userListPath("accountTypeValue", "accountValue", "userListValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromUserListName', () => { - const result = client.matchAccountTypeFromUserListName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromUserListName', () => { - const result = client.matchAccountFromUserListName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUserListFromUserListName', () => { - const result = client.matchUserListFromUserListName(fakePath); - assert.strictEqual(result, "userListValue"); - assert((client.pathTemplates.userListPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userList', async () => { + const fakePath = '/rendered/path/userList'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list: 'userListValue', + }; + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userListPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userListPath', () => { + const result = client.userListPath( + 'accountTypeValue', + 'accountValue', + 'userListValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userListPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListName', () => { + const result = client.matchAccountTypeFromUserListName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + (client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListName', () => { + const result = client.matchAccountFromUserListName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + (client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListFromUserListName', () => { + const result = client.matchUserListFromUserListName(fakePath); + assert.strictEqual(result, 'userListValue'); + assert( + (client.pathTemplates.userListPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userListDirectLicense', async () => { - const fakePath = "/rendered/path/userListDirectLicense"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list_direct_license: "userListDirectLicenseValue", - }; - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListDirectLicensePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListDirectLicensePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListDirectLicensePath', () => { - const result = client.userListDirectLicensePath("accountTypeValue", "accountValue", "userListDirectLicenseValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListDirectLicensePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromUserListDirectLicenseName', () => { - const result = client.matchAccountTypeFromUserListDirectLicenseName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromUserListDirectLicenseName', () => { - const result = client.matchAccountFromUserListDirectLicenseName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUserListDirectLicenseFromUserListDirectLicenseName', () => { - const result = client.matchUserListDirectLicenseFromUserListDirectLicenseName(fakePath); - assert.strictEqual(result, "userListDirectLicenseValue"); - assert((client.pathTemplates.userListDirectLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userListDirectLicense', async () => { + const fakePath = '/rendered/path/userListDirectLicense'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list_direct_license: 'userListDirectLicenseValue', + }; + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListDirectLicensePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userListDirectLicensePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userListDirectLicensePath', () => { + const result = client.userListDirectLicensePath( + 'accountTypeValue', + 'accountValue', + 'userListDirectLicenseValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListDirectLicenseName', () => { + const result = + client.matchAccountTypeFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListDirectLicenseName', () => { + const result = + client.matchAccountFromUserListDirectLicenseName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListDirectLicenseFromUserListDirectLicenseName', () => { + const result = + client.matchUserListDirectLicenseFromUserListDirectLicenseName( + fakePath, + ); + assert.strictEqual(result, 'userListDirectLicenseValue'); + assert( + ( + client.pathTemplates.userListDirectLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userListGlobalLicense', async () => { - const fakePath = "/rendered/path/userListGlobalLicense"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list_global_license: "userListGlobalLicenseValue", - }; - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListGlobalLicensePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListGlobalLicensePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListGlobalLicensePath', () => { - const result = client.userListGlobalLicensePath("accountTypeValue", "accountValue", "userListGlobalLicenseValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromUserListGlobalLicenseName', () => { - const result = client.matchAccountTypeFromUserListGlobalLicenseName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromUserListGlobalLicenseName', () => { - const result = client.matchAccountFromUserListGlobalLicenseName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUserListGlobalLicenseFromUserListGlobalLicenseName', () => { - const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseName(fakePath); - assert.strictEqual(result, "userListGlobalLicenseValue"); - assert((client.pathTemplates.userListGlobalLicensePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userListGlobalLicense', async () => { + const fakePath = '/rendered/path/userListGlobalLicense'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list_global_license: 'userListGlobalLicenseValue', + }; + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListGlobalLicensePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userListGlobalLicensePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userListGlobalLicensePath', () => { + const result = client.userListGlobalLicensePath( + 'accountTypeValue', + 'accountValue', + 'userListGlobalLicenseValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListGlobalLicenseName', () => { + const result = + client.matchAccountTypeFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, 'accountTypeValue'); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListGlobalLicenseName', () => { + const result = + client.matchAccountFromUserListGlobalLicenseName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseName', () => { + const result = + client.matchUserListGlobalLicenseFromUserListGlobalLicenseName( + fakePath, + ); + assert.strictEqual(result, 'userListGlobalLicenseValue'); + assert( + ( + client.pathTemplates.userListGlobalLicensePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('userListGlobalLicenseCustomerInfo', async () => { - const fakePath = "/rendered/path/userListGlobalLicenseCustomerInfo"; - const expectedParameters = { - account_type: "accountTypeValue", - account: "accountValue", - user_list_global_license: "userListGlobalLicenseValue", - license_customer_info: "licenseCustomerInfoValue", - }; - const client = new userlistserviceModule.v1.UserListServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userListGlobalLicenseCustomerInfoPath', () => { - const result = client.userListGlobalLicenseCustomerInfoPath("accountTypeValue", "accountValue", "userListGlobalLicenseValue", "licenseCustomerInfoValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountTypeFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchAccountTypeFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "accountTypeValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccountFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchAccountFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "userListGlobalLicenseValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName', () => { - const result = client.matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName(fakePath); - assert.strictEqual(result, "licenseCustomerInfoValue"); - assert((client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userListGlobalLicenseCustomerInfo', async () => { + const fakePath = '/rendered/path/userListGlobalLicenseCustomerInfo'; + const expectedParameters = { + account_type: 'accountTypeValue', + account: 'accountValue', + user_list_global_license: 'userListGlobalLicenseValue', + license_customer_info: 'licenseCustomerInfoValue', + }; + const client = new userlistserviceModule.v1.UserListServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userListGlobalLicenseCustomerInfoPath', () => { + const result = client.userListGlobalLicenseCustomerInfoPath( + 'accountTypeValue', + 'accountValue', + 'userListGlobalLicenseValue', + 'licenseCustomerInfoValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountTypeFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchAccountTypeFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'accountTypeValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccountFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchAccountFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'accountValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchUserListGlobalLicenseFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'userListGlobalLicenseValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName', () => { + const result = + client.matchLicenseCustomerInfoFromUserListGlobalLicenseCustomerInfoName( + fakePath, + ); + assert.strictEqual(result, 'licenseCustomerInfoValue'); + assert( + ( + client.pathTemplates.userListGlobalLicenseCustomerInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ads-datamanager/webpack.config.js b/packages/google-ads-datamanager/webpack.config.js index 3861d91e5b58..1e866c6c2320 100644 --- a/packages/google-ads-datamanager/webpack.config.js +++ b/packages/google-ads-datamanager/webpack.config.js @@ -1,4 +1,4 @@ -// Copyright 2026 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/packages/google-ai-generativelanguage/.eslintignore b/packages/google-ai-generativelanguage/.eslintignore new file mode 100644 index 000000000000..cfc348ec4d11 --- /dev/null +++ b/packages/google-ai-generativelanguage/.eslintignore @@ -0,0 +1,7 @@ +**/node_modules +**/.coverage +build/ +docs/ +protos/ +system-test/ +samples/generated/ diff --git a/packages/google-ai-generativelanguage/.eslintrc.json b/packages/google-ai-generativelanguage/.eslintrc.json new file mode 100644 index 000000000000..3e8d97ccb390 --- /dev/null +++ b/packages/google-ai-generativelanguage/.eslintrc.json @@ -0,0 +1,4 @@ +{ + "extends": "./node_modules/gts", + "root": true +} diff --git a/packages/google-ai-generativelanguage/README.md b/packages/google-ai-generativelanguage/README.md index 9730f33c2d60..791a8160dcb9 100644 --- a/packages/google-ai-generativelanguage/README.md +++ b/packages/google-ai-generativelanguage/README.md @@ -241,7 +241,7 @@ More Information: [Google Cloud Platform Launch Stages][launch_stages] ## Contributing -Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ai-generativelanguage/CONTRIBUTING.md). +Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/google-cloud-node/blob/main/CONTRIBUTING.md). Please note that this `README.md` and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`) @@ -251,7 +251,7 @@ are generated from a central template. Apache Version 2.0 -See [LICENSE](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-ai-generativelanguage/LICENSE) +See [LICENSE](https://github.com/googleapis/google-cloud-node/blob/main/LICENSE) [shell_img]: https://gstatic.com/cloudssh/images/open-btn.png [projects]: https://console.cloud.google.com/project diff --git a/packages/google-ai-generativelanguage/protos/protos.d.ts b/packages/google-ai-generativelanguage/protos/protos.d.ts index 642119acd8ef..3f39b39eb9ca 100644 --- a/packages/google-ai-generativelanguage/protos/protos.d.ts +++ b/packages/google-ai-generativelanguage/protos/protos.d.ts @@ -58674,6 +58674,9 @@ export namespace google { /** CommonLanguageSettings destinations */ destinations?: (google.api.ClientLibraryDestination[]|null); + + /** CommonLanguageSettings selectiveGapicGeneration */ + selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); } /** Represents a CommonLanguageSettings. */ @@ -58691,6 +58694,9 @@ export namespace google { /** CommonLanguageSettings destinations. */ public destinations: google.api.ClientLibraryDestination[]; + /** CommonLanguageSettings selectiveGapicGeneration. */ + public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + /** * Creates a new CommonLanguageSettings instance using the specified properties. * @param [properties] Properties to set @@ -59391,6 +59397,9 @@ export namespace google { /** PythonSettings common */ common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures */ + experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); } /** Represents a PythonSettings. */ @@ -59405,6 +59414,9 @@ export namespace google { /** PythonSettings common. */ public common?: (google.api.ICommonLanguageSettings|null); + /** PythonSettings experimentalFeatures. */ + public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + /** * Creates a new PythonSettings instance using the specified properties. * @param [properties] Properties to set @@ -59483,6 +59495,118 @@ 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); + + /** ExperimentalFeatures unversionedPackageDisabled */ + unversionedPackageDisabled?: (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; + + /** ExperimentalFeatures unversionedPackageDisabled. */ + public unversionedPackageDisabled: boolean; + + /** + * Creates a new ExperimentalFeatures instance using the specified properties. + * @param [properties] Properties to set + * @returns ExperimentalFeatures instance + */ + public static create(properties?: google.api.PythonSettings.IExperimentalFeatures): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Encodes the specified ExperimentalFeatures message. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @param message ExperimentalFeatures message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.PythonSettings.IExperimentalFeatures, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExperimentalFeatures message, length delimited. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @param message ExperimentalFeatures message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.PythonSettings.IExperimentalFeatures, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Verifies an ExperimentalFeatures message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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 { @@ -59809,6 +59933,9 @@ export namespace google { /** GoSettings common */ common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); } /** Represents a GoSettings. */ @@ -59823,6 +59950,9 @@ export namespace google { /** GoSettings common. */ public common?: (google.api.ICommonLanguageSettings|null); + /** GoSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + /** * Creates a new GoSettings instance using the specified properties. * @param [properties] Properties to set @@ -60147,6 +60277,109 @@ export namespace google { PACKAGE_MANAGER = 20 } + /** 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 new SelectiveGapicGeneration instance using the specified properties. + * @param [properties] Properties to set + * @returns SelectiveGapicGeneration instance + */ + public static create(properties?: google.api.ISelectiveGapicGeneration): google.api.SelectiveGapicGeneration; + + /** + * Encodes the specified SelectiveGapicGeneration message. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @param message SelectiveGapicGeneration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.ISelectiveGapicGeneration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SelectiveGapicGeneration message, length delimited. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @param message SelectiveGapicGeneration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.ISelectiveGapicGeneration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.SelectiveGapicGeneration; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.SelectiveGapicGeneration; + + /** + * Verifies a SelectiveGapicGeneration message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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. */ enum LaunchStage { LAUNCH_STAGE_UNSPECIFIED = 0, @@ -60515,6 +60748,7 @@ export namespace google { /** Edition enum. */ enum Edition { EDITION_UNKNOWN = 0, + EDITION_LEGACY = 900, EDITION_PROTO2 = 998, EDITION_PROTO3 = 999, EDITION_2023 = 1000, @@ -60545,6 +60779,9 @@ export namespace google { /** FileDescriptorProto weakDependency */ weakDependency?: (number[]|null); + /** FileDescriptorProto optionDependency */ + optionDependency?: (string[]|null); + /** FileDescriptorProto messageType */ messageType?: (google.protobuf.IDescriptorProto[]|null); @@ -60594,6 +60831,9 @@ export namespace google { /** FileDescriptorProto weakDependency. */ public weakDependency: number[]; + /** FileDescriptorProto optionDependency. */ + public optionDependency: string[]; + /** FileDescriptorProto messageType. */ public messageType: google.protobuf.IDescriptorProto[]; @@ -60728,6 +60968,9 @@ export namespace google { /** DescriptorProto reservedName */ reservedName?: (string[]|null); + + /** DescriptorProto visibility */ + visibility?: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility|null); } /** Represents a DescriptorProto. */ @@ -60769,6 +61012,9 @@ export namespace google { /** DescriptorProto reservedName. */ public reservedName: string[]; + /** DescriptorProto visibility. */ + public visibility: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility); + /** * Creates a new DescriptorProto instance using the specified properties. * @param [properties] Properties to set @@ -61616,6 +61862,9 @@ export namespace google { /** EnumDescriptorProto reservedName */ reservedName?: (string[]|null); + + /** EnumDescriptorProto visibility */ + visibility?: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility|null); } /** Represents an EnumDescriptorProto. */ @@ -61642,6 +61891,9 @@ export namespace google { /** EnumDescriptorProto reservedName. */ public reservedName: string[]; + /** EnumDescriptorProto visibility. */ + public visibility: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility); + /** * Creates a new EnumDescriptorProto instance using the specified properties. * @param [properties] Properties to set @@ -62576,6 +62828,9 @@ 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); @@ -62631,6 +62886,9 @@ 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[]; @@ -62851,6 +63109,121 @@ export namespace google { */ public static getTypeUrl(typeUrlPrefix?: string): string; } + + /** Properties of a FeatureSupport. */ + interface IFeatureSupport { + + /** FeatureSupport editionIntroduced */ + editionIntroduced?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + + /** FeatureSupport editionDeprecated */ + editionDeprecated?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + + /** FeatureSupport deprecationWarning */ + deprecationWarning?: (string|null); + + /** FeatureSupport editionRemoved */ + editionRemoved?: (google.protobuf.Edition|keyof typeof 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|keyof typeof google.protobuf.Edition); + + /** FeatureSupport editionDeprecated. */ + public editionDeprecated: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** FeatureSupport deprecationWarning. */ + public deprecationWarning: string; + + /** FeatureSupport editionRemoved. */ + public editionRemoved: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** + * Creates a new FeatureSupport instance using the specified properties. + * @param [properties] Properties to set + * @returns FeatureSupport instance + */ + public static create(properties?: google.protobuf.FieldOptions.IFeatureSupport): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Encodes the specified FeatureSupport message. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @param message FeatureSupport message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.FieldOptions.IFeatureSupport, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FeatureSupport message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @param message FeatureSupport message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.FieldOptions.IFeatureSupport, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Verifies a FeatureSupport message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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. */ @@ -63089,6 +63462,9 @@ export namespace google { /** EnumValueOptions debugRedact */ debugRedact?: (boolean|null); + /** EnumValueOptions featureSupport */ + featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); + /** EnumValueOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } @@ -63111,6 +63487,9 @@ export namespace google { /** EnumValueOptions debugRedact. */ public debugRedact: boolean; + /** EnumValueOptions featureSupport. */ + public featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); + /** EnumValueOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -63703,6 +64082,12 @@ export namespace google { /** FeatureSet jsonFormat */ jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|keyof typeof google.protobuf.FeatureSet.JsonFormat|null); + + /** FeatureSet enforceNamingStyle */ + enforceNamingStyle?: (google.protobuf.FeatureSet.EnforceNamingStyle|keyof typeof google.protobuf.FeatureSet.EnforceNamingStyle|null); + + /** FeatureSet defaultSymbolVisibility */ + defaultSymbolVisibility?: (google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|keyof typeof google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|null); } /** Represents a FeatureSet. */ @@ -63732,6 +64117,12 @@ export namespace google { /** FeatureSet jsonFormat. */ public jsonFormat: (google.protobuf.FeatureSet.JsonFormat|keyof typeof google.protobuf.FeatureSet.JsonFormat); + /** FeatureSet enforceNamingStyle. */ + public enforceNamingStyle: (google.protobuf.FeatureSet.EnforceNamingStyle|keyof typeof google.protobuf.FeatureSet.EnforceNamingStyle); + + /** FeatureSet defaultSymbolVisibility. */ + public defaultSymbolVisibility: (google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|keyof typeof google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility); + /** * Creates a new FeatureSet instance using the specified properties. * @param [properties] Properties to set @@ -63854,6 +64245,116 @@ export namespace google { ALLOW = 1, LEGACY_BEST_EFFORT = 2 } + + /** EnforceNamingStyle enum. */ + enum EnforceNamingStyle { + ENFORCE_NAMING_STYLE_UNKNOWN = 0, + STYLE2024 = 1, + STYLE_LEGACY = 2 + } + + /** Properties of a VisibilityFeature. */ + interface IVisibilityFeature { + } + + /** Represents a VisibilityFeature. */ + class VisibilityFeature implements IVisibilityFeature { + + /** + * Constructs a new VisibilityFeature. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FeatureSet.IVisibilityFeature); + + /** + * Creates a new VisibilityFeature instance using the specified properties. + * @param [properties] Properties to set + * @returns VisibilityFeature instance + */ + public static create(properties?: google.protobuf.FeatureSet.IVisibilityFeature): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Encodes the specified VisibilityFeature message. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @param message VisibilityFeature message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.FeatureSet.IVisibilityFeature, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified VisibilityFeature message, length delimited. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @param message VisibilityFeature message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.FeatureSet.IVisibilityFeature, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Verifies a VisibilityFeature message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a VisibilityFeature message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns VisibilityFeature + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Creates a plain object from a VisibilityFeature message. Also converts values to other types if specified. + * @param message VisibilityFeature + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet.VisibilityFeature, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this VisibilityFeature to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for VisibilityFeature + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace VisibilityFeature { + + /** DefaultSymbolVisibility enum. */ + enum DefaultSymbolVisibility { + DEFAULT_SYMBOL_VISIBILITY_UNKNOWN = 0, + EXPORT_ALL = 1, + EXPORT_TOP_LEVEL = 2, + LOCAL_ALL = 3, + STRICT = 4 + } + } } /** Properties of a FeatureSetDefaults. */ @@ -63973,8 +64474,11 @@ export namespace google { /** FeatureSetEditionDefault edition */ edition?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); - /** FeatureSetEditionDefault features */ - features?: (google.protobuf.IFeatureSet|null); + /** FeatureSetEditionDefault overridableFeatures */ + overridableFeatures?: (google.protobuf.IFeatureSet|null); + + /** FeatureSetEditionDefault fixedFeatures */ + fixedFeatures?: (google.protobuf.IFeatureSet|null); } /** Represents a FeatureSetEditionDefault. */ @@ -63989,8 +64493,11 @@ export namespace google { /** FeatureSetEditionDefault edition. */ public edition: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); - /** FeatureSetEditionDefault features. */ - public features?: (google.protobuf.IFeatureSet|null); + /** FeatureSetEditionDefault overridableFeatures. */ + public overridableFeatures?: (google.protobuf.IFeatureSet|null); + + /** FeatureSetEditionDefault fixedFeatures. */ + public fixedFeatures?: (google.protobuf.IFeatureSet|null); /** * Creates a new FeatureSetEditionDefault instance using the specified properties. @@ -64523,6 +65030,13 @@ export namespace google { } } + /** SymbolVisibility enum. */ + enum SymbolVisibility { + VISIBILITY_UNSET = 0, + VISIBILITY_LOCAL = 1, + VISIBILITY_EXPORT = 2 + } + /** Properties of a Duration. */ interface IDuration { diff --git a/packages/google-ai-generativelanguage/protos/protos.js b/packages/google-ai-generativelanguage/protos/protos.js index 7b7d306fc746..b8629c2ded5f 100644 --- a/packages/google-ai-generativelanguage/protos/protos.js +++ b/packages/google-ai-generativelanguage/protos/protos.js @@ -145601,6 +145601,7 @@ * @interface ICommonLanguageSettings * @property {string|null} [referenceDocsUri] CommonLanguageSettings referenceDocsUri * @property {Array.|null} [destinations] CommonLanguageSettings destinations + * @property {google.api.ISelectiveGapicGeneration|null} [selectiveGapicGeneration] CommonLanguageSettings selectiveGapicGeneration */ /** @@ -145635,6 +145636,14 @@ */ 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 new CommonLanguageSettings instance using the specified properties. * @function create @@ -145667,6 +145676,8 @@ writer.int32(message.destinations[i]); writer.ldelim(); } + if (message.selectiveGapicGeneration != null && Object.hasOwnProperty.call(message, "selectiveGapicGeneration")) + $root.google.api.SelectiveGapicGeneration.encode(message.selectiveGapicGeneration, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); return writer; }; @@ -145718,6 +145729,10 @@ message.destinations.push(reader.int32()); break; } + case 3: { + message.selectiveGapicGeneration = $root.google.api.SelectiveGapicGeneration.decode(reader, reader.uint32()); + break; + } default: reader.skipType(tag & 7); break; @@ -145769,6 +145784,11 @@ break; } } + if (message.selectiveGapicGeneration != null && message.hasOwnProperty("selectiveGapicGeneration")) { + var error = $root.google.api.SelectiveGapicGeneration.verify(message.selectiveGapicGeneration); + if (error) + return "selectiveGapicGeneration." + error; + } return null; }; @@ -145811,6 +145831,11 @@ 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; }; @@ -145829,8 +145854,10 @@ 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) { @@ -145838,6 +145865,8 @@ 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; }; @@ -147660,6 +147689,7 @@ * @memberof google.api * @interface IPythonSettings * @property {google.api.ICommonLanguageSettings|null} [common] PythonSettings common + * @property {google.api.PythonSettings.IExperimentalFeatures|null} [experimentalFeatures] PythonSettings experimentalFeatures */ /** @@ -147685,6 +147715,14 @@ */ 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 new PythonSettings instance using the specified properties. * @function create @@ -147711,6 +147749,8 @@ writer = $Writer.create(); if (message.common != null && Object.hasOwnProperty.call(message, "common")) $root.google.api.CommonLanguageSettings.encode(message.common, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.experimentalFeatures != null && Object.hasOwnProperty.call(message, "experimentalFeatures")) + $root.google.api.PythonSettings.ExperimentalFeatures.encode(message.experimentalFeatures, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); return writer; }; @@ -147751,6 +147791,10 @@ message.common = $root.google.api.CommonLanguageSettings.decode(reader, reader.uint32()); break; } + case 2: { + message.experimentalFeatures = $root.google.api.PythonSettings.ExperimentalFeatures.decode(reader, reader.uint32()); + break; + } default: reader.skipType(tag & 7); break; @@ -147791,6 +147835,11 @@ if (error) return "common." + error; } + if (message.experimentalFeatures != null && message.hasOwnProperty("experimentalFeatures")) { + var error = $root.google.api.PythonSettings.ExperimentalFeatures.verify(message.experimentalFeatures); + if (error) + return "experimentalFeatures." + error; + } return null; }; @@ -147811,6 +147860,11 @@ 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; }; @@ -147827,10 +147881,14 @@ 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; }; @@ -147860,6 +147918,258 @@ 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 + * @property {boolean|null} [unversionedPackageDisabled] ExperimentalFeatures unversionedPackageDisabled + */ + + /** + * 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; + + /** + * ExperimentalFeatures unversionedPackageDisabled. + * @member {boolean} unversionedPackageDisabled + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @instance + */ + ExperimentalFeatures.prototype.unversionedPackageDisabled = false; + + /** + * Creates a new ExperimentalFeatures instance using the specified properties. + * @function create + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures=} [properties] Properties to set + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures instance + */ + ExperimentalFeatures.create = function create(properties) { + return new ExperimentalFeatures(properties); + }; + + /** + * Encodes the specified ExperimentalFeatures message. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @function encode + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures} message ExperimentalFeatures message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExperimentalFeatures.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.restAsyncIoEnabled != null && Object.hasOwnProperty.call(message, "restAsyncIoEnabled")) + writer.uint32(/* id 1, wireType 0 =*/8).bool(message.restAsyncIoEnabled); + if (message.protobufPythonicTypesEnabled != null && Object.hasOwnProperty.call(message, "protobufPythonicTypesEnabled")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.protobufPythonicTypesEnabled); + if (message.unversionedPackageDisabled != null && Object.hasOwnProperty.call(message, "unversionedPackageDisabled")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.unversionedPackageDisabled); + return writer; + }; + + /** + * Encodes the specified ExperimentalFeatures message, length delimited. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures} message ExperimentalFeatures message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExperimentalFeatures.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer. + * @function decode + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExperimentalFeatures.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.PythonSettings.ExperimentalFeatures(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.restAsyncIoEnabled = reader.bool(); + break; + } + case 2: { + message.protobufPythonicTypesEnabled = reader.bool(); + break; + } + case 3: { + message.unversionedPackageDisabled = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExperimentalFeatures.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ExperimentalFeatures message. + * @function verify + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExperimentalFeatures.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.restAsyncIoEnabled != null && message.hasOwnProperty("restAsyncIoEnabled")) + if (typeof message.restAsyncIoEnabled !== "boolean") + return "restAsyncIoEnabled: boolean expected"; + if (message.protobufPythonicTypesEnabled != null && message.hasOwnProperty("protobufPythonicTypesEnabled")) + if (typeof message.protobufPythonicTypesEnabled !== "boolean") + return "protobufPythonicTypesEnabled: boolean expected"; + if (message.unversionedPackageDisabled != null && message.hasOwnProperty("unversionedPackageDisabled")) + if (typeof message.unversionedPackageDisabled !== "boolean") + return "unversionedPackageDisabled: boolean expected"; + return null; + }; + + /** + * 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); + if (object.unversionedPackageDisabled != null) + message.unversionedPackageDisabled = Boolean(object.unversionedPackageDisabled); + 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; + object.unversionedPackageDisabled = false; + } + if (message.restAsyncIoEnabled != null && message.hasOwnProperty("restAsyncIoEnabled")) + object.restAsyncIoEnabled = message.restAsyncIoEnabled; + if (message.protobufPythonicTypesEnabled != null && message.hasOwnProperty("protobufPythonicTypesEnabled")) + object.protobufPythonicTypesEnabled = message.protobufPythonicTypesEnabled; + if (message.unversionedPackageDisabled != null && message.hasOwnProperty("unversionedPackageDisabled")) + object.unversionedPackageDisabled = message.unversionedPackageDisabled; + 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; })(); @@ -148736,6 +149046,7 @@ * @memberof google.api * @interface IGoSettings * @property {google.api.ICommonLanguageSettings|null} [common] GoSettings common + * @property {Object.|null} [renamedServices] GoSettings renamedServices */ /** @@ -148747,6 +149058,7 @@ * @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) @@ -148761,6 +149073,14 @@ */ GoSettings.prototype.common = null; + /** + * GoSettings renamedServices. + * @member {Object.} renamedServices + * @memberof google.api.GoSettings + * @instance + */ + GoSettings.prototype.renamedServices = $util.emptyObject; + /** * Creates a new GoSettings instance using the specified properties. * @function create @@ -148787,6 +149107,9 @@ writer = $Writer.create(); if (message.common != null && Object.hasOwnProperty.call(message, "common")) $root.google.api.CommonLanguageSettings.encode(message.common, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.renamedServices != null && Object.hasOwnProperty.call(message, "renamedServices")) + for (var keys = Object.keys(message.renamedServices), i = 0; i < keys.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.renamedServices[keys[i]]).ldelim(); return writer; }; @@ -148817,7 +149140,7 @@ GoSettings.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.GoSettings(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.GoSettings(), key, value; while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -148827,6 +149150,29 @@ message.common = $root.google.api.CommonLanguageSettings.decode(reader, reader.uint32()); break; } + case 2: { + if (message.renamedServices === $util.emptyObject) + message.renamedServices = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.renamedServices[key] = value; + break; + } default: reader.skipType(tag & 7); break; @@ -148867,6 +149213,14 @@ if (error) return "common." + error; } + if (message.renamedServices != null && message.hasOwnProperty("renamedServices")) { + if (!$util.isObject(message.renamedServices)) + return "renamedServices: object expected"; + var key = Object.keys(message.renamedServices); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.renamedServices[key[i]])) + return "renamedServices: string{k:string} expected"; + } return null; }; @@ -148887,6 +149241,13 @@ 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; }; @@ -148903,10 +149264,18 @@ 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; }; @@ -149545,30 +149914,275 @@ return values; })(); - /** - * LaunchStage enum. - * @name google.api.LaunchStage - * @enum {number} - * @property {number} LAUNCH_STAGE_UNSPECIFIED=0 LAUNCH_STAGE_UNSPECIFIED value - * @property {number} UNIMPLEMENTED=6 UNIMPLEMENTED value - * @property {number} PRELAUNCH=7 PRELAUNCH value - * @property {number} EARLY_ACCESS=1 EARLY_ACCESS value - * @property {number} ALPHA=2 ALPHA value - * @property {number} BETA=3 BETA value - * @property {number} GA=4 GA value - * @property {number} DEPRECATED=5 DEPRECATED value - */ - api.LaunchStage = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "LAUNCH_STAGE_UNSPECIFIED"] = 0; - values[valuesById[6] = "UNIMPLEMENTED"] = 6; - values[valuesById[7] = "PRELAUNCH"] = 7; - values[valuesById[1] = "EARLY_ACCESS"] = 1; - values[valuesById[2] = "ALPHA"] = 2; - values[valuesById[3] = "BETA"] = 3; - values[valuesById[4] = "GA"] = 4; - values[valuesById[5] = "DEPRECATED"] = 5; - 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 new SelectiveGapicGeneration instance using the specified properties. + * @function create + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration=} [properties] Properties to set + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration instance + */ + SelectiveGapicGeneration.create = function create(properties) { + return new SelectiveGapicGeneration(properties); + }; + + /** + * Encodes the specified SelectiveGapicGeneration message. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @function encode + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration} message SelectiveGapicGeneration message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SelectiveGapicGeneration.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.methods != null && message.methods.length) + for (var i = 0; i < message.methods.length; ++i) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.methods[i]); + if (message.generateOmittedAsInternal != null && Object.hasOwnProperty.call(message, "generateOmittedAsInternal")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.generateOmittedAsInternal); + return writer; + }; + + /** + * Encodes the specified SelectiveGapicGeneration message, length delimited. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration} message SelectiveGapicGeneration message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SelectiveGapicGeneration.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer. + * @function decode + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SelectiveGapicGeneration.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.SelectiveGapicGeneration(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.methods && message.methods.length)) + message.methods = []; + message.methods.push(reader.string()); + break; + } + case 2: { + message.generateOmittedAsInternal = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SelectiveGapicGeneration.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SelectiveGapicGeneration message. + * @function verify + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SelectiveGapicGeneration.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.methods != null && message.hasOwnProperty("methods")) { + if (!Array.isArray(message.methods)) + return "methods: array expected"; + for (var i = 0; i < message.methods.length; ++i) + if (!$util.isString(message.methods[i])) + return "methods: string[] expected"; + } + if (message.generateOmittedAsInternal != null && message.hasOwnProperty("generateOmittedAsInternal")) + if (typeof message.generateOmittedAsInternal !== "boolean") + return "generateOmittedAsInternal: boolean expected"; + return null; + }; + + /** + * 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 + * @enum {number} + * @property {number} LAUNCH_STAGE_UNSPECIFIED=0 LAUNCH_STAGE_UNSPECIFIED value + * @property {number} UNIMPLEMENTED=6 UNIMPLEMENTED value + * @property {number} PRELAUNCH=7 PRELAUNCH value + * @property {number} EARLY_ACCESS=1 EARLY_ACCESS value + * @property {number} ALPHA=2 ALPHA value + * @property {number} BETA=3 BETA value + * @property {number} GA=4 GA value + * @property {number} DEPRECATED=5 DEPRECATED value + */ + api.LaunchStage = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "LAUNCH_STAGE_UNSPECIFIED"] = 0; + values[valuesById[6] = "UNIMPLEMENTED"] = 6; + values[valuesById[7] = "PRELAUNCH"] = 7; + values[valuesById[1] = "EARLY_ACCESS"] = 1; + values[valuesById[2] = "ALPHA"] = 2; + values[valuesById[3] = "BETA"] = 3; + values[valuesById[4] = "GA"] = 4; + values[valuesById[5] = "DEPRECATED"] = 5; + return values; })(); api.ResourceDescriptor = (function() { @@ -150502,6 +151116,7 @@ * @name google.protobuf.Edition * @enum {number} * @property {number} EDITION_UNKNOWN=0 EDITION_UNKNOWN value + * @property {number} EDITION_LEGACY=900 EDITION_LEGACY value * @property {number} EDITION_PROTO2=998 EDITION_PROTO2 value * @property {number} EDITION_PROTO3=999 EDITION_PROTO3 value * @property {number} EDITION_2023=1000 EDITION_2023 value @@ -150516,6 +151131,7 @@ protobuf.Edition = (function() { var valuesById = {}, values = Object.create(valuesById); values[valuesById[0] = "EDITION_UNKNOWN"] = 0; + values[valuesById[900] = "EDITION_LEGACY"] = 900; values[valuesById[998] = "EDITION_PROTO2"] = 998; values[valuesById[999] = "EDITION_PROTO3"] = 999; values[valuesById[1000] = "EDITION_2023"] = 1000; @@ -150540,6 +151156,7 @@ * @property {Array.|null} [dependency] FileDescriptorProto dependency * @property {Array.|null} [publicDependency] FileDescriptorProto publicDependency * @property {Array.|null} [weakDependency] FileDescriptorProto weakDependency + * @property {Array.|null} [optionDependency] FileDescriptorProto optionDependency * @property {Array.|null} [messageType] FileDescriptorProto messageType * @property {Array.|null} [enumType] FileDescriptorProto enumType * @property {Array.|null} [service] FileDescriptorProto service @@ -150562,6 +151179,7 @@ this.dependency = []; this.publicDependency = []; this.weakDependency = []; + this.optionDependency = []; this.messageType = []; this.enumType = []; this.service = []; @@ -150612,6 +151230,14 @@ */ FileDescriptorProto.prototype.weakDependency = $util.emptyArray; + /** + * FileDescriptorProto optionDependency. + * @member {Array.} optionDependency + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.optionDependency = $util.emptyArray; + /** * FileDescriptorProto messageType. * @member {Array.} messageType @@ -150733,6 +151359,9 @@ writer.uint32(/* id 12, wireType 2 =*/98).string(message.syntax); if (message.edition != null && Object.hasOwnProperty.call(message, "edition")) writer.uint32(/* id 14, wireType 0 =*/112).int32(message.edition); + if (message.optionDependency != null && message.optionDependency.length) + for (var i = 0; i < message.optionDependency.length; ++i) + writer.uint32(/* id 15, wireType 2 =*/122).string(message.optionDependency[i]); return writer; }; @@ -150805,6 +151434,12 @@ message.weakDependency.push(reader.int32()); break; } + case 15: { + if (!(message.optionDependency && message.optionDependency.length)) + message.optionDependency = []; + message.optionDependency.push(reader.string()); + break; + } case 4: { if (!(message.messageType && message.messageType.length)) message.messageType = []; @@ -150907,6 +151542,13 @@ if (!$util.isInteger(message.weakDependency[i])) return "weakDependency: integer[] expected"; } + if (message.optionDependency != null && message.hasOwnProperty("optionDependency")) { + if (!Array.isArray(message.optionDependency)) + return "optionDependency: array expected"; + for (var i = 0; i < message.optionDependency.length; ++i) + if (!$util.isString(message.optionDependency[i])) + return "optionDependency: string[] expected"; + } if (message.messageType != null && message.hasOwnProperty("messageType")) { if (!Array.isArray(message.messageType)) return "messageType: array expected"; @@ -150961,6 +151603,7 @@ default: return "edition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -151013,6 +151656,13 @@ for (var i = 0; i < object.weakDependency.length; ++i) message.weakDependency[i] = object.weakDependency[i] | 0; } + if (object.optionDependency) { + if (!Array.isArray(object.optionDependency)) + throw TypeError(".google.protobuf.FileDescriptorProto.optionDependency: array expected"); + message.optionDependency = []; + for (var i = 0; i < object.optionDependency.length; ++i) + message.optionDependency[i] = String(object.optionDependency[i]); + } if (object.messageType) { if (!Array.isArray(object.messageType)) throw TypeError(".google.protobuf.FileDescriptorProto.messageType: array expected"); @@ -151076,6 +151726,10 @@ case 0: message.edition = 0; break; + case "EDITION_LEGACY": + case 900: + message.edition = 900; + break; case "EDITION_PROTO2": case 998: message.edition = 998; @@ -151141,6 +151795,7 @@ object.extension = []; object.publicDependency = []; object.weakDependency = []; + object.optionDependency = []; } if (options.defaults) { object.name = ""; @@ -151197,6 +151852,11 @@ 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; + if (message.optionDependency && message.optionDependency.length) { + object.optionDependency = []; + for (var j = 0; j < message.optionDependency.length; ++j) + object.optionDependency[j] = message.optionDependency[j]; + } return object; }; @@ -151245,6 +151905,7 @@ * @property {google.protobuf.IMessageOptions|null} [options] DescriptorProto options * @property {Array.|null} [reservedRange] DescriptorProto reservedRange * @property {Array.|null} [reservedName] DescriptorProto reservedName + * @property {google.protobuf.SymbolVisibility|null} [visibility] DescriptorProto visibility */ /** @@ -151350,6 +152011,14 @@ */ DescriptorProto.prototype.reservedName = $util.emptyArray; + /** + * DescriptorProto visibility. + * @member {google.protobuf.SymbolVisibility} visibility + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.visibility = 0; + /** * Creates a new DescriptorProto instance using the specified properties. * @function create @@ -151402,6 +152071,8 @@ if (message.reservedName != null && message.reservedName.length) for (var i = 0; i < message.reservedName.length; ++i) writer.uint32(/* id 10, wireType 2 =*/82).string(message.reservedName[i]); + if (message.visibility != null && Object.hasOwnProperty.call(message, "visibility")) + writer.uint32(/* id 11, wireType 0 =*/88).int32(message.visibility); return writer; }; @@ -151494,6 +152165,10 @@ message.reservedName.push(reader.string()); break; } + case 11: { + message.visibility = reader.int32(); + break; + } default: reader.skipType(tag & 7); break; @@ -151607,6 +152282,15 @@ if (!$util.isString(message.reservedName[i])) return "reservedName: string[] expected"; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + switch (message.visibility) { + default: + return "visibility: enum value expected"; + case 0: + case 1: + case 2: + break; + } return null; }; @@ -151706,6 +152390,26 @@ for (var i = 0; i < object.reservedName.length; ++i) message.reservedName[i] = String(object.reservedName[i]); } + switch (object.visibility) { + default: + if (typeof object.visibility === "number") { + message.visibility = object.visibility; + break; + } + break; + case "VISIBILITY_UNSET": + case 0: + message.visibility = 0; + break; + case "VISIBILITY_LOCAL": + case 1: + message.visibility = 1; + break; + case "VISIBILITY_EXPORT": + case 2: + message.visibility = 2; + break; + } return message; }; @@ -151735,6 +152439,7 @@ if (options.defaults) { object.name = ""; object.options = null; + object.visibility = options.enums === String ? "VISIBILITY_UNSET" : 0; } if (message.name != null && message.hasOwnProperty("name")) object.name = message.name; @@ -151780,6 +152485,8 @@ for (var j = 0; j < message.reservedName.length; ++j) object.reservedName[j] = message.reservedName[j]; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + object.visibility = options.enums === String ? $root.google.protobuf.SymbolVisibility[message.visibility] === undefined ? message.visibility : $root.google.protobuf.SymbolVisibility[message.visibility] : message.visibility; return object; }; @@ -153824,6 +154531,7 @@ * @property {google.protobuf.IEnumOptions|null} [options] EnumDescriptorProto options * @property {Array.|null} [reservedRange] EnumDescriptorProto reservedRange * @property {Array.|null} [reservedName] EnumDescriptorProto reservedName + * @property {google.protobuf.SymbolVisibility|null} [visibility] EnumDescriptorProto visibility */ /** @@ -153884,6 +154592,14 @@ */ EnumDescriptorProto.prototype.reservedName = $util.emptyArray; + /** + * EnumDescriptorProto visibility. + * @member {google.protobuf.SymbolVisibility} visibility + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.visibility = 0; + /** * Creates a new EnumDescriptorProto instance using the specified properties. * @function create @@ -153921,6 +154637,8 @@ if (message.reservedName != null && message.reservedName.length) for (var i = 0; i < message.reservedName.length; ++i) writer.uint32(/* id 5, wireType 2 =*/42).string(message.reservedName[i]); + if (message.visibility != null && Object.hasOwnProperty.call(message, "visibility")) + writer.uint32(/* id 6, wireType 0 =*/48).int32(message.visibility); return writer; }; @@ -153983,6 +154701,10 @@ message.reservedName.push(reader.string()); break; } + case 6: { + message.visibility = reader.int32(); + break; + } default: reader.skipType(tag & 7); break; @@ -154051,6 +154773,15 @@ if (!$util.isString(message.reservedName[i])) return "reservedName: string[] expected"; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + switch (message.visibility) { + default: + return "visibility: enum value expected"; + case 0: + case 1: + case 2: + break; + } return null; }; @@ -154100,6 +154831,26 @@ for (var i = 0; i < object.reservedName.length; ++i) message.reservedName[i] = String(object.reservedName[i]); } + switch (object.visibility) { + default: + if (typeof object.visibility === "number") { + message.visibility = object.visibility; + break; + } + break; + case "VISIBILITY_UNSET": + case 0: + message.visibility = 0; + break; + case "VISIBILITY_LOCAL": + case 1: + message.visibility = 1; + break; + case "VISIBILITY_EXPORT": + case 2: + message.visibility = 2; + break; + } return message; }; @@ -154124,6 +154875,7 @@ if (options.defaults) { object.name = ""; object.options = null; + object.visibility = options.enums === String ? "VISIBILITY_UNSET" : 0; } if (message.name != null && message.hasOwnProperty("name")) object.name = message.name; @@ -154144,6 +154896,8 @@ for (var j = 0; j < message.reservedName.length; ++j) object.reservedName[j] = message.reservedName[j]; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + object.visibility = options.enums === String ? $root.google.protobuf.SymbolVisibility[message.visibility] === undefined ? message.visibility : $root.google.protobuf.SymbolVisibility[message.visibility] : message.visibility; return object; }; @@ -156462,6 +157216,7 @@ * @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 @@ -156582,6 +157337,14 @@ */ 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 @@ -156656,6 +157419,8 @@ $root.google.protobuf.FieldOptions.EditionDefault.encode(message.editionDefaults[i], writer.uint32(/* id 20, wireType 2 =*/162).fork()).ldelim(); if (message.features != null && Object.hasOwnProperty.call(message, "features")) $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 21, wireType 2 =*/170).fork()).ldelim(); + if (message.featureSupport != null && Object.hasOwnProperty.call(message, "featureSupport")) + $root.google.protobuf.FieldOptions.FeatureSupport.encode(message.featureSupport, writer.uint32(/* id 22, wireType 2 =*/178).fork()).ldelim(); if (message.uninterpretedOption != null && message.uninterpretedOption.length) for (var i = 0; i < message.uninterpretedOption.length; ++i) $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); @@ -156757,6 +157522,10 @@ message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); break; } + case 22: { + message.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.decode(reader, reader.uint32()); + break; + } case 999: { if (!(message.uninterpretedOption && message.uninterpretedOption.length)) message.uninterpretedOption = []; @@ -156892,6 +157661,11 @@ if (error) return "features." + error; } + if (message.featureSupport != null && message.hasOwnProperty("featureSupport")) { + var error = $root.google.protobuf.FieldOptions.FeatureSupport.verify(message.featureSupport); + if (error) + return "featureSupport." + error; + } if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { if (!Array.isArray(message.uninterpretedOption)) return "uninterpretedOption: array expected"; @@ -157080,6 +157854,11 @@ 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"); @@ -157177,6 +157956,7 @@ 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")) @@ -157209,6 +157989,8 @@ } 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) @@ -157481,6 +158263,7 @@ default: return "edition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -157522,103 +158305,589 @@ 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; + 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 EditionDefault message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {google.protobuf.FieldOptions.EditionDefault} message EditionDefault + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EditionDefault.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.value = ""; + object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; + } + 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 EditionDefault to JSON. + * @function toJSON + * @memberof google.protobuf.FieldOptions.EditionDefault + * @instance + * @returns {Object.} JSON object + */ + EditionDefault.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * 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; + })(); + + 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 new FeatureSupport instance using the specified properties. + * @function create + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport=} [properties] Properties to set + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport instance + */ + FeatureSupport.create = function create(properties) { + return new FeatureSupport(properties); + }; + + /** + * Encodes the specified FeatureSupport message. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport} message FeatureSupport message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FeatureSupport.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.editionIntroduced != null && Object.hasOwnProperty.call(message, "editionIntroduced")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.editionIntroduced); + if (message.editionDeprecated != null && Object.hasOwnProperty.call(message, "editionDeprecated")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.editionDeprecated); + if (message.deprecationWarning != null && Object.hasOwnProperty.call(message, "deprecationWarning")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.deprecationWarning); + if (message.editionRemoved != null && Object.hasOwnProperty.call(message, "editionRemoved")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.editionRemoved); + return writer; + }; + + /** + * Encodes the specified FeatureSupport message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport} message FeatureSupport message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FeatureSupport.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FeatureSupport.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FieldOptions.FeatureSupport(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.editionIntroduced = reader.int32(); + break; + } + case 2: { + message.editionDeprecated = reader.int32(); + break; + } + case 3: { + message.deprecationWarning = reader.string(); + break; + } + case 4: { + message.editionRemoved = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FeatureSupport.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FeatureSupport message. + * @function verify + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FeatureSupport.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.editionIntroduced != null && message.hasOwnProperty("editionIntroduced")) + switch (message.editionIntroduced) { + default: + return "editionIntroduced: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + if (message.editionDeprecated != null && message.hasOwnProperty("editionDeprecated")) + switch (message.editionDeprecated) { + default: + return "editionDeprecated: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + if (message.deprecationWarning != null && message.hasOwnProperty("deprecationWarning")) + if (!$util.isString(message.deprecationWarning)) + return "deprecationWarning: string expected"; + if (message.editionRemoved != null && message.hasOwnProperty("editionRemoved")) + switch (message.editionRemoved) { + default: + return "editionRemoved: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + return null; + }; + + /** + * 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.edition = 1000; + message.editionRemoved = 1000; break; case "EDITION_2024": case 1001: - message.edition = 1001; + message.editionRemoved = 1001; break; case "EDITION_1_TEST_ONLY": case 1: - message.edition = 1; + message.editionRemoved = 1; break; case "EDITION_2_TEST_ONLY": case 2: - message.edition = 2; + message.editionRemoved = 2; break; case "EDITION_99997_TEST_ONLY": case 99997: - message.edition = 99997; + message.editionRemoved = 99997; break; case "EDITION_99998_TEST_ONLY": case 99998: - message.edition = 99998; + message.editionRemoved = 99998; break; case "EDITION_99999_TEST_ONLY": case 99999: - message.edition = 99999; + message.editionRemoved = 99999; break; case "EDITION_MAX": case 2147483647: - message.edition = 2147483647; + message.editionRemoved = 2147483647; break; } - 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 FeatureSupport message. Also converts values to other types if specified. * @function toObject - * @memberof google.protobuf.FieldOptions.EditionDefault + * @memberof google.protobuf.FieldOptions.FeatureSupport * @static - * @param {google.protobuf.FieldOptions.EditionDefault} message EditionDefault + * @param {google.protobuf.FieldOptions.FeatureSupport} message FeatureSupport * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - EditionDefault.toObject = function toObject(message, options) { + FeatureSupport.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { - object.value = ""; - object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; - } - 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; + 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 EditionDefault to JSON. + * Converts this FeatureSupport to JSON. * @function toJSON - * @memberof google.protobuf.FieldOptions.EditionDefault + * @memberof google.protobuf.FieldOptions.FeatureSupport * @instance * @returns {Object.} JSON object */ - EditionDefault.prototype.toJSON = function toJSON() { + FeatureSupport.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 FeatureSupport * @function getTypeUrl - * @memberof google.protobuf.FieldOptions.EditionDefault + * @memberof google.protobuf.FieldOptions.FeatureSupport * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - EditionDefault.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + FeatureSupport.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.protobuf.FieldOptions.EditionDefault"; + return typeUrlPrefix + "/google.protobuf.FieldOptions.FeatureSupport"; }; - return EditionDefault; + return FeatureSupport; })(); return FieldOptions; @@ -158213,6 +159482,7 @@ * @property {boolean|null} [deprecated] EnumValueOptions deprecated * @property {google.protobuf.IFeatureSet|null} [features] EnumValueOptions features * @property {boolean|null} [debugRedact] EnumValueOptions debugRedact + * @property {google.protobuf.FieldOptions.IFeatureSupport|null} [featureSupport] EnumValueOptions featureSupport * @property {Array.|null} [uninterpretedOption] EnumValueOptions uninterpretedOption */ @@ -158256,6 +159526,14 @@ */ EnumValueOptions.prototype.debugRedact = false; + /** + * EnumValueOptions featureSupport. + * @member {google.protobuf.FieldOptions.IFeatureSupport|null|undefined} featureSupport + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.featureSupport = null; + /** * EnumValueOptions uninterpretedOption. * @member {Array.} uninterpretedOption @@ -158294,6 +159572,8 @@ $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); if (message.debugRedact != null && Object.hasOwnProperty.call(message, "debugRedact")) writer.uint32(/* id 3, wireType 0 =*/24).bool(message.debugRedact); + if (message.featureSupport != null && Object.hasOwnProperty.call(message, "featureSupport")) + $root.google.protobuf.FieldOptions.FeatureSupport.encode(message.featureSupport, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); if (message.uninterpretedOption != null && message.uninterpretedOption.length) for (var i = 0; i < message.uninterpretedOption.length; ++i) $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); @@ -158345,6 +159625,10 @@ message.debugRedact = reader.bool(); break; } + case 4: { + message.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.decode(reader, reader.uint32()); + break; + } case 999: { if (!(message.uninterpretedOption && message.uninterpretedOption.length)) message.uninterpretedOption = []; @@ -158397,6 +159681,11 @@ if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) if (typeof message.debugRedact !== "boolean") return "debugRedact: boolean expected"; + if (message.featureSupport != null && message.hasOwnProperty("featureSupport")) { + var error = $root.google.protobuf.FieldOptions.FeatureSupport.verify(message.featureSupport); + if (error) + return "featureSupport." + error; + } if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { if (!Array.isArray(message.uninterpretedOption)) return "uninterpretedOption: array expected"; @@ -158430,6 +159719,11 @@ } if (object.debugRedact != null) message.debugRedact = Boolean(object.debugRedact); + if (object.featureSupport != null) { + if (typeof object.featureSupport !== "object") + throw TypeError(".google.protobuf.EnumValueOptions.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.EnumValueOptions.uninterpretedOption: array expected"); @@ -158462,6 +159756,7 @@ object.deprecated = false; object.features = null; object.debugRedact = false; + object.featureSupport = null; } if (message.deprecated != null && message.hasOwnProperty("deprecated")) object.deprecated = message.deprecated; @@ -158469,6 +159764,8 @@ object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) object.debugRedact = message.debugRedact; + 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) @@ -159936,6 +161233,8 @@ * @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 + * @property {google.protobuf.FeatureSet.EnforceNamingStyle|null} [enforceNamingStyle] FeatureSet enforceNamingStyle + * @property {google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|null} [defaultSymbolVisibility] FeatureSet defaultSymbolVisibility */ /** @@ -160001,6 +161300,22 @@ */ FeatureSet.prototype.jsonFormat = 0; + /** + * FeatureSet enforceNamingStyle. + * @member {google.protobuf.FeatureSet.EnforceNamingStyle} enforceNamingStyle + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.enforceNamingStyle = 0; + + /** + * FeatureSet defaultSymbolVisibility. + * @member {google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility} defaultSymbolVisibility + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.defaultSymbolVisibility = 0; + /** * Creates a new FeatureSet instance using the specified properties. * @function create @@ -160037,6 +161352,10 @@ writer.uint32(/* id 5, wireType 0 =*/40).int32(message.messageEncoding); if (message.jsonFormat != null && Object.hasOwnProperty.call(message, "jsonFormat")) writer.uint32(/* id 6, wireType 0 =*/48).int32(message.jsonFormat); + if (message.enforceNamingStyle != null && Object.hasOwnProperty.call(message, "enforceNamingStyle")) + writer.uint32(/* id 7, wireType 0 =*/56).int32(message.enforceNamingStyle); + if (message.defaultSymbolVisibility != null && Object.hasOwnProperty.call(message, "defaultSymbolVisibility")) + writer.uint32(/* id 8, wireType 0 =*/64).int32(message.defaultSymbolVisibility); return writer; }; @@ -160097,6 +161416,14 @@ message.jsonFormat = reader.int32(); break; } + case 7: { + message.enforceNamingStyle = reader.int32(); + break; + } + case 8: { + message.defaultSymbolVisibility = reader.int32(); + break; + } default: reader.skipType(tag & 7); break; @@ -160187,6 +161514,26 @@ case 2: break; } + if (message.enforceNamingStyle != null && message.hasOwnProperty("enforceNamingStyle")) + switch (message.enforceNamingStyle) { + default: + return "enforceNamingStyle: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.defaultSymbolVisibility != null && message.hasOwnProperty("defaultSymbolVisibility")) + switch (message.defaultSymbolVisibility) { + default: + return "defaultSymbolVisibility: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + break; + } return null; }; @@ -160326,6 +161673,54 @@ message.jsonFormat = 2; break; } + switch (object.enforceNamingStyle) { + default: + if (typeof object.enforceNamingStyle === "number") { + message.enforceNamingStyle = object.enforceNamingStyle; + break; + } + break; + case "ENFORCE_NAMING_STYLE_UNKNOWN": + case 0: + message.enforceNamingStyle = 0; + break; + case "STYLE2024": + case 1: + message.enforceNamingStyle = 1; + break; + case "STYLE_LEGACY": + case 2: + message.enforceNamingStyle = 2; + break; + } + switch (object.defaultSymbolVisibility) { + default: + if (typeof object.defaultSymbolVisibility === "number") { + message.defaultSymbolVisibility = object.defaultSymbolVisibility; + break; + } + break; + case "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN": + case 0: + message.defaultSymbolVisibility = 0; + break; + case "EXPORT_ALL": + case 1: + message.defaultSymbolVisibility = 1; + break; + case "EXPORT_TOP_LEVEL": + case 2: + message.defaultSymbolVisibility = 2; + break; + case "LOCAL_ALL": + case 3: + message.defaultSymbolVisibility = 3; + break; + case "STRICT": + case 4: + message.defaultSymbolVisibility = 4; + break; + } return message; }; @@ -160349,6 +161744,8 @@ 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; + object.enforceNamingStyle = options.enums === String ? "ENFORCE_NAMING_STYLE_UNKNOWN" : 0; + object.defaultSymbolVisibility = options.enums === String ? "DEFAULT_SYMBOL_VISIBILITY_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; @@ -160362,6 +161759,10 @@ 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; + if (message.enforceNamingStyle != null && message.hasOwnProperty("enforceNamingStyle")) + object.enforceNamingStyle = options.enums === String ? $root.google.protobuf.FeatureSet.EnforceNamingStyle[message.enforceNamingStyle] === undefined ? message.enforceNamingStyle : $root.google.protobuf.FeatureSet.EnforceNamingStyle[message.enforceNamingStyle] : message.enforceNamingStyle; + if (message.defaultSymbolVisibility != null && message.hasOwnProperty("defaultSymbolVisibility")) + object.defaultSymbolVisibility = options.enums === String ? $root.google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility[message.defaultSymbolVisibility] === undefined ? message.defaultSymbolVisibility : $root.google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility[message.defaultSymbolVisibility] : message.defaultSymbolVisibility; return object; }; @@ -160489,6 +161890,219 @@ return values; })(); + /** + * EnforceNamingStyle enum. + * @name google.protobuf.FeatureSet.EnforceNamingStyle + * @enum {number} + * @property {number} ENFORCE_NAMING_STYLE_UNKNOWN=0 ENFORCE_NAMING_STYLE_UNKNOWN value + * @property {number} STYLE2024=1 STYLE2024 value + * @property {number} STYLE_LEGACY=2 STYLE_LEGACY value + */ + FeatureSet.EnforceNamingStyle = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ENFORCE_NAMING_STYLE_UNKNOWN"] = 0; + values[valuesById[1] = "STYLE2024"] = 1; + values[valuesById[2] = "STYLE_LEGACY"] = 2; + return values; + })(); + + FeatureSet.VisibilityFeature = (function() { + + /** + * Properties of a VisibilityFeature. + * @memberof google.protobuf.FeatureSet + * @interface IVisibilityFeature + */ + + /** + * Constructs a new VisibilityFeature. + * @memberof google.protobuf.FeatureSet + * @classdesc Represents a VisibilityFeature. + * @implements IVisibilityFeature + * @constructor + * @param {google.protobuf.FeatureSet.IVisibilityFeature=} [properties] Properties to set + */ + function VisibilityFeature(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 new VisibilityFeature instance using the specified properties. + * @function create + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature=} [properties] Properties to set + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature instance + */ + VisibilityFeature.create = function create(properties) { + return new VisibilityFeature(properties); + }; + + /** + * Encodes the specified VisibilityFeature message. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature} message VisibilityFeature message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + VisibilityFeature.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + return writer; + }; + + /** + * Encodes the specified VisibilityFeature message, length delimited. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature} message VisibilityFeature message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + VisibilityFeature.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + VisibilityFeature.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FeatureSet.VisibilityFeature(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + VisibilityFeature.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a VisibilityFeature message. + * @function verify + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + VisibilityFeature.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + return null; + }; + + /** + * Creates a VisibilityFeature message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + */ + VisibilityFeature.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FeatureSet.VisibilityFeature) + return object; + return new $root.google.protobuf.FeatureSet.VisibilityFeature(); + }; + + /** + * Creates a plain object from a VisibilityFeature message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.VisibilityFeature} message VisibilityFeature + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + VisibilityFeature.toObject = function toObject() { + return {}; + }; + + /** + * Converts this VisibilityFeature to JSON. + * @function toJSON + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @instance + * @returns {Object.} JSON object + */ + VisibilityFeature.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for VisibilityFeature + * @function getTypeUrl + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + VisibilityFeature.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FeatureSet.VisibilityFeature"; + }; + + /** + * DefaultSymbolVisibility enum. + * @name google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility + * @enum {number} + * @property {number} DEFAULT_SYMBOL_VISIBILITY_UNKNOWN=0 DEFAULT_SYMBOL_VISIBILITY_UNKNOWN value + * @property {number} EXPORT_ALL=1 EXPORT_ALL value + * @property {number} EXPORT_TOP_LEVEL=2 EXPORT_TOP_LEVEL value + * @property {number} LOCAL_ALL=3 LOCAL_ALL value + * @property {number} STRICT=4 STRICT value + */ + VisibilityFeature.DefaultSymbolVisibility = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN"] = 0; + values[valuesById[1] = "EXPORT_ALL"] = 1; + values[valuesById[2] = "EXPORT_TOP_LEVEL"] = 2; + values[valuesById[3] = "LOCAL_ALL"] = 3; + values[valuesById[4] = "STRICT"] = 4; + return values; + })(); + + return VisibilityFeature; + })(); + return FeatureSet; })(); @@ -160673,6 +162287,7 @@ default: return "minimumEdition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -160690,6 +162305,7 @@ default: return "maximumEdition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -160738,6 +162354,10 @@ case 0: message.minimumEdition = 0; break; + case "EDITION_LEGACY": + case 900: + message.minimumEdition = 900; + break; case "EDITION_PROTO2": case 998: message.minimumEdition = 998; @@ -160790,6 +162410,10 @@ case 0: message.maximumEdition = 0; break; + case "EDITION_LEGACY": + case 900: + message.maximumEdition = 900; + break; case "EDITION_PROTO2": case 998: message.maximumEdition = 998; @@ -160898,7 +162522,8 @@ * @memberof google.protobuf.FeatureSetDefaults * @interface IFeatureSetEditionDefault * @property {google.protobuf.Edition|null} [edition] FeatureSetEditionDefault edition - * @property {google.protobuf.IFeatureSet|null} [features] FeatureSetEditionDefault features + * @property {google.protobuf.IFeatureSet|null} [overridableFeatures] FeatureSetEditionDefault overridableFeatures + * @property {google.protobuf.IFeatureSet|null} [fixedFeatures] FeatureSetEditionDefault fixedFeatures */ /** @@ -160925,12 +162550,20 @@ FeatureSetEditionDefault.prototype.edition = 0; /** - * FeatureSetEditionDefault features. - * @member {google.protobuf.IFeatureSet|null|undefined} features + * 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 * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault * @instance */ - FeatureSetEditionDefault.prototype.features = null; + FeatureSetEditionDefault.prototype.fixedFeatures = null; /** * Creates a new FeatureSetEditionDefault instance using the specified properties. @@ -160956,10 +162589,12 @@ FeatureSetEditionDefault.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); - if (message.features != null && Object.hasOwnProperty.call(message, "features")) - $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); if (message.edition != null && Object.hasOwnProperty.call(message, "edition")) writer.uint32(/* id 3, wireType 0 =*/24).int32(message.edition); + if (message.overridableFeatures != null && Object.hasOwnProperty.call(message, "overridableFeatures")) + $root.google.protobuf.FeatureSet.encode(message.overridableFeatures, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.fixedFeatures != null && Object.hasOwnProperty.call(message, "fixedFeatures")) + $root.google.protobuf.FeatureSet.encode(message.fixedFeatures, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); return writer; }; @@ -161000,8 +162635,12 @@ message.edition = reader.int32(); break; } - case 2: { - message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + case 4: { + message.overridableFeatures = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + break; + } + case 5: { + message.fixedFeatures = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); break; } default: @@ -161044,6 +162683,7 @@ default: return "edition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -161056,10 +162696,15 @@ case 2147483647: break; } - if (message.features != null && message.hasOwnProperty("features")) { - var error = $root.google.protobuf.FeatureSet.verify(message.features); + if (message.overridableFeatures != null && message.hasOwnProperty("overridableFeatures")) { + var error = $root.google.protobuf.FeatureSet.verify(message.overridableFeatures); + if (error) + return "overridableFeatures." + error; + } + if (message.fixedFeatures != null && message.hasOwnProperty("fixedFeatures")) { + var error = $root.google.protobuf.FeatureSet.verify(message.fixedFeatures); if (error) - return "features." + error; + return "fixedFeatures." + error; } return null; }; @@ -161087,6 +162732,10 @@ case 0: message.edition = 0; break; + case "EDITION_LEGACY": + case 900: + message.edition = 900; + break; case "EDITION_PROTO2": case 998: message.edition = 998; @@ -161128,10 +162777,15 @@ message.edition = 2147483647; break; } - 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); + 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); } return message; }; @@ -161150,13 +162804,16 @@ 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; }; @@ -162371,6 +164028,22 @@ return GeneratedCodeInfo; })(); + /** + * SymbolVisibility enum. + * @name google.protobuf.SymbolVisibility + * @enum {number} + * @property {number} VISIBILITY_UNSET=0 VISIBILITY_UNSET value + * @property {number} VISIBILITY_LOCAL=1 VISIBILITY_LOCAL value + * @property {number} VISIBILITY_EXPORT=2 VISIBILITY_EXPORT value + */ + protobuf.SymbolVisibility = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "VISIBILITY_UNSET"] = 0; + values[valuesById[1] = "VISIBILITY_LOCAL"] = 1; + values[valuesById[2] = "VISIBILITY_EXPORT"] = 2; + return values; + })(); + protobuf.Duration = (function() { /** diff --git a/packages/google-ai-generativelanguage/protos/protos.json b/packages/google-ai-generativelanguage/protos/protos.json index eb50df440f3c..634f75a70faf 100644 --- a/packages/google-ai-generativelanguage/protos/protos.json +++ b/packages/google-ai-generativelanguage/protos/protos.json @@ -17274,8 +17274,7 @@ "java_multiple_files": true, "java_outer_classname": "ResourceProto", "java_package": "com.google.api", - "objc_class_prefix": "GAPI", - "cc_enable_arenas": true + "objc_class_prefix": "GAPI" }, "nested": { "fieldBehavior": { @@ -17421,6 +17420,10 @@ "rule": "repeated", "type": "ClientLibraryDestination", "id": 2 + }, + "selectiveGapicGeneration": { + "type": "SelectiveGapicGeneration", + "id": 3 } } }, @@ -17561,6 +17564,28 @@ "common": { "type": "CommonLanguageSettings", "id": 1 + }, + "experimentalFeatures": { + "type": "ExperimentalFeatures", + "id": 2 + } + }, + "nested": { + "ExperimentalFeatures": { + "fields": { + "restAsyncIoEnabled": { + "type": "bool", + "id": 1 + }, + "protobufPythonicTypesEnabled": { + "type": "bool", + "id": 2 + }, + "unversionedPackageDisabled": { + "type": "bool", + "id": 3 + } + } } } }, @@ -17618,6 +17643,11 @@ "common": { "type": "CommonLanguageSettings", "id": 1 + }, + "renamedServices": { + "keyType": "string", + "type": "string", + "id": 2 } } }, @@ -17679,6 +17709,19 @@ "PACKAGE_MANAGER": 20 } }, + "SelectiveGapicGeneration": { + "fields": { + "methods": { + "rule": "repeated", + "type": "string", + "id": 1 + }, + "generateOmittedAsInternal": { + "type": "bool", + "id": 2 + } + } + }, "LaunchStage": { "values": { "LAUNCH_STAGE_UNSPECIFIED": 0, @@ -17789,12 +17832,19 @@ "type": "FileDescriptorProto", "id": 1 } - } + }, + "extensions": [ + [ + 536000000, + 536000000 + ] + ] }, "Edition": { "edition": "proto2", "values": { "EDITION_UNKNOWN": 0, + "EDITION_LEGACY": 900, "EDITION_PROTO2": 998, "EDITION_PROTO3": 999, "EDITION_2023": 1000, @@ -17833,6 +17883,11 @@ "type": "int32", "id": 11 }, + "optionDependency": { + "rule": "repeated", + "type": "string", + "id": 15 + }, "messageType": { "rule": "repeated", "type": "DescriptorProto", @@ -17921,6 +17976,10 @@ "rule": "repeated", "type": "string", "id": 10 + }, + "visibility": { + "type": "SymbolVisibility", + "id": 11 } }, "nested": { @@ -18146,6 +18205,10 @@ "rule": "repeated", "type": "string", "id": 5 + }, + "visibility": { + "type": "SymbolVisibility", + "id": 6 } }, "nested": { @@ -18196,7 +18259,14 @@ "type": "ServiceOptions", "id": 3 } - } + }, + "reserved": [ + [ + 4, + 4 + ], + "stream" + ] }, "MethodDescriptorProto": { "edition": "proto2", @@ -18360,6 +18430,7 @@ 42, 42 ], + "php_generic_services", [ 38, 38 @@ -18495,7 +18566,8 @@ "type": "bool", "id": 10, "options": { - "default": false + "default": false, + "deprecated": true } }, "debugRedact": { @@ -18523,6 +18595,10 @@ "type": "FeatureSet", "id": 21 }, + "featureSupport": { + "type": "FeatureSupport", + "id": 22 + }, "uninterpretedOption": { "rule": "repeated", "type": "UninterpretedOption", @@ -18592,6 +18668,26 @@ "id": 2 } } + }, + "FeatureSupport": { + "fields": { + "editionIntroduced": { + "type": "Edition", + "id": 1 + }, + "editionDeprecated": { + "type": "Edition", + "id": 2 + }, + "deprecationWarning": { + "type": "string", + "id": 3 + }, + "editionRemoved": { + "type": "Edition", + "id": 4 + } + } } } }, @@ -18680,6 +18776,10 @@ "default": false } }, + "featureSupport": { + "type": "FieldOptions.FeatureSupport", + "id": 4 + }, "uninterpretedOption": { "rule": "repeated", "type": "UninterpretedOption", @@ -18822,6 +18922,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_2023", "edition_defaults.value": "EXPLICIT" } @@ -18832,6 +18933,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "OPEN" } @@ -18842,6 +18944,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "PACKED" } @@ -18852,6 +18955,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "VERIFY" } @@ -18862,7 +18966,8 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", - "edition_defaults.edition": "EDITION_PROTO2", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_LEGACY", "edition_defaults.value": "LENGTH_PREFIXED" } }, @@ -18872,27 +18977,38 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "ALLOW" } + }, + "enforceNamingStyle": { + "type": "EnforceNamingStyle", + "id": 7, + "options": { + "retention": "RETENTION_SOURCE", + "targets": "TARGET_TYPE_METHOD", + "feature_support.edition_introduced": "EDITION_2024", + "edition_defaults.edition": "EDITION_2024", + "edition_defaults.value": "STYLE2024" + } + }, + "defaultSymbolVisibility": { + "type": "VisibilityFeature.DefaultSymbolVisibility", + "id": 8, + "options": { + "retention": "RETENTION_SOURCE", + "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2024", + "edition_defaults.edition": "EDITION_2024", + "edition_defaults.value": "EXPORT_TOP_LEVEL" + } } }, "extensions": [ [ 1000, - 1000 - ], - [ - 1001, - 1001 - ], - [ - 1002, - 1002 - ], - [ - 9990, - 9990 + 9994 ], [ 9995, @@ -18937,7 +19053,13 @@ "UTF8_VALIDATION_UNKNOWN": 0, "VERIFY": 2, "NONE": 3 - } + }, + "reserved": [ + [ + 1, + 1 + ] + ] }, "MessageEncoding": { "values": { @@ -18952,6 +19074,33 @@ "ALLOW": 1, "LEGACY_BEST_EFFORT": 2 } + }, + "EnforceNamingStyle": { + "values": { + "ENFORCE_NAMING_STYLE_UNKNOWN": 0, + "STYLE2024": 1, + "STYLE_LEGACY": 2 + } + }, + "VisibilityFeature": { + "fields": {}, + "reserved": [ + [ + 1, + 536870911 + ] + ], + "nested": { + "DefaultSymbolVisibility": { + "values": { + "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN": 0, + "EXPORT_ALL": 1, + "EXPORT_TOP_LEVEL": 2, + "LOCAL_ALL": 3, + "STRICT": 4 + } + } + } } } }, @@ -18979,11 +19128,26 @@ "type": "Edition", "id": 3 }, - "features": { + "overridableFeatures": { "type": "FeatureSet", - "id": 2 + "id": 4 + }, + "fixedFeatures": { + "type": "FeatureSet", + "id": 5 } - } + }, + "reserved": [ + [ + 1, + 1 + ], + [ + 2, + 2 + ], + "features" + ] } } }, @@ -18996,6 +19160,12 @@ "id": 1 } }, + "extensions": [ + [ + 536000000, + 536000000 + ] + ], "nested": { "Location": { "fields": { @@ -19081,6 +19251,14 @@ } } }, + "SymbolVisibility": { + "edition": "proto2", + "values": { + "VISIBILITY_UNSET": 0, + "VISIBILITY_LOCAL": 1, + "VISIBILITY_EXPORT": 2 + } + }, "Duration": { "fields": { "seconds": { @@ -19231,6 +19409,7 @@ "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/packages/google-ai-generativelanguage/samples/generated/v1/snippet_metadata_google.ai.generativelanguage.v1.json b/packages/google-ai-generativelanguage/samples/generated/v1/snippet_metadata_google.ai.generativelanguage.v1.json index 7adf7770f50f..37bbfc9854d6 100644 --- a/packages/google-ai-generativelanguage/samples/generated/v1/snippet_metadata_google.ai.generativelanguage.v1.json +++ b/packages/google-ai-generativelanguage/samples/generated/v1/snippet_metadata_google.ai.generativelanguage.v1.json @@ -1,7 +1,7 @@ { "clientLibrary": { "name": "nodejs-generativelanguage", - "version": "3.7.0", + "version": "0.1.0", "language": "TYPESCRIPT", "apis": [ { diff --git a/packages/google-ai-generativelanguage/samples/generated/v1alpha/snippet_metadata_google.ai.generativelanguage.v1alpha.json b/packages/google-ai-generativelanguage/samples/generated/v1alpha/snippet_metadata_google.ai.generativelanguage.v1alpha.json index 0d11b9069e2e..563ded215d08 100644 --- a/packages/google-ai-generativelanguage/samples/generated/v1alpha/snippet_metadata_google.ai.generativelanguage.v1alpha.json +++ b/packages/google-ai-generativelanguage/samples/generated/v1alpha/snippet_metadata_google.ai.generativelanguage.v1alpha.json @@ -1,7 +1,7 @@ { "clientLibrary": { "name": "nodejs-generativelanguage", - "version": "3.7.0", + "version": "0.1.0", "language": "TYPESCRIPT", "apis": [ { diff --git a/packages/google-ai-generativelanguage/samples/generated/v1beta/snippet_metadata_google.ai.generativelanguage.v1beta.json b/packages/google-ai-generativelanguage/samples/generated/v1beta/snippet_metadata_google.ai.generativelanguage.v1beta.json index 2e1082d63d77..23b0998bd7b2 100644 --- a/packages/google-ai-generativelanguage/samples/generated/v1beta/snippet_metadata_google.ai.generativelanguage.v1beta.json +++ b/packages/google-ai-generativelanguage/samples/generated/v1beta/snippet_metadata_google.ai.generativelanguage.v1beta.json @@ -1,7 +1,7 @@ { "clientLibrary": { "name": "nodejs-generativelanguage", - "version": "3.7.0", + "version": "0.1.0", "language": "TYPESCRIPT", "apis": [ { diff --git a/packages/google-ai-generativelanguage/samples/generated/v1beta2/snippet_metadata_google.ai.generativelanguage.v1beta2.json b/packages/google-ai-generativelanguage/samples/generated/v1beta2/snippet_metadata_google.ai.generativelanguage.v1beta2.json index 593685524d28..1dbe29e29b31 100644 --- a/packages/google-ai-generativelanguage/samples/generated/v1beta2/snippet_metadata_google.ai.generativelanguage.v1beta2.json +++ b/packages/google-ai-generativelanguage/samples/generated/v1beta2/snippet_metadata_google.ai.generativelanguage.v1beta2.json @@ -1,7 +1,7 @@ { "clientLibrary": { "name": "nodejs-generativelanguage", - "version": "3.7.0", + "version": "0.1.0", "language": "TYPESCRIPT", "apis": [ { diff --git a/packages/google-ai-generativelanguage/samples/generated/v1beta3/snippet_metadata_google.ai.generativelanguage.v1beta3.json b/packages/google-ai-generativelanguage/samples/generated/v1beta3/snippet_metadata_google.ai.generativelanguage.v1beta3.json index f85d68722e7e..3ff1d5220413 100644 --- a/packages/google-ai-generativelanguage/samples/generated/v1beta3/snippet_metadata_google.ai.generativelanguage.v1beta3.json +++ b/packages/google-ai-generativelanguage/samples/generated/v1beta3/snippet_metadata_google.ai.generativelanguage.v1beta3.json @@ -1,7 +1,7 @@ { "clientLibrary": { "name": "nodejs-generativelanguage", - "version": "3.7.0", + "version": "0.1.0", "language": "TYPESCRIPT", "apis": [ { diff --git a/packages/google-ai-generativelanguage/src/v1/generative_service_client.ts b/packages/google-ai-generativelanguage/src/v1/generative_service_client.ts index 6746c25e8145..bb0b39bb372d 100644 --- a/packages/google-ai-generativelanguage/src/v1/generative_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1/generative_service_client.ts @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; -import {PassThrough} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; +import { PassThrough } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -45,7 +50,7 @@ export class GenerativeServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -58,9 +63,9 @@ export class GenerativeServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - generativeServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + generativeServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of GenerativeServiceClient. @@ -101,21 +106,42 @@ export class GenerativeServiceClient { * const client = new GenerativeServiceClient({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 GenerativeServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -140,7 +166,7 @@ export class GenerativeServiceClient { 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; @@ -154,10 +180,7 @@ export class GenerativeServiceClient { } // 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 { @@ -178,21 +201,26 @@ export class GenerativeServiceClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' - ), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this.descriptors.stream = { - streamGenerateContent: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries) + streamGenerateContent: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1.GenerativeService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1.GenerativeService', + 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 @@ -223,44 +251,59 @@ export class GenerativeServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1.GenerativeService. this.generativeServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1.GenerativeService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1.GenerativeService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1.GenerativeService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1 + .GenerativeService, + 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 generativeServiceStubMethods = - ['generateContent', 'streamGenerateContent', 'embedContent', 'batchEmbedContents', 'countTokens']; + const generativeServiceStubMethods = [ + 'generateContent', + 'streamGenerateContent', + 'embedContent', + 'batchEmbedContents', + 'countTokens', + ]; for (const methodName of generativeServiceStubMethods) { const callPromise = this.generativeServiceStub.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.stream[methodName] || - undefined; + const descriptor = this.descriptors.stream[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -275,8 +318,14 @@ export class GenerativeServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -287,8 +336,14 @@ export class GenerativeServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -328,8 +383,9 @@ export class GenerativeServiceClient { * 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; @@ -340,532 +396,717 @@ export class GenerativeServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Generates a model response given an input `GenerateContentRequest`. - * Refer to the [text generation - * guide](https://ai.google.dev/gemini-api/docs/text-generation) for detailed - * usage information. Input capabilities differ between models, including - * tuned models. Refer to the [model - * guide](https://ai.google.dev/gemini-api/docs/models/gemini) and [tuning - * guide](https://ai.google.dev/gemini-api/docs/model-tuning) for details. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The name of the `Model` to use for generating the completion. - * - * Format: `models/{model}`. - * @param {number[]} request.contents - * Required. The content of the current conversation with the model. - * - * For single-turn queries, this is a single instance. For multi-turn queries - * like [chat](https://ai.google.dev/gemini-api/docs/text-generation#chat), - * this is a repeated field that contains the conversation history and the - * latest request. - * @param {number[]} [request.safetySettings] - * Optional. A list of unique `SafetySetting` instances for blocking unsafe - * content. - * - * This will be enforced on the `GenerateContentRequest.contents` and - * `GenerateContentResponse.candidates`. There should not be more than one - * setting for each `SafetyCategory` type. The API will block any contents and - * responses that fail to meet the thresholds set by these settings. This list - * overrides the default settings for each `SafetyCategory` specified in the - * safety_settings. If there is no `SafetySetting` for a given - * `SafetyCategory` provided in the list, the API will use the default safety - * setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH, - * HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, - * HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY are supported. - * Refer to the [guide](https://ai.google.dev/gemini-api/docs/safety-settings) - * for detailed information on available safety settings. Also refer to the - * [Safety guidance](https://ai.google.dev/gemini-api/docs/safety-guidance) to - * learn how to incorporate safety considerations in your AI applications. - * @param {google.ai.generativelanguage.v1.GenerationConfig} [request.generationConfig] - * Optional. Configuration options for model generation and outputs. - * @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.ai.generativelanguage.v1.GenerateContentResponse|GenerateContentResponse}. - * 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/generative_service.generate_content.js - * region_tag:generativelanguage_v1_generated_GenerativeService_GenerateContent_async - */ + /** + * Generates a model response given an input `GenerateContentRequest`. + * Refer to the [text generation + * guide](https://ai.google.dev/gemini-api/docs/text-generation) for detailed + * usage information. Input capabilities differ between models, including + * tuned models. Refer to the [model + * guide](https://ai.google.dev/gemini-api/docs/models/gemini) and [tuning + * guide](https://ai.google.dev/gemini-api/docs/model-tuning) for details. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The name of the `Model` to use for generating the completion. + * + * Format: `models/{model}`. + * @param {number[]} request.contents + * Required. The content of the current conversation with the model. + * + * For single-turn queries, this is a single instance. For multi-turn queries + * like [chat](https://ai.google.dev/gemini-api/docs/text-generation#chat), + * this is a repeated field that contains the conversation history and the + * latest request. + * @param {number[]} [request.safetySettings] + * Optional. A list of unique `SafetySetting` instances for blocking unsafe + * content. + * + * This will be enforced on the `GenerateContentRequest.contents` and + * `GenerateContentResponse.candidates`. There should not be more than one + * setting for each `SafetyCategory` type. The API will block any contents and + * responses that fail to meet the thresholds set by these settings. This list + * overrides the default settings for each `SafetyCategory` specified in the + * safety_settings. If there is no `SafetySetting` for a given + * `SafetyCategory` provided in the list, the API will use the default safety + * setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH, + * HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, + * HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY are supported. + * Refer to the [guide](https://ai.google.dev/gemini-api/docs/safety-settings) + * for detailed information on available safety settings. Also refer to the + * [Safety guidance](https://ai.google.dev/gemini-api/docs/safety-guidance) to + * learn how to incorporate safety considerations in your AI applications. + * @param {google.ai.generativelanguage.v1.GenerationConfig} [request.generationConfig] + * Optional. Configuration options for model generation and outputs. + * @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.ai.generativelanguage.v1.GenerateContentResponse|GenerateContentResponse}. + * 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/generative_service.generate_content.js + * region_tag:generativelanguage_v1_generated_GenerativeService_GenerateContent_async + */ generateContent( - request?: protos.google.ai.generativelanguage.v1.IGenerateContentRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1.IGenerateContentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1.IGenerateContentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1.IGenerateContentResponse, + ( + | protos.google.ai.generativelanguage.v1.IGenerateContentRequest + | undefined + ), + {} | undefined, + ] + >; generateContent( - request: protos.google.ai.generativelanguage.v1.IGenerateContentRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1.IGenerateContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1.IGenerateContentRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1.IGenerateContentResponse, + | protos.google.ai.generativelanguage.v1.IGenerateContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateContent( - request: protos.google.ai.generativelanguage.v1.IGenerateContentRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1.IGenerateContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1.IGenerateContentRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1.IGenerateContentResponse, + | protos.google.ai.generativelanguage.v1.IGenerateContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateContent( - request?: protos.google.ai.generativelanguage.v1.IGenerateContentRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1.IGenerateContentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1.IGenerateContentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1.IGenerateContentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1.IGenerateContentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1.IGenerateContentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1.IGenerateContentResponse, + | protos.google.ai.generativelanguage.v1.IGenerateContentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1.IGenerateContentResponse, + ( + | protos.google.ai.generativelanguage.v1.IGenerateContentRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('generateContent request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1.IGenerateContentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1.IGenerateContentResponse, + | protos.google.ai.generativelanguage.v1.IGenerateContentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('generateContent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.generateContent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1.IGenerateContentRequest|undefined, - {}|undefined - ]) => { - this._log.info('generateContent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .generateContent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1.IGenerateContentResponse, + ( + | protos.google.ai.generativelanguage.v1.IGenerateContentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('generateContent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Generates a text embedding vector from the input `Content` using the - * specified [Gemini Embedding - * model](https://ai.google.dev/gemini-api/docs/models/gemini#text-embedding). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The model's resource name. This serves as an ID for the Model to - * use. - * - * This name should match a model name returned by the `ListModels` method. - * - * Format: `models/{model}` - * @param {google.ai.generativelanguage.v1.Content} request.content - * Required. The content to embed. Only the `parts.text` fields will be - * counted. - * @param {google.ai.generativelanguage.v1.TaskType} [request.taskType] - * Optional. Optional task type for which the embeddings will be used. Not - * supported on earlier models (`models/embedding-001`). - * @param {string} [request.title] - * Optional. An optional title for the text. Only applicable when TaskType is - * `RETRIEVAL_DOCUMENT`. - * - * Note: Specifying a `title` for `RETRIEVAL_DOCUMENT` provides better quality - * embeddings for retrieval. - * @param {number} [request.outputDimensionality] - * Optional. Optional reduced dimension for the output embedding. If set, - * excessive values in the output embedding are truncated from the end. - * Supported by newer models since 2024 only. You cannot set this value if - * using the earlier model (`models/embedding-001`). - * @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.ai.generativelanguage.v1.EmbedContentResponse|EmbedContentResponse}. - * 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/generative_service.embed_content.js - * region_tag:generativelanguage_v1_generated_GenerativeService_EmbedContent_async - */ + /** + * Generates a text embedding vector from the input `Content` using the + * specified [Gemini Embedding + * model](https://ai.google.dev/gemini-api/docs/models/gemini#text-embedding). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The model's resource name. This serves as an ID for the Model to + * use. + * + * This name should match a model name returned by the `ListModels` method. + * + * Format: `models/{model}` + * @param {google.ai.generativelanguage.v1.Content} request.content + * Required. The content to embed. Only the `parts.text` fields will be + * counted. + * @param {google.ai.generativelanguage.v1.TaskType} [request.taskType] + * Optional. Optional task type for which the embeddings will be used. Not + * supported on earlier models (`models/embedding-001`). + * @param {string} [request.title] + * Optional. An optional title for the text. Only applicable when TaskType is + * `RETRIEVAL_DOCUMENT`. + * + * Note: Specifying a `title` for `RETRIEVAL_DOCUMENT` provides better quality + * embeddings for retrieval. + * @param {number} [request.outputDimensionality] + * Optional. Optional reduced dimension for the output embedding. If set, + * excessive values in the output embedding are truncated from the end. + * Supported by newer models since 2024 only. You cannot set this value if + * using the earlier model (`models/embedding-001`). + * @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.ai.generativelanguage.v1.EmbedContentResponse|EmbedContentResponse}. + * 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/generative_service.embed_content.js + * region_tag:generativelanguage_v1_generated_GenerativeService_EmbedContent_async + */ embedContent( - request?: protos.google.ai.generativelanguage.v1.IEmbedContentRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1.IEmbedContentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1.IEmbedContentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1.IEmbedContentResponse, + protos.google.ai.generativelanguage.v1.IEmbedContentRequest | undefined, + {} | undefined, + ] + >; embedContent( - request: protos.google.ai.generativelanguage.v1.IEmbedContentRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1.IEmbedContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1.IEmbedContentRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1.IEmbedContentResponse, + | protos.google.ai.generativelanguage.v1.IEmbedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; embedContent( - request: protos.google.ai.generativelanguage.v1.IEmbedContentRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1.IEmbedContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1.IEmbedContentRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1.IEmbedContentResponse, + | protos.google.ai.generativelanguage.v1.IEmbedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; embedContent( - request?: protos.google.ai.generativelanguage.v1.IEmbedContentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1.IEmbedContentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1.IEmbedContentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1.IEmbedContentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1.IEmbedContentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1.IEmbedContentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1.IEmbedContentResponse, + | protos.google.ai.generativelanguage.v1.IEmbedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1.IEmbedContentResponse, + protos.google.ai.generativelanguage.v1.IEmbedContentRequest | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('embedContent request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1.IEmbedContentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1.IEmbedContentResponse, + | protos.google.ai.generativelanguage.v1.IEmbedContentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('embedContent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.embedContent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1.IEmbedContentRequest|undefined, - {}|undefined - ]) => { - this._log.info('embedContent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .embedContent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1.IEmbedContentResponse, + ( + | protos.google.ai.generativelanguage.v1.IEmbedContentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('embedContent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Generates multiple embedding vectors from the input `Content` which - * consists of a batch of strings represented as `EmbedContentRequest` - * objects. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The model's resource name. This serves as an ID for the Model to - * use. - * - * This name should match a model name returned by the `ListModels` method. - * - * Format: `models/{model}` - * @param {number[]} request.requests - * Required. Embed requests for the batch. The model in each of these requests - * must match the model specified `BatchEmbedContentsRequest.model`. - * @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.ai.generativelanguage.v1.BatchEmbedContentsResponse|BatchEmbedContentsResponse}. - * 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/generative_service.batch_embed_contents.js - * region_tag:generativelanguage_v1_generated_GenerativeService_BatchEmbedContents_async - */ + /** + * Generates multiple embedding vectors from the input `Content` which + * consists of a batch of strings represented as `EmbedContentRequest` + * objects. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The model's resource name. This serves as an ID for the Model to + * use. + * + * This name should match a model name returned by the `ListModels` method. + * + * Format: `models/{model}` + * @param {number[]} request.requests + * Required. Embed requests for the batch. The model in each of these requests + * must match the model specified `BatchEmbedContentsRequest.model`. + * @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.ai.generativelanguage.v1.BatchEmbedContentsResponse|BatchEmbedContentsResponse}. + * 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/generative_service.batch_embed_contents.js + * region_tag:generativelanguage_v1_generated_GenerativeService_BatchEmbedContents_async + */ batchEmbedContents( - request?: protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1.IBatchEmbedContentsResponse, + ( + | protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest + | undefined + ), + {} | undefined, + ] + >; batchEmbedContents( - request: protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1.IBatchEmbedContentsResponse, + | protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchEmbedContents( - request: protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1.IBatchEmbedContentsResponse, + | protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchEmbedContents( - request?: protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1.IBatchEmbedContentsResponse, + | protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1.IBatchEmbedContentsResponse, + ( + | protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('batchEmbedContents request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1.IBatchEmbedContentsResponse, + | protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchEmbedContents response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.batchEmbedContents(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest|undefined, - {}|undefined - ]) => { - this._log.info('batchEmbedContents response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchEmbedContents(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1.IBatchEmbedContentsResponse, + ( + | protos.google.ai.generativelanguage.v1.IBatchEmbedContentsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchEmbedContents response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Runs a model's tokenizer on input `Content` and returns the token count. - * Refer to the [tokens guide](https://ai.google.dev/gemini-api/docs/tokens) - * to learn more about tokens. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The model's resource name. This serves as an ID for the Model to - * use. - * - * This name should match a model name returned by the `ListModels` method. - * - * Format: `models/{model}` - * @param {number[]} [request.contents] - * Optional. The input given to the model as a prompt. This field is ignored - * when `generate_content_request` is set. - * @param {google.ai.generativelanguage.v1.GenerateContentRequest} [request.generateContentRequest] - * Optional. The overall input given to the `Model`. This includes the prompt - * as well as other model steering information like [system - * instructions](https://ai.google.dev/gemini-api/docs/system-instructions), - * and/or function declarations for [function - * calling](https://ai.google.dev/gemini-api/docs/function-calling). - * `Model`s/`Content`s and `generate_content_request`s are mutually - * exclusive. You can either send `Model` + `Content`s or a - * `generate_content_request`, but never both. - * @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.ai.generativelanguage.v1.CountTokensResponse|CountTokensResponse}. - * 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/generative_service.count_tokens.js - * region_tag:generativelanguage_v1_generated_GenerativeService_CountTokens_async - */ + /** + * Runs a model's tokenizer on input `Content` and returns the token count. + * Refer to the [tokens guide](https://ai.google.dev/gemini-api/docs/tokens) + * to learn more about tokens. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The model's resource name. This serves as an ID for the Model to + * use. + * + * This name should match a model name returned by the `ListModels` method. + * + * Format: `models/{model}` + * @param {number[]} [request.contents] + * Optional. The input given to the model as a prompt. This field is ignored + * when `generate_content_request` is set. + * @param {google.ai.generativelanguage.v1.GenerateContentRequest} [request.generateContentRequest] + * Optional. The overall input given to the `Model`. This includes the prompt + * as well as other model steering information like [system + * instructions](https://ai.google.dev/gemini-api/docs/system-instructions), + * and/or function declarations for [function + * calling](https://ai.google.dev/gemini-api/docs/function-calling). + * `Model`s/`Content`s and `generate_content_request`s are mutually + * exclusive. You can either send `Model` + `Content`s or a + * `generate_content_request`, but never both. + * @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.ai.generativelanguage.v1.CountTokensResponse|CountTokensResponse}. + * 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/generative_service.count_tokens.js + * region_tag:generativelanguage_v1_generated_GenerativeService_CountTokens_async + */ countTokens( - request?: protos.google.ai.generativelanguage.v1.ICountTokensRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1.ICountTokensResponse, - protos.google.ai.generativelanguage.v1.ICountTokensRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1.ICountTokensRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1.ICountTokensResponse, + protos.google.ai.generativelanguage.v1.ICountTokensRequest | undefined, + {} | undefined, + ] + >; countTokens( - request: protos.google.ai.generativelanguage.v1.ICountTokensRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1.ICountTokensResponse, - protos.google.ai.generativelanguage.v1.ICountTokensRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1.ICountTokensRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1.ICountTokensResponse, + | protos.google.ai.generativelanguage.v1.ICountTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): void; countTokens( - request: protos.google.ai.generativelanguage.v1.ICountTokensRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1.ICountTokensResponse, - protos.google.ai.generativelanguage.v1.ICountTokensRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1.ICountTokensRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1.ICountTokensResponse, + | protos.google.ai.generativelanguage.v1.ICountTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): void; countTokens( - request?: protos.google.ai.generativelanguage.v1.ICountTokensRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1.ICountTokensRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1.ICountTokensResponse, - protos.google.ai.generativelanguage.v1.ICountTokensRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1.ICountTokensResponse, - protos.google.ai.generativelanguage.v1.ICountTokensRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1.ICountTokensResponse, - protos.google.ai.generativelanguage.v1.ICountTokensRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1.ICountTokensRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1.ICountTokensResponse, + | protos.google.ai.generativelanguage.v1.ICountTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1.ICountTokensResponse, + protos.google.ai.generativelanguage.v1.ICountTokensRequest | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('countTokens request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1.ICountTokensResponse, - protos.google.ai.generativelanguage.v1.ICountTokensRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1.ICountTokensResponse, + | protos.google.ai.generativelanguage.v1.ICountTokensRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('countTokens response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.countTokens(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1.ICountTokensResponse, - protos.google.ai.generativelanguage.v1.ICountTokensRequest|undefined, - {}|undefined - ]) => { - this._log.info('countTokens response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .countTokens(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1.ICountTokensResponse, + ( + | protos.google.ai.generativelanguage.v1.ICountTokensRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('countTokens response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Generates a [streamed - * response](https://ai.google.dev/gemini-api/docs/text-generation?lang=python#generate-a-text-stream) - * from the model given an input `GenerateContentRequest`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The name of the `Model` to use for generating the completion. - * - * Format: `models/{model}`. - * @param {number[]} request.contents - * Required. The content of the current conversation with the model. - * - * For single-turn queries, this is a single instance. For multi-turn queries - * like [chat](https://ai.google.dev/gemini-api/docs/text-generation#chat), - * this is a repeated field that contains the conversation history and the - * latest request. - * @param {number[]} [request.safetySettings] - * Optional. A list of unique `SafetySetting` instances for blocking unsafe - * content. - * - * This will be enforced on the `GenerateContentRequest.contents` and - * `GenerateContentResponse.candidates`. There should not be more than one - * setting for each `SafetyCategory` type. The API will block any contents and - * responses that fail to meet the thresholds set by these settings. This list - * overrides the default settings for each `SafetyCategory` specified in the - * safety_settings. If there is no `SafetySetting` for a given - * `SafetyCategory` provided in the list, the API will use the default safety - * setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH, - * HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, - * HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY are supported. - * Refer to the [guide](https://ai.google.dev/gemini-api/docs/safety-settings) - * for detailed information on available safety settings. Also refer to the - * [Safety guidance](https://ai.google.dev/gemini-api/docs/safety-guidance) to - * learn how to incorporate safety considerations in your AI applications. - * @param {google.ai.generativelanguage.v1.GenerationConfig} [request.generationConfig] - * Optional. Configuration options for model generation and outputs. - * @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.ai.generativelanguage.v1.GenerateContentResponse|GenerateContentResponse} 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/generative_service.stream_generate_content.js - * region_tag:generativelanguage_v1_generated_GenerativeService_StreamGenerateContent_async - */ + /** + * Generates a [streamed + * response](https://ai.google.dev/gemini-api/docs/text-generation?lang=python#generate-a-text-stream) + * from the model given an input `GenerateContentRequest`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The name of the `Model` to use for generating the completion. + * + * Format: `models/{model}`. + * @param {number[]} request.contents + * Required. The content of the current conversation with the model. + * + * For single-turn queries, this is a single instance. For multi-turn queries + * like [chat](https://ai.google.dev/gemini-api/docs/text-generation#chat), + * this is a repeated field that contains the conversation history and the + * latest request. + * @param {number[]} [request.safetySettings] + * Optional. A list of unique `SafetySetting` instances for blocking unsafe + * content. + * + * This will be enforced on the `GenerateContentRequest.contents` and + * `GenerateContentResponse.candidates`. There should not be more than one + * setting for each `SafetyCategory` type. The API will block any contents and + * responses that fail to meet the thresholds set by these settings. This list + * overrides the default settings for each `SafetyCategory` specified in the + * safety_settings. If there is no `SafetySetting` for a given + * `SafetyCategory` provided in the list, the API will use the default safety + * setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH, + * HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, + * HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY are supported. + * Refer to the [guide](https://ai.google.dev/gemini-api/docs/safety-settings) + * for detailed information on available safety settings. Also refer to the + * [Safety guidance](https://ai.google.dev/gemini-api/docs/safety-guidance) to + * learn how to incorporate safety considerations in your AI applications. + * @param {google.ai.generativelanguage.v1.GenerationConfig} [request.generationConfig] + * Optional. Configuration options for model generation and outputs. + * @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.ai.generativelanguage.v1.GenerateContentResponse|GenerateContentResponse} 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/generative_service.stream_generate_content.js + * region_tag:generativelanguage_v1_generated_GenerativeService_StreamGenerateContent_async + */ streamGenerateContent( - request?: protos.google.ai.generativelanguage.v1.IGenerateContentRequest, - options?: CallOptions): - gax.CancellableStream{ + request?: protos.google.ai.generativelanguage.v1.IGenerateContentRequest, + 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('streamGenerateContent stream %j', options); return this.innerApiCalls.streamGenerateContent(request, options); } @@ -880,7 +1121,7 @@ export class GenerativeServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -905,7 +1146,7 @@ export class GenerativeServiceClient { */ close(): Promise { if (this.generativeServiceStub && !this._terminated) { - return this.generativeServiceStub.then(stub => { + return this.generativeServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -913,4 +1154,4 @@ export class GenerativeServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1/index.ts b/packages/google-ai-generativelanguage/src/v1/index.ts index e356d366f860..d53f9026fcf0 100644 --- a/packages/google-ai-generativelanguage/src/v1/index.ts +++ b/packages/google-ai-generativelanguage/src/v1/index.ts @@ -16,5 +16,5 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {GenerativeServiceClient} from './generative_service_client'; -export {ModelServiceClient} from './model_service_client'; +export { GenerativeServiceClient } from './generative_service_client'; +export { ModelServiceClient } from './model_service_client'; diff --git a/packages/google-ai-generativelanguage/src/v1/model_service_client.ts b/packages/google-ai-generativelanguage/src/v1/model_service_client.ts index 272cd580c445..0ac0c79f1f3e 100644 --- a/packages/google-ai-generativelanguage/src/v1/model_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1/model_service_client.ts @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class ModelServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -57,9 +64,9 @@ export class ModelServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - modelServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + modelServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ModelServiceClient. @@ -100,21 +107,42 @@ export class ModelServiceClient { * const client = new ModelServiceClient({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 ModelServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -139,7 +167,7 @@ export class ModelServiceClient { 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; @@ -153,10 +181,7 @@ export class ModelServiceClient { } // 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 { @@ -177,23 +202,27 @@ export class ModelServiceClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' - ), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), }; // 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 = { - listModels: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'models') + listModels: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'models', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1.ModelService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1.ModelService', + 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 @@ -224,37 +253,40 @@ export class ModelServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1.ModelService. this.modelServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1.ModelService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1.ModelService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.ai.generativelanguage.v1.ModelService, - 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 modelServiceStubMethods = - ['getModel', 'listModels']; + const modelServiceStubMethods = ['getModel', 'listModels']; for (const methodName of modelServiceStubMethods) { const callPromise = this.modelServiceStub.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] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -269,8 +301,14 @@ export class ModelServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -281,8 +319,14 @@ export class ModelServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -322,8 +366,9 @@ export class ModelServiceClient { * 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; @@ -334,195 +379,261 @@ export class ModelServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets information about a specific `Model` such as its version number, token - * limits, - * [parameters](https://ai.google.dev/gemini-api/docs/models/generative-models#model-parameters) - * and other metadata. Refer to the [Gemini models - * guide](https://ai.google.dev/gemini-api/docs/models/gemini) for detailed - * model information. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the model. - * - * This name should match a model name returned by the `ListModels` method. - * - * Format: `models/{model}` - * @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.ai.generativelanguage.v1.Model|Model}. - * 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/model_service.get_model.js - * region_tag:generativelanguage_v1_generated_ModelService_GetModel_async - */ + /** + * Gets information about a specific `Model` such as its version number, token + * limits, + * [parameters](https://ai.google.dev/gemini-api/docs/models/generative-models#model-parameters) + * and other metadata. Refer to the [Gemini models + * guide](https://ai.google.dev/gemini-api/docs/models/gemini) for detailed + * model information. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the model. + * + * This name should match a model name returned by the `ListModels` method. + * + * Format: `models/{model}` + * @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.ai.generativelanguage.v1.Model|Model}. + * 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/model_service.get_model.js + * region_tag:generativelanguage_v1_generated_ModelService_GetModel_async + */ getModel( - request?: protos.google.ai.generativelanguage.v1.IGetModelRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1.IModel, - protos.google.ai.generativelanguage.v1.IGetModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1.IGetModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1.IModel, + protos.google.ai.generativelanguage.v1.IGetModelRequest | undefined, + {} | undefined, + ] + >; getModel( - request: protos.google.ai.generativelanguage.v1.IGetModelRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1.IModel, - protos.google.ai.generativelanguage.v1.IGetModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1.IGetModelRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1.IModel, + | protos.google.ai.generativelanguage.v1.IGetModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getModel( - request: protos.google.ai.generativelanguage.v1.IGetModelRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1.IModel, - protos.google.ai.generativelanguage.v1.IGetModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1.IGetModelRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1.IModel, + | protos.google.ai.generativelanguage.v1.IGetModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getModel( - request?: protos.google.ai.generativelanguage.v1.IGetModelRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1.IGetModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1.IModel, - protos.google.ai.generativelanguage.v1.IGetModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1.IModel, - protos.google.ai.generativelanguage.v1.IGetModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1.IModel, - protos.google.ai.generativelanguage.v1.IGetModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1.IGetModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1.IModel, + | protos.google.ai.generativelanguage.v1.IGetModelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1.IModel, + protos.google.ai.generativelanguage.v1.IGetModelRequest | 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('getModel request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1.IModel, - protos.google.ai.generativelanguage.v1.IGetModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1.IModel, + | protos.google.ai.generativelanguage.v1.IGetModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getModel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1.IModel, - protos.google.ai.generativelanguage.v1.IGetModelRequest|undefined, - {}|undefined - ]) => { - this._log.info('getModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1.IModel, + protos.google.ai.generativelanguage.v1.IGetModelRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists the [`Model`s](https://ai.google.dev/gemini-api/docs/models/gemini) - * available through the Gemini API. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of `Models` to return (per page). - * - * If unspecified, 50 models will be returned per page. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} request.pageToken - * A page token, received from a previous `ListModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListModels` must match - * the call that provided the page token. - * @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.ai.generativelanguage.v1.Model|Model}. - * 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 `listModelsAsync()` - * 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 [`Model`s](https://ai.google.dev/gemini-api/docs/models/gemini) + * available through the Gemini API. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of `Models` to return (per page). + * + * If unspecified, 50 models will be returned per page. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} request.pageToken + * A page token, received from a previous `ListModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListModels` must match + * the call that provided the page token. + * @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.ai.generativelanguage.v1.Model|Model}. + * 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 `listModelsAsync()` + * 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. + */ listModels( - request?: protos.google.ai.generativelanguage.v1.IListModelsRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1.IModel[], - protos.google.ai.generativelanguage.v1.IListModelsRequest|null, - protos.google.ai.generativelanguage.v1.IListModelsResponse - ]>; + request?: protos.google.ai.generativelanguage.v1.IListModelsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1.IModel[], + protos.google.ai.generativelanguage.v1.IListModelsRequest | null, + protos.google.ai.generativelanguage.v1.IListModelsResponse, + ] + >; listModels( - request: protos.google.ai.generativelanguage.v1.IListModelsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1.IListModelsRequest, - protos.google.ai.generativelanguage.v1.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1.IModel>): void; + request: protos.google.ai.generativelanguage.v1.IListModelsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1.IListModelsRequest, + | protos.google.ai.generativelanguage.v1.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1.IModel + >, + ): void; listModels( - request: protos.google.ai.generativelanguage.v1.IListModelsRequest, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1.IListModelsRequest, - protos.google.ai.generativelanguage.v1.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1.IModel>): void; + request: protos.google.ai.generativelanguage.v1.IListModelsRequest, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1.IListModelsRequest, + | protos.google.ai.generativelanguage.v1.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1.IModel + >, + ): void; listModels( - request?: protos.google.ai.generativelanguage.v1.IListModelsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.ai.generativelanguage.v1.IListModelsRequest, - protos.google.ai.generativelanguage.v1.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1.IModel>, - callback?: PaginationCallback< + request?: protos.google.ai.generativelanguage.v1.IListModelsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ai.generativelanguage.v1.IListModelsRequest, - protos.google.ai.generativelanguage.v1.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1.IModel>): - Promise<[ - protos.google.ai.generativelanguage.v1.IModel[], - protos.google.ai.generativelanguage.v1.IListModelsRequest|null, - protos.google.ai.generativelanguage.v1.IListModelsResponse - ]>|void { + | protos.google.ai.generativelanguage.v1.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1.IModel + >, + callback?: PaginationCallback< + protos.google.ai.generativelanguage.v1.IListModelsRequest, + | protos.google.ai.generativelanguage.v1.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1.IModel + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1.IModel[], + protos.google.ai.generativelanguage.v1.IListModelsRequest | null, + protos.google.ai.generativelanguage.v1.IListModelsResponse, + ] + > | 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 || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.ai.generativelanguage.v1.IListModelsRequest, - protos.google.ai.generativelanguage.v1.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1.IModel>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.ai.generativelanguage.v1.IListModelsRequest, + | protos.google.ai.generativelanguage.v1.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1.IModel + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listModels values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -531,112 +642,118 @@ export class ModelServiceClient { this._log.info('listModels request %j', request); return this.innerApiCalls .listModels(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ai.generativelanguage.v1.IModel[], - protos.google.ai.generativelanguage.v1.IListModelsRequest|null, - protos.google.ai.generativelanguage.v1.IListModelsResponse - ]) => { - this._log.info('listModels values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ai.generativelanguage.v1.IModel[], + protos.google.ai.generativelanguage.v1.IListModelsRequest | null, + protos.google.ai.generativelanguage.v1.IListModelsResponse, + ]) => { + this._log.info('listModels values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listModels`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of `Models` to return (per page). - * - * If unspecified, 50 models will be returned per page. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} request.pageToken - * A page token, received from a previous `ListModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListModels` must match - * the call that provided the page token. - * @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.ai.generativelanguage.v1.Model|Model} 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 `listModelsAsync()` - * 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 `listModels`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of `Models` to return (per page). + * + * If unspecified, 50 models will be returned per page. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} request.pageToken + * A page token, received from a previous `ListModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListModels` must match + * the call that provided the page token. + * @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.ai.generativelanguage.v1.Model|Model} 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 `listModelsAsync()` + * 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. + */ listModelsStream( - request?: protos.google.ai.generativelanguage.v1.IListModelsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ai.generativelanguage.v1.IListModelsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listModels stream %j', request); return this.descriptors.page.listModels.createStream( this.innerApiCalls.listModels as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listModels`, 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 {number} request.pageSize - * The maximum number of `Models` to return (per page). - * - * If unspecified, 50 models will be returned per page. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} request.pageToken - * A page token, received from a previous `ListModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListModels` must match - * the call that provided the 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 protos.google.ai.generativelanguage.v1.Model|Model}. 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 include:samples/generated/v1/model_service.list_models.js - * region_tag:generativelanguage_v1_generated_ModelService_ListModels_async - */ + /** + * Equivalent to `listModels`, 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 {number} request.pageSize + * The maximum number of `Models` to return (per page). + * + * If unspecified, 50 models will be returned per page. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} request.pageToken + * A page token, received from a previous `ListModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListModels` must match + * the call that provided the 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 protos.google.ai.generativelanguage.v1.Model|Model}. 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 include:samples/generated/v1/model_service.list_models.js + * region_tag:generativelanguage_v1_generated_ModelService_ListModels_async + */ listModelsAsync( - request?: protos.google.ai.generativelanguage.v1.IListModelsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ai.generativelanguage.v1.IListModelsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listModels iterate %j', request); return this.descriptors.page.listModels.asyncIterate( this.innerApiCalls['listModels'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -649,7 +766,7 @@ export class ModelServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -674,7 +791,7 @@ export class ModelServiceClient { */ close(): Promise { if (this.modelServiceStub && !this._terminated) { - return this.modelServiceStub.then(stub => { + return this.modelServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -682,4 +799,4 @@ export class ModelServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1alpha/cache_service_client.ts b/packages/google-ai-generativelanguage/src/v1alpha/cache_service_client.ts index 9ec5d019bb2e..3e15087f38f0 100644 --- a/packages/google-ai-generativelanguage/src/v1alpha/cache_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1alpha/cache_service_client.ts @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +54,7 @@ export class CacheServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -60,9 +67,9 @@ export class CacheServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - cacheServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + cacheServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of CacheServiceClient. @@ -103,21 +110,42 @@ export class CacheServiceClient { * const client = new CacheServiceClient({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 CacheServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -142,7 +170,7 @@ export class CacheServiceClient { 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; @@ -156,10 +184,7 @@ export class CacheServiceClient { } // 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 { @@ -181,31 +206,25 @@ export class CacheServiceClient { // Create useful helper objects for these. this.pathTemplates = { cachedContentPathTemplate: new this._gaxModule.PathTemplate( - 'cachedContents/{id}' + 'cachedContents/{id}', ), chunkPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}/chunks/{chunk}' - ), - corpusPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}' + 'corpora/{corpus}/documents/{document}/chunks/{chunk}', ), + corpusPathTemplate: new this._gaxModule.PathTemplate('corpora/{corpus}'), corpusPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/permissions/{permission}' + 'corpora/{corpus}/permissions/{permission}', ), documentPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}' - ), - filePathTemplate: new this._gaxModule.PathTemplate( - 'files/{file}' - ), - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' + 'corpora/{corpus}/documents/{document}', ), + filePathTemplate: new this._gaxModule.PathTemplate('files/{file}'), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), tunedModelPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}' + 'tunedModels/{tuned_model}', ), tunedModelPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}/permissions/{permission}' + 'tunedModels/{tuned_model}/permissions/{permission}', ), }; @@ -213,14 +232,20 @@ export class CacheServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listCachedContents: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'cachedContents') + listCachedContents: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'cachedContents', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1alpha.CacheService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1alpha.CacheService', + 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 @@ -251,37 +276,47 @@ export class CacheServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1alpha.CacheService. this.cacheServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1alpha.CacheService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1alpha.CacheService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1alpha.CacheService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1alpha + .CacheService, + 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 cacheServiceStubMethods = - ['listCachedContents', 'createCachedContent', 'getCachedContent', 'updateCachedContent', 'deleteCachedContent']; + const cacheServiceStubMethods = [ + 'listCachedContents', + 'createCachedContent', + 'getCachedContent', + 'updateCachedContent', + 'deleteCachedContent', + ]; for (const methodName of cacheServiceStubMethods) { const callPromise = this.cacheServiceStub.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] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -296,8 +331,14 @@ export class CacheServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -308,8 +349,14 @@ export class CacheServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -349,8 +396,9 @@ export class CacheServiceClient { * 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; @@ -361,463 +409,686 @@ export class CacheServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates CachedContent resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ai.generativelanguage.v1alpha.CachedContent} request.cachedContent - * Required. The cached content 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.ai.generativelanguage.v1alpha.CachedContent|CachedContent}. - * 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/v1alpha/cache_service.create_cached_content.js - * region_tag:generativelanguage_v1alpha_generated_CacheService_CreateCachedContent_async - */ + /** + * Creates CachedContent resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ai.generativelanguage.v1alpha.CachedContent} request.cachedContent + * Required. The cached content 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.ai.generativelanguage.v1alpha.CachedContent|CachedContent}. + * 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/v1alpha/cache_service.create_cached_content.js + * region_tag:generativelanguage_v1alpha_generated_CacheService_CreateCachedContent_async + */ createCachedContent( - request?: protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICachedContent, + ( + | protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest + | undefined + ), + {} | undefined, + ] + >; createCachedContent( - request: protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ICachedContent, + | protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createCachedContent( - request: protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ICachedContent, + | protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createCachedContent( - request?: protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.ICachedContent, + | protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICachedContent, + ( + | protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest + | 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 || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createCachedContent request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.ICachedContent, + | protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createCachedContent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createCachedContent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest|undefined, - {}|undefined - ]) => { - this._log.info('createCachedContent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createCachedContent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.ICachedContent, + ( + | protos.google.ai.generativelanguage.v1alpha.ICreateCachedContentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createCachedContent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Reads CachedContent resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name referring to the content cache entry. - * Format: `cachedContents/{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.ai.generativelanguage.v1alpha.CachedContent|CachedContent}. - * 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/v1alpha/cache_service.get_cached_content.js - * region_tag:generativelanguage_v1alpha_generated_CacheService_GetCachedContent_async - */ + /** + * Reads CachedContent resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name referring to the content cache entry. + * Format: `cachedContents/{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.ai.generativelanguage.v1alpha.CachedContent|CachedContent}. + * 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/v1alpha/cache_service.get_cached_content.js + * region_tag:generativelanguage_v1alpha_generated_CacheService_GetCachedContent_async + */ getCachedContent( - request?: protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICachedContent, + ( + | protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest + | undefined + ), + {} | undefined, + ] + >; getCachedContent( - request: protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ICachedContent, + | protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getCachedContent( - request: protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ICachedContent, + | protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getCachedContent( - request?: protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.ICachedContent, + | protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICachedContent, + ( + | protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest + | 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('getCachedContent request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.ICachedContent, + | protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getCachedContent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getCachedContent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest|undefined, - {}|undefined - ]) => { - this._log.info('getCachedContent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getCachedContent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.ICachedContent, + ( + | protos.google.ai.generativelanguage.v1alpha.IGetCachedContentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getCachedContent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates CachedContent resource (only expiration is updatable). - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ai.generativelanguage.v1alpha.CachedContent} request.cachedContent - * Required. The content cache entry to update - * @param {google.protobuf.FieldMask} request.updateMask - * The list of fields to update. - * @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.ai.generativelanguage.v1alpha.CachedContent|CachedContent}. - * 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/v1alpha/cache_service.update_cached_content.js - * region_tag:generativelanguage_v1alpha_generated_CacheService_UpdateCachedContent_async - */ + /** + * Updates CachedContent resource (only expiration is updatable). + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ai.generativelanguage.v1alpha.CachedContent} request.cachedContent + * Required. The content cache entry to update + * @param {google.protobuf.FieldMask} request.updateMask + * The list of fields to update. + * @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.ai.generativelanguage.v1alpha.CachedContent|CachedContent}. + * 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/v1alpha/cache_service.update_cached_content.js + * region_tag:generativelanguage_v1alpha_generated_CacheService_UpdateCachedContent_async + */ updateCachedContent( - request?: protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICachedContent, + ( + | protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest + | undefined + ), + {} | undefined, + ] + >; updateCachedContent( - request: protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ICachedContent, + | protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCachedContent( - request: protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ICachedContent, + | protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCachedContent( - request?: protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.ICachedContent, + | protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICachedContent, + ( + | protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest + | 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({ - 'cached_content.name': request.cachedContent!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'cached_content.name': request.cachedContent!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateCachedContent request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.ICachedContent, + | protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateCachedContent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateCachedContent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.ICachedContent, - protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateCachedContent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateCachedContent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.ICachedContent, + ( + | protos.google.ai.generativelanguage.v1alpha.IUpdateCachedContentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateCachedContent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes CachedContent resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name referring to the content cache entry - * Format: `cachedContents/{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 include:samples/generated/v1alpha/cache_service.delete_cached_content.js - * region_tag:generativelanguage_v1alpha_generated_CacheService_DeleteCachedContent_async - */ + /** + * Deletes CachedContent resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name referring to the content cache entry + * Format: `cachedContents/{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 include:samples/generated/v1alpha/cache_service.delete_cached_content.js + * region_tag:generativelanguage_v1alpha_generated_CacheService_DeleteCachedContent_async + */ deleteCachedContent( - request?: protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest + | undefined + ), + {} | undefined, + ] + >; deleteCachedContent( - request: protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteCachedContent( - request: protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteCachedContent( - request?: protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest + | 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('deleteCachedContent request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteCachedContent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteCachedContent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteCachedContent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteCachedContent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.IDeleteCachedContentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteCachedContent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists CachedContents. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of cached contents to return. The service may - * return fewer than this value. If unspecified, some default (under maximum) - * number of items will be returned. The maximum value is 1000; values above - * 1000 will be coerced to 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListCachedContents` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListCachedContents` must - * match the call that provided the page token. - * @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.ai.generativelanguage.v1alpha.CachedContent|CachedContent}. - * 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 `listCachedContentsAsync()` - * 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 CachedContents. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of cached contents to return. The service may + * return fewer than this value. If unspecified, some default (under maximum) + * number of items will be returned. The maximum value is 1000; values above + * 1000 will be coerced to 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListCachedContents` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListCachedContents` must + * match the call that provided the page token. + * @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.ai.generativelanguage.v1alpha.CachedContent|CachedContent}. + * 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 `listCachedContentsAsync()` + * 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. + */ listCachedContents( - request?: protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICachedContent[], - protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListCachedContentsResponse - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICachedContent[], + protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest | null, + protos.google.ai.generativelanguage.v1alpha.IListCachedContentsResponse, + ] + >; listCachedContents( - request: protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest, - protos.google.ai.generativelanguage.v1alpha.IListCachedContentsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.ICachedContent>): void; + request: protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest, + | protos.google.ai.generativelanguage.v1alpha.IListCachedContentsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.ICachedContent + >, + ): void; listCachedContents( - request: protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest, - protos.google.ai.generativelanguage.v1alpha.IListCachedContentsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.ICachedContent>): void; + request: protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest, + | protos.google.ai.generativelanguage.v1alpha.IListCachedContentsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.ICachedContent + >, + ): void; listCachedContents( - request?: protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest, - protos.google.ai.generativelanguage.v1alpha.IListCachedContentsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.ICachedContent>, - callback?: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest, - protos.google.ai.generativelanguage.v1alpha.IListCachedContentsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.ICachedContent>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICachedContent[], - protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListCachedContentsResponse - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IListCachedContentsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.ICachedContent + >, + callback?: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest, + | protos.google.ai.generativelanguage.v1alpha.IListCachedContentsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.ICachedContent + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICachedContent[], + protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest | null, + protos.google.ai.generativelanguage.v1alpha.IListCachedContentsResponse, + ] + > | 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 || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest, - protos.google.ai.generativelanguage.v1alpha.IListCachedContentsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.ICachedContent>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest, + | protos.google.ai.generativelanguage.v1alpha.IListCachedContentsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.ICachedContent + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listCachedContents values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -826,106 +1097,112 @@ export class CacheServiceClient { this._log.info('listCachedContents request %j', request); return this.innerApiCalls .listCachedContents(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ai.generativelanguage.v1alpha.ICachedContent[], - protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListCachedContentsResponse - ]) => { - this._log.info('listCachedContents values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ai.generativelanguage.v1alpha.ICachedContent[], + protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest | null, + protos.google.ai.generativelanguage.v1alpha.IListCachedContentsResponse, + ]) => { + this._log.info('listCachedContents values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listCachedContents`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of cached contents to return. The service may - * return fewer than this value. If unspecified, some default (under maximum) - * number of items will be returned. The maximum value is 1000; values above - * 1000 will be coerced to 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListCachedContents` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListCachedContents` must - * match the call that provided the page token. - * @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.ai.generativelanguage.v1alpha.CachedContent|CachedContent} 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 `listCachedContentsAsync()` - * 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 `listCachedContents`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of cached contents to return. The service may + * return fewer than this value. If unspecified, some default (under maximum) + * number of items will be returned. The maximum value is 1000; values above + * 1000 will be coerced to 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListCachedContents` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListCachedContents` must + * match the call that provided the page token. + * @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.ai.generativelanguage.v1alpha.CachedContent|CachedContent} 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 `listCachedContentsAsync()` + * 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. + */ listCachedContentsStream( - request?: protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listCachedContents']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCachedContents stream %j', request); return this.descriptors.page.listCachedContents.createStream( this.innerApiCalls.listCachedContents as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listCachedContents`, 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 {number} [request.pageSize] - * Optional. The maximum number of cached contents to return. The service may - * return fewer than this value. If unspecified, some default (under maximum) - * number of items will be returned. The maximum value is 1000; values above - * 1000 will be coerced to 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListCachedContents` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListCachedContents` must - * match the call that provided the 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 protos.google.ai.generativelanguage.v1alpha.CachedContent|CachedContent}. 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 include:samples/generated/v1alpha/cache_service.list_cached_contents.js - * region_tag:generativelanguage_v1alpha_generated_CacheService_ListCachedContents_async - */ + /** + * Equivalent to `listCachedContents`, 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 {number} [request.pageSize] + * Optional. The maximum number of cached contents to return. The service may + * return fewer than this value. If unspecified, some default (under maximum) + * number of items will be returned. The maximum value is 1000; values above + * 1000 will be coerced to 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListCachedContents` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListCachedContents` must + * match the call that provided the 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 protos.google.ai.generativelanguage.v1alpha.CachedContent|CachedContent}. 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 include:samples/generated/v1alpha/cache_service.list_cached_contents.js + * region_tag:generativelanguage_v1alpha_generated_CacheService_ListCachedContents_async + */ listCachedContentsAsync( - request?: protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ai.generativelanguage.v1alpha.IListCachedContentsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listCachedContents']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCachedContents iterate %j', request); return this.descriptors.page.listCachedContents.asyncIterate( this.innerApiCalls['listCachedContents'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -938,7 +1215,7 @@ export class CacheServiceClient { * @param {string} id * @returns {string} Resource name string. */ - cachedContentPath(id:string) { + cachedContentPath(id: string) { return this.pathTemplates.cachedContentPathTemplate.render({ id: id, }); @@ -952,7 +1229,8 @@ export class CacheServiceClient { * @returns {string} A string representing the id. */ matchIdFromCachedContentName(cachedContentName: string) { - return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName).id; + return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName) + .id; } /** @@ -963,7 +1241,7 @@ export class CacheServiceClient { * @param {string} chunk * @returns {string} Resource name string. */ - chunkPath(corpus:string,document:string,chunk:string) { + chunkPath(corpus: string, document: string, chunk: string) { return this.pathTemplates.chunkPathTemplate.render({ corpus: corpus, document: document, @@ -1010,7 +1288,7 @@ export class CacheServiceClient { * @param {string} corpus * @returns {string} Resource name string. */ - corpusPath(corpus:string) { + corpusPath(corpus: string) { return this.pathTemplates.corpusPathTemplate.render({ corpus: corpus, }); @@ -1034,7 +1312,7 @@ export class CacheServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - corpusPermissionsPath(corpus:string,permission:string) { + corpusPermissionsPath(corpus: string, permission: string) { return this.pathTemplates.corpusPermissionsPathTemplate.render({ corpus: corpus, permission: permission, @@ -1049,7 +1327,9 @@ export class CacheServiceClient { * @returns {string} A string representing the corpus. */ matchCorpusFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).corpus; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).corpus; } /** @@ -1060,7 +1340,9 @@ export class CacheServiceClient { * @returns {string} A string representing the permission. */ matchPermissionFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).permission; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).permission; } /** @@ -1070,7 +1352,7 @@ export class CacheServiceClient { * @param {string} document * @returns {string} Resource name string. */ - documentPath(corpus:string,document:string) { + documentPath(corpus: string, document: string) { return this.pathTemplates.documentPathTemplate.render({ corpus: corpus, document: document, @@ -1105,7 +1387,7 @@ export class CacheServiceClient { * @param {string} file * @returns {string} Resource name string. */ - filePath(file:string) { + filePath(file: string) { return this.pathTemplates.filePathTemplate.render({ file: file, }); @@ -1128,7 +1410,7 @@ export class CacheServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -1151,7 +1433,7 @@ export class CacheServiceClient { * @param {string} tuned_model * @returns {string} Resource name string. */ - tunedModelPath(tunedModel:string) { + tunedModelPath(tunedModel: string) { return this.pathTemplates.tunedModelPathTemplate.render({ tuned_model: tunedModel, }); @@ -1165,7 +1447,8 @@ export class CacheServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromTunedModelName(tunedModelName: string) { - return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName).tuned_model; + return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName) + .tuned_model; } /** @@ -1175,7 +1458,7 @@ export class CacheServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - tunedModelPermissionsPath(tunedModel:string,permission:string) { + tunedModelPermissionsPath(tunedModel: string, permission: string) { return this.pathTemplates.tunedModelPermissionsPathTemplate.render({ tuned_model: tunedModel, permission: permission, @@ -1189,8 +1472,12 @@ export class CacheServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the tuned_model. */ - matchTunedModelFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).tuned_model; + matchTunedModelFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).tuned_model; } /** @@ -1200,8 +1487,12 @@ export class CacheServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the permission. */ - matchPermissionFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).permission; + matchPermissionFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).permission; } /** @@ -1212,7 +1503,7 @@ export class CacheServiceClient { */ close(): Promise { if (this.cacheServiceStub && !this._terminated) { - return this.cacheServiceStub.then(stub => { + return this.cacheServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1220,4 +1511,4 @@ export class CacheServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1alpha/discuss_service_client.ts b/packages/google-ai-generativelanguage/src/v1alpha/discuss_service_client.ts index 96afce50dda1..4ce57e354456 100644 --- a/packages/google-ai-generativelanguage/src/v1alpha/discuss_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1alpha/discuss_service_client.ts @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +52,7 @@ export class DiscussServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -60,9 +65,9 @@ export class DiscussServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - discussServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + discussServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of DiscussServiceClient. @@ -103,21 +108,42 @@ export class DiscussServiceClient { * const client = new DiscussServiceClient({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 DiscussServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -142,7 +168,7 @@ export class DiscussServiceClient { 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; @@ -156,10 +182,7 @@ export class DiscussServiceClient { } // 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 { @@ -181,38 +204,35 @@ export class DiscussServiceClient { // Create useful helper objects for these. this.pathTemplates = { cachedContentPathTemplate: new this._gaxModule.PathTemplate( - 'cachedContents/{id}' + 'cachedContents/{id}', ), chunkPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}/chunks/{chunk}' - ), - corpusPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}' + 'corpora/{corpus}/documents/{document}/chunks/{chunk}', ), + corpusPathTemplate: new this._gaxModule.PathTemplate('corpora/{corpus}'), corpusPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/permissions/{permission}' + 'corpora/{corpus}/permissions/{permission}', ), documentPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}' - ), - filePathTemplate: new this._gaxModule.PathTemplate( - 'files/{file}' - ), - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' + 'corpora/{corpus}/documents/{document}', ), + filePathTemplate: new this._gaxModule.PathTemplate('files/{file}'), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), tunedModelPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}' + 'tunedModels/{tuned_model}', ), tunedModelPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}/permissions/{permission}' + 'tunedModels/{tuned_model}/permissions/{permission}', ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1alpha.DiscussService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1alpha.DiscussService', + 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 @@ -243,36 +263,41 @@ export class DiscussServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1alpha.DiscussService. this.discussServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1alpha.DiscussService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1alpha.DiscussService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1alpha.DiscussService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1alpha + .DiscussService, + 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 discussServiceStubMethods = - ['generateMessage', 'countMessageTokens']; + const discussServiceStubMethods = ['generateMessage', 'countMessageTokens']; for (const methodName of discussServiceStubMethods) { const callPromise = this.discussServiceStub.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 = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -287,8 +312,14 @@ export class DiscussServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -299,8 +330,14 @@ export class DiscussServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -340,8 +377,9 @@ export class DiscussServiceClient { * 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; @@ -352,231 +390,329 @@ export class DiscussServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Generates a response from the model given an input `MessagePrompt`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The name of the model to use. - * - * Format: `name=models/{model}`. - * @param {google.ai.generativelanguage.v1alpha.MessagePrompt} request.prompt - * Required. The structured textual input given to the model as a prompt. - * - * Given a - * prompt, the model will return what it predicts is the next message in the - * discussion. - * @param {number} [request.temperature] - * Optional. Controls the randomness of the output. - * - * Values can range over `[0.0,1.0]`, - * inclusive. A value closer to `1.0` will produce responses that are more - * varied, while a value closer to `0.0` will typically result in - * less surprising responses from the model. - * @param {number} [request.candidateCount] - * Optional. The number of generated response messages to return. - * - * This value must be between - * `[1, 8]`, inclusive. If unset, this will default to `1`. - * @param {number} [request.topP] - * Optional. The maximum cumulative probability of tokens to consider when - * sampling. - * - * The model uses combined Top-k and nucleus sampling. - * - * Nucleus sampling considers the smallest set of tokens whose probability - * sum is at least `top_p`. - * @param {number} [request.topK] - * Optional. The maximum number of tokens to consider when sampling. - * - * The model uses combined Top-k and nucleus sampling. - * - * Top-k sampling considers the set of `top_k` most probable tokens. - * @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.ai.generativelanguage.v1alpha.GenerateMessageResponse|GenerateMessageResponse}. - * 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/v1alpha/discuss_service.generate_message.js - * region_tag:generativelanguage_v1alpha_generated_DiscussService_GenerateMessage_async - */ + /** + * Generates a response from the model given an input `MessagePrompt`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The name of the model to use. + * + * Format: `name=models/{model}`. + * @param {google.ai.generativelanguage.v1alpha.MessagePrompt} request.prompt + * Required. The structured textual input given to the model as a prompt. + * + * Given a + * prompt, the model will return what it predicts is the next message in the + * discussion. + * @param {number} [request.temperature] + * Optional. Controls the randomness of the output. + * + * Values can range over `[0.0,1.0]`, + * inclusive. A value closer to `1.0` will produce responses that are more + * varied, while a value closer to `0.0` will typically result in + * less surprising responses from the model. + * @param {number} [request.candidateCount] + * Optional. The number of generated response messages to return. + * + * This value must be between + * `[1, 8]`, inclusive. If unset, this will default to `1`. + * @param {number} [request.topP] + * Optional. The maximum cumulative probability of tokens to consider when + * sampling. + * + * The model uses combined Top-k and nucleus sampling. + * + * Nucleus sampling considers the smallest set of tokens whose probability + * sum is at least `top_p`. + * @param {number} [request.topK] + * Optional. The maximum number of tokens to consider when sampling. + * + * The model uses combined Top-k and nucleus sampling. + * + * Top-k sampling considers the set of `top_k` most probable tokens. + * @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.ai.generativelanguage.v1alpha.GenerateMessageResponse|GenerateMessageResponse}. + * 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/v1alpha/discuss_service.generate_message.js + * region_tag:generativelanguage_v1alpha_generated_DiscussService_GenerateMessage_async + */ generateMessage( - request?: protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IGenerateMessageResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest + | undefined + ), + {} | undefined, + ] + >; generateMessage( - request: protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IGenerateMessageResponse, + | protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateMessage( - request: protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IGenerateMessageResponse, + | protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateMessage( - request?: protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IGenerateMessageResponse, + | protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IGenerateMessageResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('generateMessage request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IGenerateMessageResponse, + | protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('generateMessage response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.generateMessage(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest|undefined, - {}|undefined - ]) => { - this._log.info('generateMessage response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .generateMessage(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IGenerateMessageResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IGenerateMessageRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('generateMessage response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Runs a model's tokenizer on a string and returns the token count. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The model's resource name. This serves as an ID for the Model to - * use. - * - * This name should match a model name returned by the `ListModels` method. - * - * Format: `models/{model}` - * @param {google.ai.generativelanguage.v1alpha.MessagePrompt} request.prompt - * Required. The prompt, whose token count is to 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 {@link protos.google.ai.generativelanguage.v1alpha.CountMessageTokensResponse|CountMessageTokensResponse}. - * 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/v1alpha/discuss_service.count_message_tokens.js - * region_tag:generativelanguage_v1alpha_generated_DiscussService_CountMessageTokens_async - */ + /** + * Runs a model's tokenizer on a string and returns the token count. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The model's resource name. This serves as an ID for the Model to + * use. + * + * This name should match a model name returned by the `ListModels` method. + * + * Format: `models/{model}` + * @param {google.ai.generativelanguage.v1alpha.MessagePrompt} request.prompt + * Required. The prompt, whose token count is to 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 {@link protos.google.ai.generativelanguage.v1alpha.CountMessageTokensResponse|CountMessageTokensResponse}. + * 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/v1alpha/discuss_service.count_message_tokens.js + * region_tag:generativelanguage_v1alpha_generated_DiscussService_CountMessageTokens_async + */ countMessageTokens( - request?: protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest + | undefined + ), + {} | undefined, + ] + >; countMessageTokens( - request: protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensResponse, + | protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): void; countMessageTokens( - request: protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensResponse, + | protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): void; countMessageTokens( - request?: protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensResponse, + | protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('countMessageTokens request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensResponse, + | protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('countMessageTokens response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.countMessageTokens(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest|undefined, - {}|undefined - ]) => { - this._log.info('countMessageTokens response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .countMessageTokens(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('countMessageTokens response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -592,7 +728,7 @@ export class DiscussServiceClient { * @param {string} id * @returns {string} Resource name string. */ - cachedContentPath(id:string) { + cachedContentPath(id: string) { return this.pathTemplates.cachedContentPathTemplate.render({ id: id, }); @@ -606,7 +742,8 @@ export class DiscussServiceClient { * @returns {string} A string representing the id. */ matchIdFromCachedContentName(cachedContentName: string) { - return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName).id; + return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName) + .id; } /** @@ -617,7 +754,7 @@ export class DiscussServiceClient { * @param {string} chunk * @returns {string} Resource name string. */ - chunkPath(corpus:string,document:string,chunk:string) { + chunkPath(corpus: string, document: string, chunk: string) { return this.pathTemplates.chunkPathTemplate.render({ corpus: corpus, document: document, @@ -664,7 +801,7 @@ export class DiscussServiceClient { * @param {string} corpus * @returns {string} Resource name string. */ - corpusPath(corpus:string) { + corpusPath(corpus: string) { return this.pathTemplates.corpusPathTemplate.render({ corpus: corpus, }); @@ -688,7 +825,7 @@ export class DiscussServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - corpusPermissionsPath(corpus:string,permission:string) { + corpusPermissionsPath(corpus: string, permission: string) { return this.pathTemplates.corpusPermissionsPathTemplate.render({ corpus: corpus, permission: permission, @@ -703,7 +840,9 @@ export class DiscussServiceClient { * @returns {string} A string representing the corpus. */ matchCorpusFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).corpus; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).corpus; } /** @@ -714,7 +853,9 @@ export class DiscussServiceClient { * @returns {string} A string representing the permission. */ matchPermissionFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).permission; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).permission; } /** @@ -724,7 +865,7 @@ export class DiscussServiceClient { * @param {string} document * @returns {string} Resource name string. */ - documentPath(corpus:string,document:string) { + documentPath(corpus: string, document: string) { return this.pathTemplates.documentPathTemplate.render({ corpus: corpus, document: document, @@ -759,7 +900,7 @@ export class DiscussServiceClient { * @param {string} file * @returns {string} Resource name string. */ - filePath(file:string) { + filePath(file: string) { return this.pathTemplates.filePathTemplate.render({ file: file, }); @@ -782,7 +923,7 @@ export class DiscussServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -805,7 +946,7 @@ export class DiscussServiceClient { * @param {string} tuned_model * @returns {string} Resource name string. */ - tunedModelPath(tunedModel:string) { + tunedModelPath(tunedModel: string) { return this.pathTemplates.tunedModelPathTemplate.render({ tuned_model: tunedModel, }); @@ -819,7 +960,8 @@ export class DiscussServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromTunedModelName(tunedModelName: string) { - return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName).tuned_model; + return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName) + .tuned_model; } /** @@ -829,7 +971,7 @@ export class DiscussServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - tunedModelPermissionsPath(tunedModel:string,permission:string) { + tunedModelPermissionsPath(tunedModel: string, permission: string) { return this.pathTemplates.tunedModelPermissionsPathTemplate.render({ tuned_model: tunedModel, permission: permission, @@ -843,8 +985,12 @@ export class DiscussServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the tuned_model. */ - matchTunedModelFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).tuned_model; + matchTunedModelFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).tuned_model; } /** @@ -854,8 +1000,12 @@ export class DiscussServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the permission. */ - matchPermissionFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).permission; + matchPermissionFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).permission; } /** @@ -866,7 +1016,7 @@ export class DiscussServiceClient { */ close(): Promise { if (this.discussServiceStub && !this._terminated) { - return this.discussServiceStub.then(stub => { + return this.discussServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -874,4 +1024,4 @@ export class DiscussServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1alpha/file_service_client.ts b/packages/google-ai-generativelanguage/src/v1alpha/file_service_client.ts index 8a4a2c7ec1b2..2c8f71dbb9b1 100644 --- a/packages/google-ai-generativelanguage/src/v1alpha/file_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1alpha/file_service_client.ts @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class FileServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -57,9 +64,9 @@ export class FileServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - fileServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + fileServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of FileServiceClient. @@ -100,21 +107,42 @@ export class FileServiceClient { * const client = new FileServiceClient({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 FileServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -139,7 +167,7 @@ export class FileServiceClient { 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; @@ -153,10 +181,7 @@ export class FileServiceClient { } // 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 { @@ -178,31 +203,25 @@ export class FileServiceClient { // Create useful helper objects for these. this.pathTemplates = { cachedContentPathTemplate: new this._gaxModule.PathTemplate( - 'cachedContents/{id}' + 'cachedContents/{id}', ), chunkPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}/chunks/{chunk}' - ), - corpusPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}' + 'corpora/{corpus}/documents/{document}/chunks/{chunk}', ), + corpusPathTemplate: new this._gaxModule.PathTemplate('corpora/{corpus}'), corpusPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/permissions/{permission}' + 'corpora/{corpus}/permissions/{permission}', ), documentPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}' - ), - filePathTemplate: new this._gaxModule.PathTemplate( - 'files/{file}' - ), - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' + 'corpora/{corpus}/documents/{document}', ), + filePathTemplate: new this._gaxModule.PathTemplate('files/{file}'), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), tunedModelPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}' + 'tunedModels/{tuned_model}', ), tunedModelPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}/permissions/{permission}' + 'tunedModels/{tuned_model}/permissions/{permission}', ), }; @@ -210,14 +229,20 @@ export class FileServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listFiles: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'files') + listFiles: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'files', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1alpha.FileService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1alpha.FileService', + 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 @@ -248,37 +273,46 @@ export class FileServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1alpha.FileService. this.fileServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1alpha.FileService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1alpha.FileService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1alpha.FileService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1alpha + .FileService, + 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 fileServiceStubMethods = - ['createFile', 'listFiles', 'getFile', 'deleteFile']; + const fileServiceStubMethods = [ + 'createFile', + 'listFiles', + 'getFile', + 'deleteFile', + ]; for (const methodName of fileServiceStubMethods) { const callPromise = this.fileServiceStub.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] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -293,8 +327,14 @@ export class FileServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -305,8 +345,14 @@ export class FileServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -346,8 +392,9 @@ export class FileServiceClient { * 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; @@ -358,361 +405,529 @@ export class FileServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a `File`. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ai.generativelanguage.v1alpha.File} [request.file] - * Optional. Metadata for the file 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.ai.generativelanguage.v1alpha.CreateFileResponse|CreateFileResponse}. - * 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/v1alpha/file_service.create_file.js - * region_tag:generativelanguage_v1alpha_generated_FileService_CreateFile_async - */ + /** + * Creates a `File`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ai.generativelanguage.v1alpha.File} [request.file] + * Optional. Metadata for the file 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.ai.generativelanguage.v1alpha.CreateFileResponse|CreateFileResponse}. + * 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/v1alpha/file_service.create_file.js + * region_tag:generativelanguage_v1alpha_generated_FileService_CreateFile_async + */ createFile( - request?: protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICreateFileResponse, - protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICreateFileResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest + | undefined + ), + {} | undefined, + ] + >; createFile( - request: protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICreateFileResponse, - protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ICreateFileResponse, + | protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createFile( - request: protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICreateFileResponse, - protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ICreateFileResponse, + | protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createFile( - request?: protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.ICreateFileResponse, - protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.ICreateFileResponse, - protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICreateFileResponse, - protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.ICreateFileResponse, + | protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICreateFileResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest + | 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 || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createFile request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICreateFileResponse, - protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.ICreateFileResponse, + | protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createFile response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createFile(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.ICreateFileResponse, - protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest|undefined, - {}|undefined - ]) => { - this._log.info('createFile response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createFile(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.ICreateFileResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.ICreateFileRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createFile response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets the metadata for the given `File`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the `File` to get. - * Example: `files/abc-123` - * @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.ai.generativelanguage.v1alpha.File|File}. - * 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/v1alpha/file_service.get_file.js - * region_tag:generativelanguage_v1alpha_generated_FileService_GetFile_async - */ + /** + * Gets the metadata for the given `File`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the `File` to get. + * Example: `files/abc-123` + * @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.ai.generativelanguage.v1alpha.File|File}. + * 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/v1alpha/file_service.get_file.js + * region_tag:generativelanguage_v1alpha_generated_FileService_GetFile_async + */ getFile( - request?: protos.google.ai.generativelanguage.v1alpha.IGetFileRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IFile, - protos.google.ai.generativelanguage.v1alpha.IGetFileRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IGetFileRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IFile, + protos.google.ai.generativelanguage.v1alpha.IGetFileRequest | undefined, + {} | undefined, + ] + >; getFile( - request: protos.google.ai.generativelanguage.v1alpha.IGetFileRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IFile, - protos.google.ai.generativelanguage.v1alpha.IGetFileRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGetFileRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IFile, + | protos.google.ai.generativelanguage.v1alpha.IGetFileRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getFile( - request: protos.google.ai.generativelanguage.v1alpha.IGetFileRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IFile, - protos.google.ai.generativelanguage.v1alpha.IGetFileRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGetFileRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IFile, + | protos.google.ai.generativelanguage.v1alpha.IGetFileRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getFile( - request?: protos.google.ai.generativelanguage.v1alpha.IGetFileRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IGetFileRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IFile, - protos.google.ai.generativelanguage.v1alpha.IGetFileRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1alpha.IFile, - protos.google.ai.generativelanguage.v1alpha.IGetFileRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IFile, - protos.google.ai.generativelanguage.v1alpha.IGetFileRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IGetFileRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IFile, + | protos.google.ai.generativelanguage.v1alpha.IGetFileRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IFile, + protos.google.ai.generativelanguage.v1alpha.IGetFileRequest | 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('getFile request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.IFile, - protos.google.ai.generativelanguage.v1alpha.IGetFileRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IFile, + | protos.google.ai.generativelanguage.v1alpha.IGetFileRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getFile response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getFile(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.IFile, - protos.google.ai.generativelanguage.v1alpha.IGetFileRequest|undefined, - {}|undefined - ]) => { - this._log.info('getFile response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getFile(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IFile, + ( + | protos.google.ai.generativelanguage.v1alpha.IGetFileRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getFile response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes the `File`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the `File` to delete. - * Example: `files/abc-123` - * @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/v1alpha/file_service.delete_file.js - * region_tag:generativelanguage_v1alpha_generated_FileService_DeleteFile_async - */ + /** + * Deletes the `File`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the `File` to delete. + * Example: `files/abc-123` + * @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/v1alpha/file_service.delete_file.js + * region_tag:generativelanguage_v1alpha_generated_FileService_DeleteFile_async + */ deleteFile( - request?: protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest + | undefined + ), + {} | undefined, + ] + >; deleteFile( - request: protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteFile( - request: protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteFile( - request?: protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest + | 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('deleteFile request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteFile response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteFile(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteFile response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteFile(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.IDeleteFileRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteFile response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists the metadata for `File`s owned by the requesting project. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. Maximum number of `File`s to return per page. - * If unspecified, defaults to 10. Maximum `page_size` is 100. - * @param {string} [request.pageToken] - * Optional. A page token from a previous `ListFiles` call. - * @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.ai.generativelanguage.v1alpha.File|File}. - * 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 `listFilesAsync()` - * 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 metadata for `File`s owned by the requesting project. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. Maximum number of `File`s to return per page. + * If unspecified, defaults to 10. Maximum `page_size` is 100. + * @param {string} [request.pageToken] + * Optional. A page token from a previous `ListFiles` call. + * @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.ai.generativelanguage.v1alpha.File|File}. + * 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 `listFilesAsync()` + * 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. + */ listFiles( - request?: protos.google.ai.generativelanguage.v1alpha.IListFilesRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IFile[], - protos.google.ai.generativelanguage.v1alpha.IListFilesRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListFilesResponse - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IListFilesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IFile[], + protos.google.ai.generativelanguage.v1alpha.IListFilesRequest | null, + protos.google.ai.generativelanguage.v1alpha.IListFilesResponse, + ] + >; listFiles( - request: protos.google.ai.generativelanguage.v1alpha.IListFilesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListFilesRequest, - protos.google.ai.generativelanguage.v1alpha.IListFilesResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IFile>): void; + request: protos.google.ai.generativelanguage.v1alpha.IListFilesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListFilesRequest, + | protos.google.ai.generativelanguage.v1alpha.IListFilesResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IFile + >, + ): void; listFiles( - request: protos.google.ai.generativelanguage.v1alpha.IListFilesRequest, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListFilesRequest, - protos.google.ai.generativelanguage.v1alpha.IListFilesResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IFile>): void; + request: protos.google.ai.generativelanguage.v1alpha.IListFilesRequest, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListFilesRequest, + | protos.google.ai.generativelanguage.v1alpha.IListFilesResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IFile + >, + ): void; listFiles( - request?: protos.google.ai.generativelanguage.v1alpha.IListFilesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListFilesRequest, - protos.google.ai.generativelanguage.v1alpha.IListFilesResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IFile>, - callback?: PaginationCallback< + request?: protos.google.ai.generativelanguage.v1alpha.IListFilesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ai.generativelanguage.v1alpha.IListFilesRequest, - protos.google.ai.generativelanguage.v1alpha.IListFilesResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IFile>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IFile[], - protos.google.ai.generativelanguage.v1alpha.IListFilesRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListFilesResponse - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IListFilesResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IFile + >, + callback?: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListFilesRequest, + | protos.google.ai.generativelanguage.v1alpha.IListFilesResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IFile + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IFile[], + protos.google.ai.generativelanguage.v1alpha.IListFilesRequest | null, + protos.google.ai.generativelanguage.v1alpha.IListFilesResponse, + ] + > | 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 || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListFilesRequest, - protos.google.ai.generativelanguage.v1alpha.IListFilesResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IFile>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListFilesRequest, + | protos.google.ai.generativelanguage.v1alpha.IListFilesResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IFile + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listFiles values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -721,94 +936,100 @@ export class FileServiceClient { this._log.info('listFiles request %j', request); return this.innerApiCalls .listFiles(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ai.generativelanguage.v1alpha.IFile[], - protos.google.ai.generativelanguage.v1alpha.IListFilesRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListFilesResponse - ]) => { - this._log.info('listFiles values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ai.generativelanguage.v1alpha.IFile[], + protos.google.ai.generativelanguage.v1alpha.IListFilesRequest | null, + protos.google.ai.generativelanguage.v1alpha.IListFilesResponse, + ]) => { + this._log.info('listFiles values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listFiles`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. Maximum number of `File`s to return per page. - * If unspecified, defaults to 10. Maximum `page_size` is 100. - * @param {string} [request.pageToken] - * Optional. A page token from a previous `ListFiles` call. - * @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.ai.generativelanguage.v1alpha.File|File} 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 `listFilesAsync()` - * 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 `listFiles`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. Maximum number of `File`s to return per page. + * If unspecified, defaults to 10. Maximum `page_size` is 100. + * @param {string} [request.pageToken] + * Optional. A page token from a previous `ListFiles` call. + * @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.ai.generativelanguage.v1alpha.File|File} 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 `listFilesAsync()` + * 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. + */ listFilesStream( - request?: protos.google.ai.generativelanguage.v1alpha.IListFilesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ai.generativelanguage.v1alpha.IListFilesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listFiles']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listFiles stream %j', request); return this.descriptors.page.listFiles.createStream( this.innerApiCalls.listFiles as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listFiles`, 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 {number} [request.pageSize] - * Optional. Maximum number of `File`s to return per page. - * If unspecified, defaults to 10. Maximum `page_size` is 100. - * @param {string} [request.pageToken] - * Optional. A page token from a previous `ListFiles` call. - * @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.ai.generativelanguage.v1alpha.File|File}. 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 include:samples/generated/v1alpha/file_service.list_files.js - * region_tag:generativelanguage_v1alpha_generated_FileService_ListFiles_async - */ + /** + * Equivalent to `listFiles`, 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 {number} [request.pageSize] + * Optional. Maximum number of `File`s to return per page. + * If unspecified, defaults to 10. Maximum `page_size` is 100. + * @param {string} [request.pageToken] + * Optional. A page token from a previous `ListFiles` call. + * @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.ai.generativelanguage.v1alpha.File|File}. 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 include:samples/generated/v1alpha/file_service.list_files.js + * region_tag:generativelanguage_v1alpha_generated_FileService_ListFiles_async + */ listFilesAsync( - request?: protos.google.ai.generativelanguage.v1alpha.IListFilesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ai.generativelanguage.v1alpha.IListFilesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listFiles']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listFiles iterate %j', request); return this.descriptors.page.listFiles.asyncIterate( this.innerApiCalls['listFiles'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -821,7 +1042,7 @@ export class FileServiceClient { * @param {string} id * @returns {string} Resource name string. */ - cachedContentPath(id:string) { + cachedContentPath(id: string) { return this.pathTemplates.cachedContentPathTemplate.render({ id: id, }); @@ -835,7 +1056,8 @@ export class FileServiceClient { * @returns {string} A string representing the id. */ matchIdFromCachedContentName(cachedContentName: string) { - return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName).id; + return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName) + .id; } /** @@ -846,7 +1068,7 @@ export class FileServiceClient { * @param {string} chunk * @returns {string} Resource name string. */ - chunkPath(corpus:string,document:string,chunk:string) { + chunkPath(corpus: string, document: string, chunk: string) { return this.pathTemplates.chunkPathTemplate.render({ corpus: corpus, document: document, @@ -893,7 +1115,7 @@ export class FileServiceClient { * @param {string} corpus * @returns {string} Resource name string. */ - corpusPath(corpus:string) { + corpusPath(corpus: string) { return this.pathTemplates.corpusPathTemplate.render({ corpus: corpus, }); @@ -917,7 +1139,7 @@ export class FileServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - corpusPermissionsPath(corpus:string,permission:string) { + corpusPermissionsPath(corpus: string, permission: string) { return this.pathTemplates.corpusPermissionsPathTemplate.render({ corpus: corpus, permission: permission, @@ -932,7 +1154,9 @@ export class FileServiceClient { * @returns {string} A string representing the corpus. */ matchCorpusFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).corpus; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).corpus; } /** @@ -943,7 +1167,9 @@ export class FileServiceClient { * @returns {string} A string representing the permission. */ matchPermissionFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).permission; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).permission; } /** @@ -953,7 +1179,7 @@ export class FileServiceClient { * @param {string} document * @returns {string} Resource name string. */ - documentPath(corpus:string,document:string) { + documentPath(corpus: string, document: string) { return this.pathTemplates.documentPathTemplate.render({ corpus: corpus, document: document, @@ -988,7 +1214,7 @@ export class FileServiceClient { * @param {string} file * @returns {string} Resource name string. */ - filePath(file:string) { + filePath(file: string) { return this.pathTemplates.filePathTemplate.render({ file: file, }); @@ -1011,7 +1237,7 @@ export class FileServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -1034,7 +1260,7 @@ export class FileServiceClient { * @param {string} tuned_model * @returns {string} Resource name string. */ - tunedModelPath(tunedModel:string) { + tunedModelPath(tunedModel: string) { return this.pathTemplates.tunedModelPathTemplate.render({ tuned_model: tunedModel, }); @@ -1048,7 +1274,8 @@ export class FileServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromTunedModelName(tunedModelName: string) { - return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName).tuned_model; + return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName) + .tuned_model; } /** @@ -1058,7 +1285,7 @@ export class FileServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - tunedModelPermissionsPath(tunedModel:string,permission:string) { + tunedModelPermissionsPath(tunedModel: string, permission: string) { return this.pathTemplates.tunedModelPermissionsPathTemplate.render({ tuned_model: tunedModel, permission: permission, @@ -1072,8 +1299,12 @@ export class FileServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the tuned_model. */ - matchTunedModelFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).tuned_model; + matchTunedModelFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).tuned_model; } /** @@ -1083,8 +1314,12 @@ export class FileServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the permission. */ - matchPermissionFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).permission; + matchPermissionFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).permission; } /** @@ -1095,7 +1330,7 @@ export class FileServiceClient { */ close(): Promise { if (this.fileServiceStub && !this._terminated) { - return this.fileServiceStub.then(stub => { + return this.fileServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1103,4 +1338,4 @@ export class FileServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1alpha/generative_service_client.ts b/packages/google-ai-generativelanguage/src/v1alpha/generative_service_client.ts index c62feb466459..fadd62d47b6b 100644 --- a/packages/google-ai-generativelanguage/src/v1alpha/generative_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1alpha/generative_service_client.ts @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; -import {PassThrough} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; +import { PassThrough } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -45,7 +50,7 @@ export class GenerativeServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -58,9 +63,9 @@ export class GenerativeServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - generativeServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + generativeServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of GenerativeServiceClient. @@ -101,21 +106,42 @@ export class GenerativeServiceClient { * const client = new GenerativeServiceClient({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 GenerativeServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -140,7 +166,7 @@ export class GenerativeServiceClient { 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; @@ -154,10 +180,7 @@ export class GenerativeServiceClient { } // 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 { @@ -179,45 +202,50 @@ export class GenerativeServiceClient { // Create useful helper objects for these. this.pathTemplates = { cachedContentPathTemplate: new this._gaxModule.PathTemplate( - 'cachedContents/{id}' + 'cachedContents/{id}', ), chunkPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}/chunks/{chunk}' - ), - corpusPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}' + 'corpora/{corpus}/documents/{document}/chunks/{chunk}', ), + corpusPathTemplate: new this._gaxModule.PathTemplate('corpora/{corpus}'), corpusPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/permissions/{permission}' + 'corpora/{corpus}/permissions/{permission}', ), documentPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}' - ), - filePathTemplate: new this._gaxModule.PathTemplate( - 'files/{file}' - ), - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' + 'corpora/{corpus}/documents/{document}', ), + filePathTemplate: new this._gaxModule.PathTemplate('files/{file}'), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), tunedModelPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}' + 'tunedModels/{tuned_model}', ), tunedModelPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}/permissions/{permission}' + 'tunedModels/{tuned_model}/permissions/{permission}', ), }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this.descriptors.stream = { - streamGenerateContent: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), - bidiGenerateContent: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries) + streamGenerateContent: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + bidiGenerateContent: 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.ai.generativelanguage.v1alpha.GenerativeService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1alpha.GenerativeService', + 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 @@ -248,44 +276,61 @@ export class GenerativeServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1alpha.GenerativeService. this.generativeServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1alpha.GenerativeService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1alpha.GenerativeService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1alpha.GenerativeService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1alpha + .GenerativeService, + 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 generativeServiceStubMethods = - ['generateContent', 'generateAnswer', 'streamGenerateContent', 'embedContent', 'batchEmbedContents', 'countTokens', 'bidiGenerateContent']; + const generativeServiceStubMethods = [ + 'generateContent', + 'generateAnswer', + 'streamGenerateContent', + 'embedContent', + 'batchEmbedContents', + 'countTokens', + 'bidiGenerateContent', + ]; for (const methodName of generativeServiceStubMethods) { const callPromise = this.generativeServiceStub.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.stream[methodName] || - undefined; + const descriptor = this.descriptors.stream[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -300,8 +345,14 @@ export class GenerativeServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -312,8 +363,14 @@ export class GenerativeServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -353,8 +410,9 @@ export class GenerativeServiceClient { * 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; @@ -365,742 +423,988 @@ export class GenerativeServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Generates a model response given an input `GenerateContentRequest`. - * Refer to the [text generation - * guide](https://ai.google.dev/gemini-api/docs/text-generation) for detailed - * usage information. Input capabilities differ between models, including - * tuned models. Refer to the [model - * guide](https://ai.google.dev/gemini-api/docs/models/gemini) and [tuning - * guide](https://ai.google.dev/gemini-api/docs/model-tuning) for details. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The name of the `Model` to use for generating the completion. - * - * Format: `models/{model}`. - * @param {google.ai.generativelanguage.v1alpha.Content} [request.systemInstruction] - * Optional. Developer set [system - * instruction(s)](https://ai.google.dev/gemini-api/docs/system-instructions). - * Currently, text only. - * @param {number[]} request.contents - * Required. The content of the current conversation with the model. - * - * For single-turn queries, this is a single instance. For multi-turn queries - * like [chat](https://ai.google.dev/gemini-api/docs/text-generation#chat), - * this is a repeated field that contains the conversation history and the - * latest request. - * @param {number[]} [request.tools] - * Optional. A list of `Tools` the `Model` may use to generate the next - * response. - * - * A `Tool` is a piece of code that enables the system to interact with - * external systems to perform an action, or set of actions, outside of - * knowledge and scope of the `Model`. Supported `Tool`s are `Function` and - * `code_execution`. Refer to the [Function - * calling](https://ai.google.dev/gemini-api/docs/function-calling) and the - * [Code execution](https://ai.google.dev/gemini-api/docs/code-execution) - * guides to learn more. - * @param {google.ai.generativelanguage.v1alpha.ToolConfig} [request.toolConfig] - * Optional. Tool configuration for any `Tool` specified in the request. Refer - * to the [Function calling - * guide](https://ai.google.dev/gemini-api/docs/function-calling#function_calling_mode) - * for a usage example. - * @param {number[]} [request.safetySettings] - * Optional. A list of unique `SafetySetting` instances for blocking unsafe - * content. - * - * This will be enforced on the `GenerateContentRequest.contents` and - * `GenerateContentResponse.candidates`. There should not be more than one - * setting for each `SafetyCategory` type. The API will block any contents and - * responses that fail to meet the thresholds set by these settings. This list - * overrides the default settings for each `SafetyCategory` specified in the - * safety_settings. If there is no `SafetySetting` for a given - * `SafetyCategory` provided in the list, the API will use the default safety - * setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH, - * HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, - * HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY are supported. - * Refer to the [guide](https://ai.google.dev/gemini-api/docs/safety-settings) - * for detailed information on available safety settings. Also refer to the - * [Safety guidance](https://ai.google.dev/gemini-api/docs/safety-guidance) to - * learn how to incorporate safety considerations in your AI applications. - * @param {google.ai.generativelanguage.v1alpha.GenerationConfig} [request.generationConfig] - * Optional. Configuration options for model generation and outputs. - * @param {string} [request.cachedContent] - * Optional. The name of the content - * [cached](https://ai.google.dev/gemini-api/docs/caching) to use as context - * to serve the prediction. Format: `cachedContents/{cachedContent}` - * @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.ai.generativelanguage.v1alpha.GenerateContentResponse|GenerateContentResponse}. - * 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/v1alpha/generative_service.generate_content.js - * region_tag:generativelanguage_v1alpha_generated_GenerativeService_GenerateContent_async - */ + /** + * Generates a model response given an input `GenerateContentRequest`. + * Refer to the [text generation + * guide](https://ai.google.dev/gemini-api/docs/text-generation) for detailed + * usage information. Input capabilities differ between models, including + * tuned models. Refer to the [model + * guide](https://ai.google.dev/gemini-api/docs/models/gemini) and [tuning + * guide](https://ai.google.dev/gemini-api/docs/model-tuning) for details. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The name of the `Model` to use for generating the completion. + * + * Format: `models/{model}`. + * @param {google.ai.generativelanguage.v1alpha.Content} [request.systemInstruction] + * Optional. Developer set [system + * instruction(s)](https://ai.google.dev/gemini-api/docs/system-instructions). + * Currently, text only. + * @param {number[]} request.contents + * Required. The content of the current conversation with the model. + * + * For single-turn queries, this is a single instance. For multi-turn queries + * like [chat](https://ai.google.dev/gemini-api/docs/text-generation#chat), + * this is a repeated field that contains the conversation history and the + * latest request. + * @param {number[]} [request.tools] + * Optional. A list of `Tools` the `Model` may use to generate the next + * response. + * + * A `Tool` is a piece of code that enables the system to interact with + * external systems to perform an action, or set of actions, outside of + * knowledge and scope of the `Model`. Supported `Tool`s are `Function` and + * `code_execution`. Refer to the [Function + * calling](https://ai.google.dev/gemini-api/docs/function-calling) and the + * [Code execution](https://ai.google.dev/gemini-api/docs/code-execution) + * guides to learn more. + * @param {google.ai.generativelanguage.v1alpha.ToolConfig} [request.toolConfig] + * Optional. Tool configuration for any `Tool` specified in the request. Refer + * to the [Function calling + * guide](https://ai.google.dev/gemini-api/docs/function-calling#function_calling_mode) + * for a usage example. + * @param {number[]} [request.safetySettings] + * Optional. A list of unique `SafetySetting` instances for blocking unsafe + * content. + * + * This will be enforced on the `GenerateContentRequest.contents` and + * `GenerateContentResponse.candidates`. There should not be more than one + * setting for each `SafetyCategory` type. The API will block any contents and + * responses that fail to meet the thresholds set by these settings. This list + * overrides the default settings for each `SafetyCategory` specified in the + * safety_settings. If there is no `SafetySetting` for a given + * `SafetyCategory` provided in the list, the API will use the default safety + * setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH, + * HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, + * HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY are supported. + * Refer to the [guide](https://ai.google.dev/gemini-api/docs/safety-settings) + * for detailed information on available safety settings. Also refer to the + * [Safety guidance](https://ai.google.dev/gemini-api/docs/safety-guidance) to + * learn how to incorporate safety considerations in your AI applications. + * @param {google.ai.generativelanguage.v1alpha.GenerationConfig} [request.generationConfig] + * Optional. Configuration options for model generation and outputs. + * @param {string} [request.cachedContent] + * Optional. The name of the content + * [cached](https://ai.google.dev/gemini-api/docs/caching) to use as context + * to serve the prediction. Format: `cachedContents/{cachedContent}` + * @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.ai.generativelanguage.v1alpha.GenerateContentResponse|GenerateContentResponse}. + * 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/v1alpha/generative_service.generate_content.js + * region_tag:generativelanguage_v1alpha_generated_GenerativeService_GenerateContent_async + */ generateContent( - request?: protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IGenerateContentResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest + | undefined + ), + {} | undefined, + ] + >; generateContent( - request: protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IGenerateContentResponse, + | protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateContent( - request: protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IGenerateContentResponse, + | protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateContent( - request?: protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1alpha.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IGenerateContentResponse, + | protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IGenerateContentResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('generateContent request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IGenerateContentResponse, + | protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('generateContent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.generateContent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest|undefined, - {}|undefined - ]) => { - this._log.info('generateContent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .generateContent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IGenerateContentResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('generateContent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Generates a grounded answer from the model given an input - * `GenerateAnswerRequest`. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ai.generativelanguage.v1alpha.GroundingPassages} request.inlinePassages - * Passages provided inline with the request. - * @param {google.ai.generativelanguage.v1alpha.SemanticRetrieverConfig} request.semanticRetriever - * Content retrieved from resources created via the Semantic Retriever - * API. - * @param {string} request.model - * Required. The name of the `Model` to use for generating the grounded - * response. - * - * Format: `model=models/{model}`. - * @param {number[]} request.contents - * Required. The content of the current conversation with the `Model`. For - * single-turn queries, this is a single question to answer. For multi-turn - * queries, this is a repeated field that contains conversation history and - * the last `Content` in the list containing the question. - * - * Note: `GenerateAnswer` only supports queries in English. - * @param {google.ai.generativelanguage.v1alpha.GenerateAnswerRequest.AnswerStyle} request.answerStyle - * Required. Style in which answers should be returned. - * @param {number[]} [request.safetySettings] - * Optional. A list of unique `SafetySetting` instances for blocking unsafe - * content. - * - * This will be enforced on the `GenerateAnswerRequest.contents` and - * `GenerateAnswerResponse.candidate`. There should not be more than one - * setting for each `SafetyCategory` type. The API will block any contents and - * responses that fail to meet the thresholds set by these settings. This list - * overrides the default settings for each `SafetyCategory` specified in the - * safety_settings. If there is no `SafetySetting` for a given - * `SafetyCategory` provided in the list, the API will use the default safety - * setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH, - * HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, - * HARM_CATEGORY_HARASSMENT are supported. - * Refer to the - * [guide](https://ai.google.dev/gemini-api/docs/safety-settings) - * for detailed information on available safety settings. Also refer to the - * [Safety guidance](https://ai.google.dev/gemini-api/docs/safety-guidance) to - * learn how to incorporate safety considerations in your AI applications. - * @param {number} [request.temperature] - * Optional. Controls the randomness of the output. - * - * Values can range from [0.0,1.0], inclusive. A value closer to 1.0 will - * produce responses that are more varied and creative, while a value closer - * to 0.0 will typically result in more straightforward responses from the - * model. A low temperature (~0.2) is usually recommended for - * Attributed-Question-Answering use cases. - * @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.ai.generativelanguage.v1alpha.GenerateAnswerResponse|GenerateAnswerResponse}. - * 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/v1alpha/generative_service.generate_answer.js - * region_tag:generativelanguage_v1alpha_generated_GenerativeService_GenerateAnswer_async - */ + /** + * Generates a grounded answer from the model given an input + * `GenerateAnswerRequest`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ai.generativelanguage.v1alpha.GroundingPassages} request.inlinePassages + * Passages provided inline with the request. + * @param {google.ai.generativelanguage.v1alpha.SemanticRetrieverConfig} request.semanticRetriever + * Content retrieved from resources created via the Semantic Retriever + * API. + * @param {string} request.model + * Required. The name of the `Model` to use for generating the grounded + * response. + * + * Format: `model=models/{model}`. + * @param {number[]} request.contents + * Required. The content of the current conversation with the `Model`. For + * single-turn queries, this is a single question to answer. For multi-turn + * queries, this is a repeated field that contains conversation history and + * the last `Content` in the list containing the question. + * + * Note: `GenerateAnswer` only supports queries in English. + * @param {google.ai.generativelanguage.v1alpha.GenerateAnswerRequest.AnswerStyle} request.answerStyle + * Required. Style in which answers should be returned. + * @param {number[]} [request.safetySettings] + * Optional. A list of unique `SafetySetting` instances for blocking unsafe + * content. + * + * This will be enforced on the `GenerateAnswerRequest.contents` and + * `GenerateAnswerResponse.candidate`. There should not be more than one + * setting for each `SafetyCategory` type. The API will block any contents and + * responses that fail to meet the thresholds set by these settings. This list + * overrides the default settings for each `SafetyCategory` specified in the + * safety_settings. If there is no `SafetySetting` for a given + * `SafetyCategory` provided in the list, the API will use the default safety + * setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH, + * HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, + * HARM_CATEGORY_HARASSMENT are supported. + * Refer to the + * [guide](https://ai.google.dev/gemini-api/docs/safety-settings) + * for detailed information on available safety settings. Also refer to the + * [Safety guidance](https://ai.google.dev/gemini-api/docs/safety-guidance) to + * learn how to incorporate safety considerations in your AI applications. + * @param {number} [request.temperature] + * Optional. Controls the randomness of the output. + * + * Values can range from [0.0,1.0], inclusive. A value closer to 1.0 will + * produce responses that are more varied and creative, while a value closer + * to 0.0 will typically result in more straightforward responses from the + * model. A low temperature (~0.2) is usually recommended for + * Attributed-Question-Answering use cases. + * @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.ai.generativelanguage.v1alpha.GenerateAnswerResponse|GenerateAnswerResponse}. + * 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/v1alpha/generative_service.generate_answer.js + * region_tag:generativelanguage_v1alpha_generated_GenerativeService_GenerateAnswer_async + */ generateAnswer( - request?: protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest + | undefined + ), + {} | undefined, + ] + >; generateAnswer( - request: protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerResponse, + | protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateAnswer( - request: protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerResponse, + | protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateAnswer( - request?: protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerResponse, + | protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('generateAnswer request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerResponse, + | protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('generateAnswer response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.generateAnswer(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest|undefined, - {}|undefined - ]) => { - this._log.info('generateAnswer response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .generateAnswer(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('generateAnswer response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Generates a text embedding vector from the input `Content` using the - * specified [Gemini Embedding - * model](https://ai.google.dev/gemini-api/docs/models/gemini#text-embedding). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The model's resource name. This serves as an ID for the Model to - * use. - * - * This name should match a model name returned by the `ListModels` method. - * - * Format: `models/{model}` - * @param {google.ai.generativelanguage.v1alpha.Content} request.content - * Required. The content to embed. Only the `parts.text` fields will be - * counted. - * @param {google.ai.generativelanguage.v1alpha.TaskType} [request.taskType] - * Optional. Optional task type for which the embeddings will be used. Can - * only be set for `models/embedding-001`. - * @param {string} [request.title] - * Optional. An optional title for the text. Only applicable when TaskType is - * `RETRIEVAL_DOCUMENT`. - * - * Note: Specifying a `title` for `RETRIEVAL_DOCUMENT` provides better quality - * embeddings for retrieval. - * @param {number} [request.outputDimensionality] - * Optional. Optional reduced dimension for the output embedding. If set, - * excessive values in the output embedding are truncated from the end. - * Supported by newer models since 2024 only. You cannot set this value if - * using the earlier model (`models/embedding-001`). - * @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.ai.generativelanguage.v1alpha.EmbedContentResponse|EmbedContentResponse}. - * 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/v1alpha/generative_service.embed_content.js - * region_tag:generativelanguage_v1alpha_generated_GenerativeService_EmbedContent_async - */ + /** + * Generates a text embedding vector from the input `Content` using the + * specified [Gemini Embedding + * model](https://ai.google.dev/gemini-api/docs/models/gemini#text-embedding). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The model's resource name. This serves as an ID for the Model to + * use. + * + * This name should match a model name returned by the `ListModels` method. + * + * Format: `models/{model}` + * @param {google.ai.generativelanguage.v1alpha.Content} request.content + * Required. The content to embed. Only the `parts.text` fields will be + * counted. + * @param {google.ai.generativelanguage.v1alpha.TaskType} [request.taskType] + * Optional. Optional task type for which the embeddings will be used. Can + * only be set for `models/embedding-001`. + * @param {string} [request.title] + * Optional. An optional title for the text. Only applicable when TaskType is + * `RETRIEVAL_DOCUMENT`. + * + * Note: Specifying a `title` for `RETRIEVAL_DOCUMENT` provides better quality + * embeddings for retrieval. + * @param {number} [request.outputDimensionality] + * Optional. Optional reduced dimension for the output embedding. If set, + * excessive values in the output embedding are truncated from the end. + * Supported by newer models since 2024 only. You cannot set this value if + * using the earlier model (`models/embedding-001`). + * @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.ai.generativelanguage.v1alpha.EmbedContentResponse|EmbedContentResponse}. + * 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/v1alpha/generative_service.embed_content.js + * region_tag:generativelanguage_v1alpha_generated_GenerativeService_EmbedContent_async + */ embedContent( - request?: protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IEmbedContentResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest + | undefined + ), + {} | undefined, + ] + >; embedContent( - request: protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IEmbedContentResponse, + | protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; embedContent( - request: protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IEmbedContentResponse, + | protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; embedContent( - request?: protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IEmbedContentResponse, + | protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IEmbedContentResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('embedContent request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IEmbedContentResponse, + | protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('embedContent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.embedContent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest|undefined, - {}|undefined - ]) => { - this._log.info('embedContent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .embedContent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IEmbedContentResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IEmbedContentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('embedContent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Generates multiple embedding vectors from the input `Content` which - * consists of a batch of strings represented as `EmbedContentRequest` - * objects. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The model's resource name. This serves as an ID for the Model to - * use. - * - * This name should match a model name returned by the `ListModels` method. - * - * Format: `models/{model}` - * @param {number[]} request.requests - * Required. Embed requests for the batch. The model in each of these requests - * must match the model specified `BatchEmbedContentsRequest.model`. - * @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.ai.generativelanguage.v1alpha.BatchEmbedContentsResponse|BatchEmbedContentsResponse}. - * 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/v1alpha/generative_service.batch_embed_contents.js - * region_tag:generativelanguage_v1alpha_generated_GenerativeService_BatchEmbedContents_async - */ + /** + * Generates multiple embedding vectors from the input `Content` which + * consists of a batch of strings represented as `EmbedContentRequest` + * objects. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The model's resource name. This serves as an ID for the Model to + * use. + * + * This name should match a model name returned by the `ListModels` method. + * + * Format: `models/{model}` + * @param {number[]} request.requests + * Required. Embed requests for the batch. The model in each of these requests + * must match the model specified `BatchEmbedContentsRequest.model`. + * @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.ai.generativelanguage.v1alpha.BatchEmbedContentsResponse|BatchEmbedContentsResponse}. + * 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/v1alpha/generative_service.batch_embed_contents.js + * region_tag:generativelanguage_v1alpha_generated_GenerativeService_BatchEmbedContents_async + */ batchEmbedContents( - request?: protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest + | undefined + ), + {} | undefined, + ] + >; batchEmbedContents( - request: protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsResponse, + | protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchEmbedContents( - request: protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsResponse, + | protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchEmbedContents( - request?: protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsResponse, + | protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('batchEmbedContents request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsResponse, + | protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchEmbedContents response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.batchEmbedContents(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest|undefined, - {}|undefined - ]) => { - this._log.info('batchEmbedContents response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchEmbedContents(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchEmbedContents response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Runs a model's tokenizer on input `Content` and returns the token count. - * Refer to the [tokens guide](https://ai.google.dev/gemini-api/docs/tokens) - * to learn more about tokens. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The model's resource name. This serves as an ID for the Model to - * use. - * - * This name should match a model name returned by the `ListModels` method. - * - * Format: `models/{model}` - * @param {number[]} [request.contents] - * Optional. The input given to the model as a prompt. This field is ignored - * when `generate_content_request` is set. - * @param {google.ai.generativelanguage.v1alpha.GenerateContentRequest} [request.generateContentRequest] - * Optional. The overall input given to the `Model`. This includes the prompt - * as well as other model steering information like [system - * instructions](https://ai.google.dev/gemini-api/docs/system-instructions), - * and/or function declarations for [function - * calling](https://ai.google.dev/gemini-api/docs/function-calling). - * `Model`s/`Content`s and `generate_content_request`s are mutually - * exclusive. You can either send `Model` + `Content`s or a - * `generate_content_request`, but never both. - * @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.ai.generativelanguage.v1alpha.CountTokensResponse|CountTokensResponse}. - * 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/v1alpha/generative_service.count_tokens.js - * region_tag:generativelanguage_v1alpha_generated_GenerativeService_CountTokens_async - */ + /** + * Runs a model's tokenizer on input `Content` and returns the token count. + * Refer to the [tokens guide](https://ai.google.dev/gemini-api/docs/tokens) + * to learn more about tokens. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The model's resource name. This serves as an ID for the Model to + * use. + * + * This name should match a model name returned by the `ListModels` method. + * + * Format: `models/{model}` + * @param {number[]} [request.contents] + * Optional. The input given to the model as a prompt. This field is ignored + * when `generate_content_request` is set. + * @param {google.ai.generativelanguage.v1alpha.GenerateContentRequest} [request.generateContentRequest] + * Optional. The overall input given to the `Model`. This includes the prompt + * as well as other model steering information like [system + * instructions](https://ai.google.dev/gemini-api/docs/system-instructions), + * and/or function declarations for [function + * calling](https://ai.google.dev/gemini-api/docs/function-calling). + * `Model`s/`Content`s and `generate_content_request`s are mutually + * exclusive. You can either send `Model` + `Content`s or a + * `generate_content_request`, but never both. + * @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.ai.generativelanguage.v1alpha.CountTokensResponse|CountTokensResponse}. + * 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/v1alpha/generative_service.count_tokens.js + * region_tag:generativelanguage_v1alpha_generated_GenerativeService_CountTokens_async + */ countTokens( - request?: protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICountTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICountTokensResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest + | undefined + ), + {} | undefined, + ] + >; countTokens( - request: protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICountTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ICountTokensResponse, + | protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): void; countTokens( - request: protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICountTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ICountTokensResponse, + | protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): void; countTokens( - request?: protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.ICountTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.ICountTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICountTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.ICountTokensResponse, + | protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICountTokensResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('countTokens request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICountTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.ICountTokensResponse, + | protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('countTokens response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.countTokens(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.ICountTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest|undefined, - {}|undefined - ]) => { - this._log.info('countTokens response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .countTokens(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.ICountTokensResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.ICountTokensRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('countTokens response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Generates a [streamed - * response](https://ai.google.dev/gemini-api/docs/text-generation?lang=python#generate-a-text-stream) - * from the model given an input `GenerateContentRequest`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The name of the `Model` to use for generating the completion. - * - * Format: `models/{model}`. - * @param {google.ai.generativelanguage.v1alpha.Content} [request.systemInstruction] - * Optional. Developer set [system - * instruction(s)](https://ai.google.dev/gemini-api/docs/system-instructions). - * Currently, text only. - * @param {number[]} request.contents - * Required. The content of the current conversation with the model. - * - * For single-turn queries, this is a single instance. For multi-turn queries - * like [chat](https://ai.google.dev/gemini-api/docs/text-generation#chat), - * this is a repeated field that contains the conversation history and the - * latest request. - * @param {number[]} [request.tools] - * Optional. A list of `Tools` the `Model` may use to generate the next - * response. - * - * A `Tool` is a piece of code that enables the system to interact with - * external systems to perform an action, or set of actions, outside of - * knowledge and scope of the `Model`. Supported `Tool`s are `Function` and - * `code_execution`. Refer to the [Function - * calling](https://ai.google.dev/gemini-api/docs/function-calling) and the - * [Code execution](https://ai.google.dev/gemini-api/docs/code-execution) - * guides to learn more. - * @param {google.ai.generativelanguage.v1alpha.ToolConfig} [request.toolConfig] - * Optional. Tool configuration for any `Tool` specified in the request. Refer - * to the [Function calling - * guide](https://ai.google.dev/gemini-api/docs/function-calling#function_calling_mode) - * for a usage example. - * @param {number[]} [request.safetySettings] - * Optional. A list of unique `SafetySetting` instances for blocking unsafe - * content. - * - * This will be enforced on the `GenerateContentRequest.contents` and - * `GenerateContentResponse.candidates`. There should not be more than one - * setting for each `SafetyCategory` type. The API will block any contents and - * responses that fail to meet the thresholds set by these settings. This list - * overrides the default settings for each `SafetyCategory` specified in the - * safety_settings. If there is no `SafetySetting` for a given - * `SafetyCategory` provided in the list, the API will use the default safety - * setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH, - * HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, - * HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY are supported. - * Refer to the [guide](https://ai.google.dev/gemini-api/docs/safety-settings) - * for detailed information on available safety settings. Also refer to the - * [Safety guidance](https://ai.google.dev/gemini-api/docs/safety-guidance) to - * learn how to incorporate safety considerations in your AI applications. - * @param {google.ai.generativelanguage.v1alpha.GenerationConfig} [request.generationConfig] - * Optional. Configuration options for model generation and outputs. - * @param {string} [request.cachedContent] - * Optional. The name of the content - * [cached](https://ai.google.dev/gemini-api/docs/caching) to use as context - * to serve the prediction. Format: `cachedContents/{cachedContent}` - * @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.ai.generativelanguage.v1alpha.GenerateContentResponse|GenerateContentResponse} 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/v1alpha/generative_service.stream_generate_content.js - * region_tag:generativelanguage_v1alpha_generated_GenerativeService_StreamGenerateContent_async - */ + /** + * Generates a [streamed + * response](https://ai.google.dev/gemini-api/docs/text-generation?lang=python#generate-a-text-stream) + * from the model given an input `GenerateContentRequest`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The name of the `Model` to use for generating the completion. + * + * Format: `models/{model}`. + * @param {google.ai.generativelanguage.v1alpha.Content} [request.systemInstruction] + * Optional. Developer set [system + * instruction(s)](https://ai.google.dev/gemini-api/docs/system-instructions). + * Currently, text only. + * @param {number[]} request.contents + * Required. The content of the current conversation with the model. + * + * For single-turn queries, this is a single instance. For multi-turn queries + * like [chat](https://ai.google.dev/gemini-api/docs/text-generation#chat), + * this is a repeated field that contains the conversation history and the + * latest request. + * @param {number[]} [request.tools] + * Optional. A list of `Tools` the `Model` may use to generate the next + * response. + * + * A `Tool` is a piece of code that enables the system to interact with + * external systems to perform an action, or set of actions, outside of + * knowledge and scope of the `Model`. Supported `Tool`s are `Function` and + * `code_execution`. Refer to the [Function + * calling](https://ai.google.dev/gemini-api/docs/function-calling) and the + * [Code execution](https://ai.google.dev/gemini-api/docs/code-execution) + * guides to learn more. + * @param {google.ai.generativelanguage.v1alpha.ToolConfig} [request.toolConfig] + * Optional. Tool configuration for any `Tool` specified in the request. Refer + * to the [Function calling + * guide](https://ai.google.dev/gemini-api/docs/function-calling#function_calling_mode) + * for a usage example. + * @param {number[]} [request.safetySettings] + * Optional. A list of unique `SafetySetting` instances for blocking unsafe + * content. + * + * This will be enforced on the `GenerateContentRequest.contents` and + * `GenerateContentResponse.candidates`. There should not be more than one + * setting for each `SafetyCategory` type. The API will block any contents and + * responses that fail to meet the thresholds set by these settings. This list + * overrides the default settings for each `SafetyCategory` specified in the + * safety_settings. If there is no `SafetySetting` for a given + * `SafetyCategory` provided in the list, the API will use the default safety + * setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH, + * HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, + * HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY are supported. + * Refer to the [guide](https://ai.google.dev/gemini-api/docs/safety-settings) + * for detailed information on available safety settings. Also refer to the + * [Safety guidance](https://ai.google.dev/gemini-api/docs/safety-guidance) to + * learn how to incorporate safety considerations in your AI applications. + * @param {google.ai.generativelanguage.v1alpha.GenerationConfig} [request.generationConfig] + * Optional. Configuration options for model generation and outputs. + * @param {string} [request.cachedContent] + * Optional. The name of the content + * [cached](https://ai.google.dev/gemini-api/docs/caching) to use as context + * to serve the prediction. Format: `cachedContents/{cachedContent}` + * @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.ai.generativelanguage.v1alpha.GenerateContentResponse|GenerateContentResponse} 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/v1alpha/generative_service.stream_generate_content.js + * region_tag:generativelanguage_v1alpha_generated_GenerativeService_StreamGenerateContent_async + */ streamGenerateContent( - request?: protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest, - options?: CallOptions): - gax.CancellableStream{ + request?: protos.google.ai.generativelanguage.v1alpha.IGenerateContentRequest, + 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('streamGenerateContent stream %j', options); return this.innerApiCalls.streamGenerateContent(request, options); } -/** - * Low-Latency bidirectional streaming API that supports audio and video - * streaming inputs can produce multimodal output streams (audio and text). - * - * @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.ai.generativelanguage.v1alpha.BidiGenerateContentClientMessage|BidiGenerateContentClientMessage} for write() method, and - * will emit objects representing {@link protos.google.ai.generativelanguage.v1alpha.BidiGenerateContentServerMessage|BidiGenerateContentServerMessage} 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/v1alpha/generative_service.bidi_generate_content.js - * region_tag:generativelanguage_v1alpha_generated_GenerativeService_BidiGenerateContent_async - */ - bidiGenerateContent( - options?: CallOptions): - gax.CancellableStream { - this.initialize().catch(err => {throw err}); + /** + * Low-Latency bidirectional streaming API that supports audio and video + * streaming inputs can produce multimodal output streams (audio and text). + * + * @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.ai.generativelanguage.v1alpha.BidiGenerateContentClientMessage|BidiGenerateContentClientMessage} for write() method, and + * will emit objects representing {@link protos.google.ai.generativelanguage.v1alpha.BidiGenerateContentServerMessage|BidiGenerateContentServerMessage} 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/v1alpha/generative_service.bidi_generate_content.js + * region_tag:generativelanguage_v1alpha_generated_GenerativeService_BidiGenerateContent_async + */ + bidiGenerateContent(options?: CallOptions): gax.CancellableStream { + this.initialize().catch((err) => { + throw err; + }); this._log.info('bidiGenerateContent stream %j', options); return this.innerApiCalls.bidiGenerateContent(null, options); } @@ -1115,7 +1419,7 @@ export class GenerativeServiceClient { * @param {string} id * @returns {string} Resource name string. */ - cachedContentPath(id:string) { + cachedContentPath(id: string) { return this.pathTemplates.cachedContentPathTemplate.render({ id: id, }); @@ -1129,7 +1433,8 @@ export class GenerativeServiceClient { * @returns {string} A string representing the id. */ matchIdFromCachedContentName(cachedContentName: string) { - return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName).id; + return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName) + .id; } /** @@ -1140,7 +1445,7 @@ export class GenerativeServiceClient { * @param {string} chunk * @returns {string} Resource name string. */ - chunkPath(corpus:string,document:string,chunk:string) { + chunkPath(corpus: string, document: string, chunk: string) { return this.pathTemplates.chunkPathTemplate.render({ corpus: corpus, document: document, @@ -1187,7 +1492,7 @@ export class GenerativeServiceClient { * @param {string} corpus * @returns {string} Resource name string. */ - corpusPath(corpus:string) { + corpusPath(corpus: string) { return this.pathTemplates.corpusPathTemplate.render({ corpus: corpus, }); @@ -1211,7 +1516,7 @@ export class GenerativeServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - corpusPermissionsPath(corpus:string,permission:string) { + corpusPermissionsPath(corpus: string, permission: string) { return this.pathTemplates.corpusPermissionsPathTemplate.render({ corpus: corpus, permission: permission, @@ -1226,7 +1531,9 @@ export class GenerativeServiceClient { * @returns {string} A string representing the corpus. */ matchCorpusFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).corpus; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).corpus; } /** @@ -1237,7 +1544,9 @@ export class GenerativeServiceClient { * @returns {string} A string representing the permission. */ matchPermissionFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).permission; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).permission; } /** @@ -1247,7 +1556,7 @@ export class GenerativeServiceClient { * @param {string} document * @returns {string} Resource name string. */ - documentPath(corpus:string,document:string) { + documentPath(corpus: string, document: string) { return this.pathTemplates.documentPathTemplate.render({ corpus: corpus, document: document, @@ -1282,7 +1591,7 @@ export class GenerativeServiceClient { * @param {string} file * @returns {string} Resource name string. */ - filePath(file:string) { + filePath(file: string) { return this.pathTemplates.filePathTemplate.render({ file: file, }); @@ -1305,7 +1614,7 @@ export class GenerativeServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -1328,7 +1637,7 @@ export class GenerativeServiceClient { * @param {string} tuned_model * @returns {string} Resource name string. */ - tunedModelPath(tunedModel:string) { + tunedModelPath(tunedModel: string) { return this.pathTemplates.tunedModelPathTemplate.render({ tuned_model: tunedModel, }); @@ -1342,7 +1651,8 @@ export class GenerativeServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromTunedModelName(tunedModelName: string) { - return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName).tuned_model; + return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName) + .tuned_model; } /** @@ -1352,7 +1662,7 @@ export class GenerativeServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - tunedModelPermissionsPath(tunedModel:string,permission:string) { + tunedModelPermissionsPath(tunedModel: string, permission: string) { return this.pathTemplates.tunedModelPermissionsPathTemplate.render({ tuned_model: tunedModel, permission: permission, @@ -1366,8 +1676,12 @@ export class GenerativeServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the tuned_model. */ - matchTunedModelFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).tuned_model; + matchTunedModelFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).tuned_model; } /** @@ -1377,8 +1691,12 @@ export class GenerativeServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the permission. */ - matchPermissionFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).permission; + matchPermissionFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).permission; } /** @@ -1389,7 +1707,7 @@ export class GenerativeServiceClient { */ close(): Promise { if (this.generativeServiceStub && !this._terminated) { - return this.generativeServiceStub.then(stub => { + return this.generativeServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1397,4 +1715,4 @@ export class GenerativeServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1alpha/index.ts b/packages/google-ai-generativelanguage/src/v1alpha/index.ts index 0990437bcba5..0cd29f98b444 100644 --- a/packages/google-ai-generativelanguage/src/v1alpha/index.ts +++ b/packages/google-ai-generativelanguage/src/v1alpha/index.ts @@ -16,12 +16,12 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {CacheServiceClient} from './cache_service_client'; -export {DiscussServiceClient} from './discuss_service_client'; -export {FileServiceClient} from './file_service_client'; -export {GenerativeServiceClient} from './generative_service_client'; -export {ModelServiceClient} from './model_service_client'; -export {PermissionServiceClient} from './permission_service_client'; -export {PredictionServiceClient} from './prediction_service_client'; -export {RetrieverServiceClient} from './retriever_service_client'; -export {TextServiceClient} from './text_service_client'; +export { CacheServiceClient } from './cache_service_client'; +export { DiscussServiceClient } from './discuss_service_client'; +export { FileServiceClient } from './file_service_client'; +export { GenerativeServiceClient } from './generative_service_client'; +export { ModelServiceClient } from './model_service_client'; +export { PermissionServiceClient } from './permission_service_client'; +export { PredictionServiceClient } from './prediction_service_client'; +export { RetrieverServiceClient } from './retriever_service_client'; +export { TextServiceClient } from './text_service_client'; diff --git a/packages/google-ai-generativelanguage/src/v1alpha/model_service_client.ts b/packages/google-ai-generativelanguage/src/v1alpha/model_service_client.ts index 53e4d2c10b5c..ded737403c98 100644 --- a/packages/google-ai-generativelanguage/src/v1alpha/model_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1alpha/model_service_client.ts @@ -18,11 +18,20 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +53,7 @@ export class ModelServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -57,10 +66,10 @@ export class ModelServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - modelServiceStub?: Promise<{[name: string]: Function}>; + modelServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ModelServiceClient. @@ -101,21 +110,42 @@ export class ModelServiceClient { * const client = new ModelServiceClient({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 ModelServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -140,7 +170,7 @@ export class ModelServiceClient { 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; @@ -154,10 +184,7 @@ export class ModelServiceClient { } // 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 { @@ -179,31 +206,25 @@ export class ModelServiceClient { // Create useful helper objects for these. this.pathTemplates = { cachedContentPathTemplate: new this._gaxModule.PathTemplate( - 'cachedContents/{id}' + 'cachedContents/{id}', ), chunkPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}/chunks/{chunk}' - ), - corpusPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}' + 'corpora/{corpus}/documents/{document}/chunks/{chunk}', ), + corpusPathTemplate: new this._gaxModule.PathTemplate('corpora/{corpus}'), corpusPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/permissions/{permission}' + 'corpora/{corpus}/permissions/{permission}', ), documentPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}' - ), - filePathTemplate: new this._gaxModule.PathTemplate( - 'files/{file}' - ), - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' + 'corpora/{corpus}/documents/{document}', ), + filePathTemplate: new this._gaxModule.PathTemplate('files/{file}'), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), tunedModelPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}' + 'tunedModels/{tuned_model}', ), tunedModelPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}/permissions/{permission}' + 'tunedModels/{tuned_model}/permissions/{permission}', ), }; @@ -211,10 +232,16 @@ export class ModelServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listModels: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'models'), - listTunedModels: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'tunedModels') + listModels: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'models', + ), + listTunedModels: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'tunedModels', + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -223,31 +250,51 @@ export class ModelServiceClient { // 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.GetOperation',get: '/v1alpha/{name=tunedModels/*/operations/*}',additional_bindings: [{get: '/v1alpha/{name=generatedFiles/*/operations/*}',},{get: '/v1alpha/{name=models/*/operations/*}',}], - },{selector: 'google.longrunning.Operations.ListOperations',get: '/v1alpha/{name=tunedModels/*}/operations',additional_bindings: [{get: '/v1alpha/{name=models/*}/operations',}], - }]; + lroOptions.httpRules = [ + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v1alpha/{name=tunedModels/*/operations/*}', + additional_bindings: [ + { get: '/v1alpha/{name=generatedFiles/*/operations/*}' }, + { get: '/v1alpha/{name=models/*/operations/*}' }, + ], + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v1alpha/{name=tunedModels/*}/operations', + additional_bindings: [{ get: '/v1alpha/{name=models/*}/operations' }], + }, + ]; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const createTunedModelResponse = protoFilesRoot.lookup( - '.google.ai.generativelanguage.v1alpha.TunedModel') as gax.protobuf.Type; + '.google.ai.generativelanguage.v1alpha.TunedModel', + ) as gax.protobuf.Type; const createTunedModelMetadata = protoFilesRoot.lookup( - '.google.ai.generativelanguage.v1alpha.CreateTunedModelMetadata') as gax.protobuf.Type; + '.google.ai.generativelanguage.v1alpha.CreateTunedModelMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { createTunedModel: new this._gaxModule.LongrunningDescriptor( this.operationsClient, createTunedModelResponse.decode.bind(createTunedModelResponse), - createTunedModelMetadata.decode.bind(createTunedModelMetadata)) + createTunedModelMetadata.decode.bind(createTunedModelMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1alpha.ModelService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1alpha.ModelService', + 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 @@ -278,28 +325,42 @@ export class ModelServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1alpha.ModelService. this.modelServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1alpha.ModelService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1alpha.ModelService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1alpha.ModelService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1alpha + .ModelService, + 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 modelServiceStubMethods = - ['getModel', 'listModels', 'getTunedModel', 'listTunedModels', 'createTunedModel', 'updateTunedModel', 'deleteTunedModel']; + const modelServiceStubMethods = [ + 'getModel', + 'listModels', + 'getTunedModel', + 'listTunedModels', + 'createTunedModel', + 'updateTunedModel', + 'deleteTunedModel', + ]; for (const methodName of modelServiceStubMethods) { const callPromise = this.modelServiceStub.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] || @@ -309,7 +370,7 @@ export class ModelServiceClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -324,8 +385,14 @@ export class ModelServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -336,8 +403,14 @@ export class ModelServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -377,8 +450,9 @@ export class ModelServiceClient { * 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; @@ -389,595 +463,874 @@ export class ModelServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets information about a specific `Model` such as its version number, token - * limits, - * [parameters](https://ai.google.dev/gemini-api/docs/models/generative-models#model-parameters) - * and other metadata. Refer to the [Gemini models - * guide](https://ai.google.dev/gemini-api/docs/models/gemini) for detailed - * model information. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the model. - * - * This name should match a model name returned by the `ListModels` method. - * - * Format: `models/{model}` - * @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.ai.generativelanguage.v1alpha.Model|Model}. - * 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/v1alpha/model_service.get_model.js - * region_tag:generativelanguage_v1alpha_generated_ModelService_GetModel_async - */ + /** + * Gets information about a specific `Model` such as its version number, token + * limits, + * [parameters](https://ai.google.dev/gemini-api/docs/models/generative-models#model-parameters) + * and other metadata. Refer to the [Gemini models + * guide](https://ai.google.dev/gemini-api/docs/models/gemini) for detailed + * model information. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the model. + * + * This name should match a model name returned by the `ListModels` method. + * + * Format: `models/{model}` + * @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.ai.generativelanguage.v1alpha.Model|Model}. + * 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/v1alpha/model_service.get_model.js + * region_tag:generativelanguage_v1alpha_generated_ModelService_GetModel_async + */ getModel( - request?: protos.google.ai.generativelanguage.v1alpha.IGetModelRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IModel, - protos.google.ai.generativelanguage.v1alpha.IGetModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IGetModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IModel, + protos.google.ai.generativelanguage.v1alpha.IGetModelRequest | undefined, + {} | undefined, + ] + >; getModel( - request: protos.google.ai.generativelanguage.v1alpha.IGetModelRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IModel, - protos.google.ai.generativelanguage.v1alpha.IGetModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGetModelRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IModel, + | protos.google.ai.generativelanguage.v1alpha.IGetModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getModel( - request: protos.google.ai.generativelanguage.v1alpha.IGetModelRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IModel, - protos.google.ai.generativelanguage.v1alpha.IGetModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGetModelRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IModel, + | protos.google.ai.generativelanguage.v1alpha.IGetModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getModel( - request?: protos.google.ai.generativelanguage.v1alpha.IGetModelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.IModel, - protos.google.ai.generativelanguage.v1alpha.IGetModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IGetModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IModel, - protos.google.ai.generativelanguage.v1alpha.IGetModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IModel, - protos.google.ai.generativelanguage.v1alpha.IGetModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IGetModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IModel, + | protos.google.ai.generativelanguage.v1alpha.IGetModelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IModel, + protos.google.ai.generativelanguage.v1alpha.IGetModelRequest | 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('getModel request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.IModel, - protos.google.ai.generativelanguage.v1alpha.IGetModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IModel, + | protos.google.ai.generativelanguage.v1alpha.IGetModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getModel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.IModel, - protos.google.ai.generativelanguage.v1alpha.IGetModelRequest|undefined, - {}|undefined - ]) => { - this._log.info('getModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IModel, + ( + | protos.google.ai.generativelanguage.v1alpha.IGetModelRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets information about a specific TunedModel. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the model. - * - * Format: `tunedModels/my-model-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.ai.generativelanguage.v1alpha.TunedModel|TunedModel}. - * 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/v1alpha/model_service.get_tuned_model.js - * region_tag:generativelanguage_v1alpha_generated_ModelService_GetTunedModel_async - */ + /** + * Gets information about a specific TunedModel. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the model. + * + * Format: `tunedModels/my-model-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.ai.generativelanguage.v1alpha.TunedModel|TunedModel}. + * 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/v1alpha/model_service.get_tuned_model.js + * region_tag:generativelanguage_v1alpha_generated_ModelService_GetTunedModel_async + */ getTunedModel( - request?: protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ITunedModel, - protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + ( + | protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest + | undefined + ), + {} | undefined, + ] + >; getTunedModel( - request: protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ITunedModel, - protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + | protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getTunedModel( - request: protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ITunedModel, - protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + | protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getTunedModel( - request?: protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.ITunedModel, - protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.ITunedModel, - protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ITunedModel, - protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + | protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + ( + | protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest + | 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('getTunedModel request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.ITunedModel, - protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + | protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getTunedModel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getTunedModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.ITunedModel, - protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest|undefined, - {}|undefined - ]) => { - this._log.info('getTunedModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getTunedModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + ( + | protos.google.ai.generativelanguage.v1alpha.IGetTunedModelRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getTunedModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a tuned model. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ai.generativelanguage.v1alpha.TunedModel} request.tunedModel - * Required. The tuned model to update. - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. The list of fields to update. - * @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.ai.generativelanguage.v1alpha.TunedModel|TunedModel}. - * 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/v1alpha/model_service.update_tuned_model.js - * region_tag:generativelanguage_v1alpha_generated_ModelService_UpdateTunedModel_async - */ + /** + * Updates a tuned model. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ai.generativelanguage.v1alpha.TunedModel} request.tunedModel + * Required. The tuned model to update. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. The list of fields to update. + * @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.ai.generativelanguage.v1alpha.TunedModel|TunedModel}. + * 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/v1alpha/model_service.update_tuned_model.js + * region_tag:generativelanguage_v1alpha_generated_ModelService_UpdateTunedModel_async + */ updateTunedModel( - request?: protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ITunedModel, - protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + ( + | protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest + | undefined + ), + {} | undefined, + ] + >; updateTunedModel( - request: protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ITunedModel, - protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + | protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateTunedModel( - request: protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ITunedModel, - protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + | protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateTunedModel( - request?: protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.ITunedModel, - protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.ITunedModel, - protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ITunedModel, - protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + | protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + ( + | protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest + | 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({ - 'tuned_model.name': request.tunedModel!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'tuned_model.name': request.tunedModel!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateTunedModel request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.ITunedModel, - protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + | protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateTunedModel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateTunedModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.ITunedModel, - protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateTunedModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateTunedModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + ( + | protos.google.ai.generativelanguage.v1alpha.IUpdateTunedModelRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateTunedModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a tuned model. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the model. - * Format: `tunedModels/my-model-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 include:samples/generated/v1alpha/model_service.delete_tuned_model.js - * region_tag:generativelanguage_v1alpha_generated_ModelService_DeleteTunedModel_async - */ + /** + * Deletes a tuned model. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the model. + * Format: `tunedModels/my-model-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 include:samples/generated/v1alpha/model_service.delete_tuned_model.js + * region_tag:generativelanguage_v1alpha_generated_ModelService_DeleteTunedModel_async + */ deleteTunedModel( - request?: protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest + | undefined + ), + {} | undefined, + ] + >; deleteTunedModel( - request: protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteTunedModel( - request: protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteTunedModel( - request?: protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest + | 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('deleteTunedModel request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteTunedModel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteTunedModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteTunedModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteTunedModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.IDeleteTunedModelRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteTunedModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a tuned model. - * Check intermediate tuning progress (if any) through the - * [google.longrunning.Operations] service. - * - * Access status and results through the Operations service. - * Example: - * GET /v1/tunedModels/az2mb0bpw6i/operations/000-111-222 - * - * @param {Object} request - * The request object that will be sent. - * @param {string} [request.tunedModelId] - * Optional. The unique id for the tuned model if specified. - * This value should be up to 40 characters, the first character must be a - * letter, the last could be a letter or a number. The id must match the - * regular expression: `[a-z]([a-z0-9-]{0,38}[a-z0-9])?`. - * @param {google.ai.generativelanguage.v1alpha.TunedModel} request.tunedModel - * Required. The tuned model 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 include:samples/generated/v1alpha/model_service.create_tuned_model.js - * region_tag:generativelanguage_v1alpha_generated_ModelService_CreateTunedModel_async - */ + /** + * Creates a tuned model. + * Check intermediate tuning progress (if any) through the + * [google.longrunning.Operations] service. + * + * Access status and results through the Operations service. + * Example: + * GET /v1/tunedModels/az2mb0bpw6i/operations/000-111-222 + * + * @param {Object} request + * The request object that will be sent. + * @param {string} [request.tunedModelId] + * Optional. The unique id for the tuned model if specified. + * This value should be up to 40 characters, the first character must be a + * letter, the last could be a letter or a number. The id must match the + * regular expression: `[a-z]([a-z0-9-]{0,38}[a-z0-9])?`. + * @param {google.ai.generativelanguage.v1alpha.TunedModel} request.tunedModel + * Required. The tuned model 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 include:samples/generated/v1alpha/model_service.create_tuned_model.js + * region_tag:generativelanguage_v1alpha_generated_ModelService_CreateTunedModel_async + */ createTunedModel( - request?: protos.google.ai.generativelanguage.v1alpha.ICreateTunedModelRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.ICreateTunedModelRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + protos.google.ai.generativelanguage.v1alpha.ICreateTunedModelMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; createTunedModel( - request: protos.google.ai.generativelanguage.v1alpha.ICreateTunedModelRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.ICreateTunedModelRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + protos.google.ai.generativelanguage.v1alpha.ICreateTunedModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createTunedModel( - request: protos.google.ai.generativelanguage.v1alpha.ICreateTunedModelRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.ICreateTunedModelRequest, + callback: Callback< + LROperation< + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + protos.google.ai.generativelanguage.v1alpha.ICreateTunedModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createTunedModel( - request?: protos.google.ai.generativelanguage.v1alpha.ICreateTunedModelRequest, - 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.ai.generativelanguage.v1alpha.ICreateTunedModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + protos.google.ai.generativelanguage.v1alpha.ICreateTunedModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + protos.google.ai.generativelanguage.v1alpha.ICreateTunedModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + protos.google.ai.generativelanguage.v1alpha.ICreateTunedModelMetadata + >, + 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 || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + protos.google.ai.generativelanguage.v1alpha.ICreateTunedModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('createTunedModel response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('createTunedModel request %j', request); - return this.innerApiCalls.createTunedModel(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('createTunedModel response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .createTunedModel(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + protos.google.ai.generativelanguage.v1alpha.ICreateTunedModelMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createTunedModel response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `createTunedModel()`. - * @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/v1alpha/model_service.create_tuned_model.js - * region_tag:generativelanguage_v1alpha_generated_ModelService_CreateTunedModel_async - */ - async checkCreateTunedModelProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `createTunedModel()`. + * @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/v1alpha/model_service.create_tuned_model.js + * region_tag:generativelanguage_v1alpha_generated_ModelService_CreateTunedModel_async + */ + async checkCreateTunedModelProgress( + name: string, + ): Promise< + LROperation< + protos.google.ai.generativelanguage.v1alpha.TunedModel, + protos.google.ai.generativelanguage.v1alpha.CreateTunedModelMetadata + > + > { this._log.info('createTunedModel 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.createTunedModel, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createTunedModel, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.ai.generativelanguage.v1alpha.TunedModel, + protos.google.ai.generativelanguage.v1alpha.CreateTunedModelMetadata + >; } - /** - * Lists the [`Model`s](https://ai.google.dev/gemini-api/docs/models/gemini) - * available through the Gemini API. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of `Models` to return (per page). - * - * If unspecified, 50 models will be returned per page. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} request.pageToken - * A page token, received from a previous `ListModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListModels` must match - * the call that provided the page token. - * @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.ai.generativelanguage.v1alpha.Model|Model}. - * 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 `listModelsAsync()` - * 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 [`Model`s](https://ai.google.dev/gemini-api/docs/models/gemini) + * available through the Gemini API. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of `Models` to return (per page). + * + * If unspecified, 50 models will be returned per page. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} request.pageToken + * A page token, received from a previous `ListModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListModels` must match + * the call that provided the page token. + * @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.ai.generativelanguage.v1alpha.Model|Model}. + * 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 `listModelsAsync()` + * 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. + */ listModels( - request?: protos.google.ai.generativelanguage.v1alpha.IListModelsRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IModel[], - protos.google.ai.generativelanguage.v1alpha.IListModelsRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListModelsResponse - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IListModelsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IModel[], + protos.google.ai.generativelanguage.v1alpha.IListModelsRequest | null, + protos.google.ai.generativelanguage.v1alpha.IListModelsResponse, + ] + >; listModels( - request: protos.google.ai.generativelanguage.v1alpha.IListModelsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListModelsRequest, - protos.google.ai.generativelanguage.v1alpha.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IModel>): void; + request: protos.google.ai.generativelanguage.v1alpha.IListModelsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListModelsRequest, + | protos.google.ai.generativelanguage.v1alpha.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IModel + >, + ): void; listModels( - request: protos.google.ai.generativelanguage.v1alpha.IListModelsRequest, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListModelsRequest, - protos.google.ai.generativelanguage.v1alpha.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IModel>): void; + request: protos.google.ai.generativelanguage.v1alpha.IListModelsRequest, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListModelsRequest, + | protos.google.ai.generativelanguage.v1alpha.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IModel + >, + ): void; listModels( - request?: protos.google.ai.generativelanguage.v1alpha.IListModelsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListModelsRequest, - protos.google.ai.generativelanguage.v1alpha.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IModel>, - callback?: PaginationCallback< + request?: protos.google.ai.generativelanguage.v1alpha.IListModelsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ai.generativelanguage.v1alpha.IListModelsRequest, - protos.google.ai.generativelanguage.v1alpha.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IModel>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IModel[], - protos.google.ai.generativelanguage.v1alpha.IListModelsRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListModelsResponse - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IModel + >, + callback?: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListModelsRequest, + | protos.google.ai.generativelanguage.v1alpha.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IModel + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IModel[], + protos.google.ai.generativelanguage.v1alpha.IListModelsRequest | null, + protos.google.ai.generativelanguage.v1alpha.IListModelsResponse, + ] + > | 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 || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListModelsRequest, - protos.google.ai.generativelanguage.v1alpha.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IModel>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListModelsRequest, + | protos.google.ai.generativelanguage.v1alpha.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IModel + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listModels values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -986,214 +1339,246 @@ export class ModelServiceClient { this._log.info('listModels request %j', request); return this.innerApiCalls .listModels(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ai.generativelanguage.v1alpha.IModel[], - protos.google.ai.generativelanguage.v1alpha.IListModelsRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListModelsResponse - ]) => { - this._log.info('listModels values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ai.generativelanguage.v1alpha.IModel[], + protos.google.ai.generativelanguage.v1alpha.IListModelsRequest | null, + protos.google.ai.generativelanguage.v1alpha.IListModelsResponse, + ]) => { + this._log.info('listModels values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listModels`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of `Models` to return (per page). - * - * If unspecified, 50 models will be returned per page. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} request.pageToken - * A page token, received from a previous `ListModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListModels` must match - * the call that provided the page token. - * @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.ai.generativelanguage.v1alpha.Model|Model} 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 `listModelsAsync()` - * 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 `listModels`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of `Models` to return (per page). + * + * If unspecified, 50 models will be returned per page. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} request.pageToken + * A page token, received from a previous `ListModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListModels` must match + * the call that provided the page token. + * @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.ai.generativelanguage.v1alpha.Model|Model} 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 `listModelsAsync()` + * 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. + */ listModelsStream( - request?: protos.google.ai.generativelanguage.v1alpha.IListModelsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ai.generativelanguage.v1alpha.IListModelsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listModels stream %j', request); return this.descriptors.page.listModels.createStream( this.innerApiCalls.listModels as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listModels`, 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 {number} request.pageSize - * The maximum number of `Models` to return (per page). - * - * If unspecified, 50 models will be returned per page. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} request.pageToken - * A page token, received from a previous `ListModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListModels` must match - * the call that provided the 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 protos.google.ai.generativelanguage.v1alpha.Model|Model}. 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 include:samples/generated/v1alpha/model_service.list_models.js - * region_tag:generativelanguage_v1alpha_generated_ModelService_ListModels_async - */ + /** + * Equivalent to `listModels`, 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 {number} request.pageSize + * The maximum number of `Models` to return (per page). + * + * If unspecified, 50 models will be returned per page. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} request.pageToken + * A page token, received from a previous `ListModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListModels` must match + * the call that provided the 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 protos.google.ai.generativelanguage.v1alpha.Model|Model}. 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 include:samples/generated/v1alpha/model_service.list_models.js + * region_tag:generativelanguage_v1alpha_generated_ModelService_ListModels_async + */ listModelsAsync( - request?: protos.google.ai.generativelanguage.v1alpha.IListModelsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ai.generativelanguage.v1alpha.IListModelsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listModels iterate %j', request); return this.descriptors.page.listModels.asyncIterate( this.innerApiCalls['listModels'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists created tuned models. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of `TunedModels` to return (per page). - * The service may return fewer tuned models. - * - * If unspecified, at most 10 tuned models will be returned. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListTunedModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListTunedModels` - * must match the call that provided the page token. - * @param {string} [request.filter] - * Optional. A filter is a full text search over the tuned model's description - * and display name. By default, results will not include tuned models shared - * with everyone. - * - * Additional operators: - * - owner:me - * - writers:me - * - readers:me - * - readers:everyone - * - * Examples: - * "owner:me" returns all tuned models to which caller has owner role - * "readers:me" returns all tuned models to which caller has reader role - * "readers:everyone" returns all tuned models that are shared with everyone - * @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.ai.generativelanguage.v1alpha.TunedModel|TunedModel}. - * 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 `listTunedModelsAsync()` - * 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 created tuned models. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of `TunedModels` to return (per page). + * The service may return fewer tuned models. + * + * If unspecified, at most 10 tuned models will be returned. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListTunedModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListTunedModels` + * must match the call that provided the page token. + * @param {string} [request.filter] + * Optional. A filter is a full text search over the tuned model's description + * and display name. By default, results will not include tuned models shared + * with everyone. + * + * Additional operators: + * - owner:me + * - writers:me + * - readers:me + * - readers:everyone + * + * Examples: + * "owner:me" returns all tuned models to which caller has owner role + * "readers:me" returns all tuned models to which caller has reader role + * "readers:everyone" returns all tuned models that are shared with everyone + * @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.ai.generativelanguage.v1alpha.TunedModel|TunedModel}. + * 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 `listTunedModelsAsync()` + * 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. + */ listTunedModels( - request?: protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ITunedModel[], - protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListTunedModelsResponse - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ITunedModel[], + protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest | null, + protos.google.ai.generativelanguage.v1alpha.IListTunedModelsResponse, + ] + >; listTunedModels( - request: protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest, - protos.google.ai.generativelanguage.v1alpha.IListTunedModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.ITunedModel>): void; + request: protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest, + | protos.google.ai.generativelanguage.v1alpha.IListTunedModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.ITunedModel + >, + ): void; listTunedModels( - request: protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest, - protos.google.ai.generativelanguage.v1alpha.IListTunedModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.ITunedModel>): void; + request: protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest, + | protos.google.ai.generativelanguage.v1alpha.IListTunedModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.ITunedModel + >, + ): void; listTunedModels( - request?: protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest, - protos.google.ai.generativelanguage.v1alpha.IListTunedModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.ITunedModel>, - callback?: PaginationCallback< + request?: protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest, - protos.google.ai.generativelanguage.v1alpha.IListTunedModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.ITunedModel>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ITunedModel[], - protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListTunedModelsResponse - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IListTunedModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.ITunedModel + >, + callback?: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest, + | protos.google.ai.generativelanguage.v1alpha.IListTunedModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.ITunedModel + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ITunedModel[], + protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest | null, + protos.google.ai.generativelanguage.v1alpha.IListTunedModelsResponse, + ] + > | 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 || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest, - protos.google.ai.generativelanguage.v1alpha.IListTunedModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.ITunedModel>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest, + | protos.google.ai.generativelanguage.v1alpha.IListTunedModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.ITunedModel + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listTunedModels values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1202,147 +1587,153 @@ export class ModelServiceClient { this._log.info('listTunedModels request %j', request); return this.innerApiCalls .listTunedModels(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ai.generativelanguage.v1alpha.ITunedModel[], - protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListTunedModelsResponse - ]) => { - this._log.info('listTunedModels values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ai.generativelanguage.v1alpha.ITunedModel[], + protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest | null, + protos.google.ai.generativelanguage.v1alpha.IListTunedModelsResponse, + ]) => { + this._log.info('listTunedModels values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listTunedModels`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of `TunedModels` to return (per page). - * The service may return fewer tuned models. - * - * If unspecified, at most 10 tuned models will be returned. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListTunedModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListTunedModels` - * must match the call that provided the page token. - * @param {string} [request.filter] - * Optional. A filter is a full text search over the tuned model's description - * and display name. By default, results will not include tuned models shared - * with everyone. - * - * Additional operators: - * - owner:me - * - writers:me - * - readers:me - * - readers:everyone - * - * Examples: - * "owner:me" returns all tuned models to which caller has owner role - * "readers:me" returns all tuned models to which caller has reader role - * "readers:everyone" returns all tuned models that are shared with everyone - * @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.ai.generativelanguage.v1alpha.TunedModel|TunedModel} 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 `listTunedModelsAsync()` - * 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 `listTunedModels`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of `TunedModels` to return (per page). + * The service may return fewer tuned models. + * + * If unspecified, at most 10 tuned models will be returned. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListTunedModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListTunedModels` + * must match the call that provided the page token. + * @param {string} [request.filter] + * Optional. A filter is a full text search over the tuned model's description + * and display name. By default, results will not include tuned models shared + * with everyone. + * + * Additional operators: + * - owner:me + * - writers:me + * - readers:me + * - readers:everyone + * + * Examples: + * "owner:me" returns all tuned models to which caller has owner role + * "readers:me" returns all tuned models to which caller has reader role + * "readers:everyone" returns all tuned models that are shared with everyone + * @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.ai.generativelanguage.v1alpha.TunedModel|TunedModel} 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 `listTunedModelsAsync()` + * 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. + */ listTunedModelsStream( - request?: protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listTunedModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTunedModels stream %j', request); return this.descriptors.page.listTunedModels.createStream( this.innerApiCalls.listTunedModels as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listTunedModels`, 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 {number} [request.pageSize] - * Optional. The maximum number of `TunedModels` to return (per page). - * The service may return fewer tuned models. - * - * If unspecified, at most 10 tuned models will be returned. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListTunedModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListTunedModels` - * must match the call that provided the page token. - * @param {string} [request.filter] - * Optional. A filter is a full text search over the tuned model's description - * and display name. By default, results will not include tuned models shared - * with everyone. - * - * Additional operators: - * - owner:me - * - writers:me - * - readers:me - * - readers:everyone - * - * Examples: - * "owner:me" returns all tuned models to which caller has owner role - * "readers:me" returns all tuned models to which caller has reader role - * "readers:everyone" returns all tuned models that are shared with everyone - * @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.ai.generativelanguage.v1alpha.TunedModel|TunedModel}. 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 include:samples/generated/v1alpha/model_service.list_tuned_models.js - * region_tag:generativelanguage_v1alpha_generated_ModelService_ListTunedModels_async - */ + /** + * Equivalent to `listTunedModels`, 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 {number} [request.pageSize] + * Optional. The maximum number of `TunedModels` to return (per page). + * The service may return fewer tuned models. + * + * If unspecified, at most 10 tuned models will be returned. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListTunedModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListTunedModels` + * must match the call that provided the page token. + * @param {string} [request.filter] + * Optional. A filter is a full text search over the tuned model's description + * and display name. By default, results will not include tuned models shared + * with everyone. + * + * Additional operators: + * - owner:me + * - writers:me + * - readers:me + * - readers:everyone + * + * Examples: + * "owner:me" returns all tuned models to which caller has owner role + * "readers:me" returns all tuned models to which caller has reader role + * "readers:everyone" returns all tuned models that are shared with everyone + * @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.ai.generativelanguage.v1alpha.TunedModel|TunedModel}. 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 include:samples/generated/v1alpha/model_service.list_tuned_models.js + * region_tag:generativelanguage_v1alpha_generated_ModelService_ListTunedModels_async + */ listTunedModelsAsync( - request?: protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ai.generativelanguage.v1alpha.IListTunedModelsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listTunedModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTunedModels iterate %j', request); return this.descriptors.page.listTunedModels.asyncIterate( this.innerApiCalls['listTunedModels'] as GaxCall, request as {}, - callSettings + callSettings, ) as 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. @@ -1385,22 +1776,22 @@ export class ModelServiceClient { protos.google.longrunning.Operation, protos.google.longrunning.GetOperationRequest, {} | 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); } /** @@ -1435,15 +1826,15 @@ export class ModelServiceClient { */ listOperationsAsync( request: protos.google.longrunning.ListOperationsRequest, - options?: gax.CallOptions + 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); } /** @@ -1477,7 +1868,7 @@ export class ModelServiceClient { * await client.cancelOperation({name: ''}); * ``` */ - cancelOperation( + cancelOperation( request: protos.google.longrunning.CancelOperationRequest, optionsOrCallback?: | gax.CallOptions @@ -1490,25 +1881,24 @@ export class ModelServiceClient { protos.google.longrunning.CancelOperationRequest, protos.google.protobuf.Empty, {} | 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); } - /** * Deletes a long-running operation. This method indicates that the client is * no longer interested in the operation result. It does not cancel the @@ -1547,22 +1937,22 @@ export class ModelServiceClient { protos.google.protobuf.Empty, protos.google.longrunning.DeleteOperationRequest, {} | 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); } @@ -1576,7 +1966,7 @@ export class ModelServiceClient { * @param {string} id * @returns {string} Resource name string. */ - cachedContentPath(id:string) { + cachedContentPath(id: string) { return this.pathTemplates.cachedContentPathTemplate.render({ id: id, }); @@ -1590,7 +1980,8 @@ export class ModelServiceClient { * @returns {string} A string representing the id. */ matchIdFromCachedContentName(cachedContentName: string) { - return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName).id; + return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName) + .id; } /** @@ -1601,7 +1992,7 @@ export class ModelServiceClient { * @param {string} chunk * @returns {string} Resource name string. */ - chunkPath(corpus:string,document:string,chunk:string) { + chunkPath(corpus: string, document: string, chunk: string) { return this.pathTemplates.chunkPathTemplate.render({ corpus: corpus, document: document, @@ -1648,7 +2039,7 @@ export class ModelServiceClient { * @param {string} corpus * @returns {string} Resource name string. */ - corpusPath(corpus:string) { + corpusPath(corpus: string) { return this.pathTemplates.corpusPathTemplate.render({ corpus: corpus, }); @@ -1672,7 +2063,7 @@ export class ModelServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - corpusPermissionsPath(corpus:string,permission:string) { + corpusPermissionsPath(corpus: string, permission: string) { return this.pathTemplates.corpusPermissionsPathTemplate.render({ corpus: corpus, permission: permission, @@ -1687,7 +2078,9 @@ export class ModelServiceClient { * @returns {string} A string representing the corpus. */ matchCorpusFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).corpus; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).corpus; } /** @@ -1698,7 +2091,9 @@ export class ModelServiceClient { * @returns {string} A string representing the permission. */ matchPermissionFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).permission; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).permission; } /** @@ -1708,7 +2103,7 @@ export class ModelServiceClient { * @param {string} document * @returns {string} Resource name string. */ - documentPath(corpus:string,document:string) { + documentPath(corpus: string, document: string) { return this.pathTemplates.documentPathTemplate.render({ corpus: corpus, document: document, @@ -1743,7 +2138,7 @@ export class ModelServiceClient { * @param {string} file * @returns {string} Resource name string. */ - filePath(file:string) { + filePath(file: string) { return this.pathTemplates.filePathTemplate.render({ file: file, }); @@ -1766,7 +2161,7 @@ export class ModelServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -1789,7 +2184,7 @@ export class ModelServiceClient { * @param {string} tuned_model * @returns {string} Resource name string. */ - tunedModelPath(tunedModel:string) { + tunedModelPath(tunedModel: string) { return this.pathTemplates.tunedModelPathTemplate.render({ tuned_model: tunedModel, }); @@ -1803,7 +2198,8 @@ export class ModelServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromTunedModelName(tunedModelName: string) { - return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName).tuned_model; + return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName) + .tuned_model; } /** @@ -1813,7 +2209,7 @@ export class ModelServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - tunedModelPermissionsPath(tunedModel:string,permission:string) { + tunedModelPermissionsPath(tunedModel: string, permission: string) { return this.pathTemplates.tunedModelPermissionsPathTemplate.render({ tuned_model: tunedModel, permission: permission, @@ -1827,8 +2223,12 @@ export class ModelServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the tuned_model. */ - matchTunedModelFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).tuned_model; + matchTunedModelFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).tuned_model; } /** @@ -1838,8 +2238,12 @@ export class ModelServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the permission. */ - matchPermissionFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).permission; + matchPermissionFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).permission; } /** @@ -1850,7 +2254,7 @@ export class ModelServiceClient { */ close(): Promise { if (this.modelServiceStub && !this._terminated) { - return this.modelServiceStub.then(stub => { + return this.modelServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1859,4 +2263,4 @@ export class ModelServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1alpha/permission_service_client.ts b/packages/google-ai-generativelanguage/src/v1alpha/permission_service_client.ts index cb470e55ca21..40f43a7661bd 100644 --- a/packages/google-ai-generativelanguage/src/v1alpha/permission_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1alpha/permission_service_client.ts @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class PermissionServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -57,9 +64,9 @@ export class PermissionServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - permissionServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + permissionServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of PermissionServiceClient. @@ -100,21 +107,42 @@ export class PermissionServiceClient { * const client = new PermissionServiceClient({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 PermissionServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -139,7 +167,7 @@ export class PermissionServiceClient { 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; @@ -153,10 +181,7 @@ export class PermissionServiceClient { } // 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 { @@ -178,31 +203,25 @@ export class PermissionServiceClient { // Create useful helper objects for these. this.pathTemplates = { cachedContentPathTemplate: new this._gaxModule.PathTemplate( - 'cachedContents/{id}' + 'cachedContents/{id}', ), chunkPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}/chunks/{chunk}' - ), - corpusPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}' + 'corpora/{corpus}/documents/{document}/chunks/{chunk}', ), + corpusPathTemplate: new this._gaxModule.PathTemplate('corpora/{corpus}'), corpusPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/permissions/{permission}' + 'corpora/{corpus}/permissions/{permission}', ), documentPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}' - ), - filePathTemplate: new this._gaxModule.PathTemplate( - 'files/{file}' - ), - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' + 'corpora/{corpus}/documents/{document}', ), + filePathTemplate: new this._gaxModule.PathTemplate('files/{file}'), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), tunedModelPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}' + 'tunedModels/{tuned_model}', ), tunedModelPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}/permissions/{permission}' + 'tunedModels/{tuned_model}/permissions/{permission}', ), }; @@ -210,14 +229,20 @@ export class PermissionServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listPermissions: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'permissions') + listPermissions: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'permissions', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1alpha.PermissionService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1alpha.PermissionService', + 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 @@ -248,37 +273,48 @@ export class PermissionServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1alpha.PermissionService. this.permissionServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1alpha.PermissionService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1alpha.PermissionService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1alpha.PermissionService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1alpha + .PermissionService, + 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 permissionServiceStubMethods = - ['createPermission', 'getPermission', 'listPermissions', 'updatePermission', 'deletePermission', 'transferOwnership']; + const permissionServiceStubMethods = [ + 'createPermission', + 'getPermission', + 'listPermissions', + 'updatePermission', + 'deletePermission', + 'transferOwnership', + ]; for (const methodName of permissionServiceStubMethods) { const callPromise = this.permissionServiceStub.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] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -293,8 +329,14 @@ export class PermissionServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -305,8 +347,14 @@ export class PermissionServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -346,8 +394,9 @@ export class PermissionServiceClient { * 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; @@ -358,596 +407,866 @@ export class PermissionServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Create a permission to a specific resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource of the `Permission`. - * Formats: - * `tunedModels/{tuned_model}` - * `corpora/{corpus}` - * @param {google.ai.generativelanguage.v1alpha.Permission} request.permission - * Required. The permission 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.ai.generativelanguage.v1alpha.Permission|Permission}. - * 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/v1alpha/permission_service.create_permission.js - * region_tag:generativelanguage_v1alpha_generated_PermissionService_CreatePermission_async - */ + /** + * Create a permission to a specific resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource of the `Permission`. + * Formats: + * `tunedModels/{tuned_model}` + * `corpora/{corpus}` + * @param {google.ai.generativelanguage.v1alpha.Permission} request.permission + * Required. The permission 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.ai.generativelanguage.v1alpha.Permission|Permission}. + * 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/v1alpha/permission_service.create_permission.js + * region_tag:generativelanguage_v1alpha_generated_PermissionService_CreatePermission_async + */ createPermission( - request?: protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IPermission, + ( + | protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest + | undefined + ), + {} | undefined, + ] + >; createPermission( - request: protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IPermission, + | protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createPermission( - request: protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IPermission, + | protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createPermission( - request?: protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IPermission, + | protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IPermission, + ( + | protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest + | 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('createPermission request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IPermission, + | protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createPermission response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createPermission(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest|undefined, - {}|undefined - ]) => { - this._log.info('createPermission response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createPermission(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IPermission, + ( + | protos.google.ai.generativelanguage.v1alpha.ICreatePermissionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createPermission response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets information about a specific Permission. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the permission. - * - * Formats: - * `tunedModels/{tuned_model}/permissions/{permission}` - * `corpora/{corpus}/permissions/{permission}` - * @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.ai.generativelanguage.v1alpha.Permission|Permission}. - * 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/v1alpha/permission_service.get_permission.js - * region_tag:generativelanguage_v1alpha_generated_PermissionService_GetPermission_async - */ + /** + * Gets information about a specific Permission. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the permission. + * + * Formats: + * `tunedModels/{tuned_model}/permissions/{permission}` + * `corpora/{corpus}/permissions/{permission}` + * @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.ai.generativelanguage.v1alpha.Permission|Permission}. + * 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/v1alpha/permission_service.get_permission.js + * region_tag:generativelanguage_v1alpha_generated_PermissionService_GetPermission_async + */ getPermission( - request?: protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IPermission, + ( + | protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest + | undefined + ), + {} | undefined, + ] + >; getPermission( - request: protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IPermission, + | protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getPermission( - request: protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IPermission, + | protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getPermission( - request?: protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IPermission, + | protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IPermission, + ( + | protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest + | 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('getPermission request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IPermission, + | protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getPermission response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getPermission(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest|undefined, - {}|undefined - ]) => { - this._log.info('getPermission response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getPermission(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IPermission, + ( + | protos.google.ai.generativelanguage.v1alpha.IGetPermissionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getPermission response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the permission. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ai.generativelanguage.v1alpha.Permission} request.permission - * Required. The permission to update. - * - * The permission's `name` field is used to identify the permission to update. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to update. Accepted ones: - * - role (`Permission.role` 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 {@link protos.google.ai.generativelanguage.v1alpha.Permission|Permission}. - * 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/v1alpha/permission_service.update_permission.js - * region_tag:generativelanguage_v1alpha_generated_PermissionService_UpdatePermission_async - */ + /** + * Updates the permission. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ai.generativelanguage.v1alpha.Permission} request.permission + * Required. The permission to update. + * + * The permission's `name` field is used to identify the permission to update. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to update. Accepted ones: + * - role (`Permission.role` 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 {@link protos.google.ai.generativelanguage.v1alpha.Permission|Permission}. + * 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/v1alpha/permission_service.update_permission.js + * region_tag:generativelanguage_v1alpha_generated_PermissionService_UpdatePermission_async + */ updatePermission( - request?: protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IPermission, + ( + | protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest + | undefined + ), + {} | undefined, + ] + >; updatePermission( - request: protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IPermission, + | protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updatePermission( - request: protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IPermission, + | protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updatePermission( - request?: protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IPermission, + | protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IPermission, + ( + | protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest + | 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({ - 'permission.name': request.permission!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'permission.name': request.permission!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updatePermission request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IPermission, + | protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updatePermission response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updatePermission(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.IPermission, - protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest|undefined, - {}|undefined - ]) => { - this._log.info('updatePermission response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updatePermission(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IPermission, + ( + | protos.google.ai.generativelanguage.v1alpha.IUpdatePermissionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updatePermission response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes the permission. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the permission. - * Formats: - * `tunedModels/{tuned_model}/permissions/{permission}` - * `corpora/{corpus}/permissions/{permission}` - * @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/v1alpha/permission_service.delete_permission.js - * region_tag:generativelanguage_v1alpha_generated_PermissionService_DeletePermission_async - */ + /** + * Deletes the permission. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the permission. + * Formats: + * `tunedModels/{tuned_model}/permissions/{permission}` + * `corpora/{corpus}/permissions/{permission}` + * @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/v1alpha/permission_service.delete_permission.js + * region_tag:generativelanguage_v1alpha_generated_PermissionService_DeletePermission_async + */ deletePermission( - request?: protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest + | undefined + ), + {} | undefined, + ] + >; deletePermission( - request: protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deletePermission( - request: protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deletePermission( - request?: protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest + | 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('deletePermission request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deletePermission response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deletePermission(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest|undefined, - {}|undefined - ]) => { - this._log.info('deletePermission response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deletePermission(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.IDeletePermissionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deletePermission response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Transfers ownership of the tuned model. - * This is the only way to change ownership of the tuned model. - * The current owner will be downgraded to writer role. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the tuned model to transfer ownership. - * - * Format: `tunedModels/my-model-id` - * @param {string} request.emailAddress - * Required. The email address of the user to whom the tuned model is being - * transferred to. - * @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.ai.generativelanguage.v1alpha.TransferOwnershipResponse|TransferOwnershipResponse}. - * 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/v1alpha/permission_service.transfer_ownership.js - * region_tag:generativelanguage_v1alpha_generated_PermissionService_TransferOwnership_async - */ + /** + * Transfers ownership of the tuned model. + * This is the only way to change ownership of the tuned model. + * The current owner will be downgraded to writer role. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the tuned model to transfer ownership. + * + * Format: `tunedModels/my-model-id` + * @param {string} request.emailAddress + * Required. The email address of the user to whom the tuned model is being + * transferred to. + * @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.ai.generativelanguage.v1alpha.TransferOwnershipResponse|TransferOwnershipResponse}. + * 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/v1alpha/permission_service.transfer_ownership.js + * region_tag:generativelanguage_v1alpha_generated_PermissionService_TransferOwnership_async + */ transferOwnership( - request?: protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest + | undefined + ), + {} | undefined, + ] + >; transferOwnership( - request: protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipResponse, + | protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest + | null + | undefined, + {} | null | undefined + >, + ): void; transferOwnership( - request: protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipResponse, + | protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest + | null + | undefined, + {} | null | undefined + >, + ): void; transferOwnership( - request?: protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipResponse, + | protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest + | 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('transferOwnership request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipResponse, + | protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('transferOwnership response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.transferOwnership(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest|undefined, - {}|undefined - ]) => { - this._log.info('transferOwnership response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .transferOwnership(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('transferOwnership response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists permissions for the specific resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource of the permissions. - * Formats: - * `tunedModels/{tuned_model}` - * `corpora/{corpus}` - * @param {number} [request.pageSize] - * Optional. The maximum number of `Permission`s to return (per page). - * The service may return fewer permissions. - * - * If unspecified, at most 10 permissions will be returned. - * This method returns at most 1000 permissions per page, even if you pass - * larger page_size. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListPermissions` call. - * - * Provide the `page_token` returned by one request as an argument to the - * next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListPermissions` - * must match the call that provided the page token. - * @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.ai.generativelanguage.v1alpha.Permission|Permission}. - * 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 `listPermissionsAsync()` - * 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 permissions for the specific resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource of the permissions. + * Formats: + * `tunedModels/{tuned_model}` + * `corpora/{corpus}` + * @param {number} [request.pageSize] + * Optional. The maximum number of `Permission`s to return (per page). + * The service may return fewer permissions. + * + * If unspecified, at most 10 permissions will be returned. + * This method returns at most 1000 permissions per page, even if you pass + * larger page_size. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListPermissions` call. + * + * Provide the `page_token` returned by one request as an argument to the + * next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListPermissions` + * must match the call that provided the page token. + * @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.ai.generativelanguage.v1alpha.Permission|Permission}. + * 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 `listPermissionsAsync()` + * 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. + */ listPermissions( - request?: protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IPermission[], - protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListPermissionsResponse - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IPermission[], + protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest | null, + protos.google.ai.generativelanguage.v1alpha.IListPermissionsResponse, + ] + >; listPermissions( - request: protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest, - protos.google.ai.generativelanguage.v1alpha.IListPermissionsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IPermission>): void; + request: protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest, + | protos.google.ai.generativelanguage.v1alpha.IListPermissionsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IPermission + >, + ): void; listPermissions( - request: protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest, - protos.google.ai.generativelanguage.v1alpha.IListPermissionsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IPermission>): void; + request: protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest, + | protos.google.ai.generativelanguage.v1alpha.IListPermissionsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IPermission + >, + ): void; listPermissions( - request?: protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest, - protos.google.ai.generativelanguage.v1alpha.IListPermissionsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IPermission>, - callback?: PaginationCallback< + request?: protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest, - protos.google.ai.generativelanguage.v1alpha.IListPermissionsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IPermission>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IPermission[], - protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListPermissionsResponse - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IListPermissionsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IPermission + >, + callback?: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest, + | protos.google.ai.generativelanguage.v1alpha.IListPermissionsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IPermission + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IPermission[], + protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest | null, + protos.google.ai.generativelanguage.v1alpha.IListPermissionsResponse, + ] + > | 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.ai.generativelanguage.v1alpha.IListPermissionsRequest, - protos.google.ai.generativelanguage.v1alpha.IListPermissionsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IPermission>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest, + | protos.google.ai.generativelanguage.v1alpha.IListPermissionsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IPermission + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listPermissions values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -956,134 +1275,138 @@ export class PermissionServiceClient { this._log.info('listPermissions request %j', request); return this.innerApiCalls .listPermissions(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ai.generativelanguage.v1alpha.IPermission[], - protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListPermissionsResponse - ]) => { - this._log.info('listPermissions values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ai.generativelanguage.v1alpha.IPermission[], + protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest | null, + protos.google.ai.generativelanguage.v1alpha.IListPermissionsResponse, + ]) => { + this._log.info('listPermissions values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listPermissions`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource of the permissions. - * Formats: - * `tunedModels/{tuned_model}` - * `corpora/{corpus}` - * @param {number} [request.pageSize] - * Optional. The maximum number of `Permission`s to return (per page). - * The service may return fewer permissions. - * - * If unspecified, at most 10 permissions will be returned. - * This method returns at most 1000 permissions per page, even if you pass - * larger page_size. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListPermissions` call. - * - * Provide the `page_token` returned by one request as an argument to the - * next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListPermissions` - * must match the call that provided the page token. - * @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.ai.generativelanguage.v1alpha.Permission|Permission} 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 `listPermissionsAsync()` - * 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 `listPermissions`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource of the permissions. + * Formats: + * `tunedModels/{tuned_model}` + * `corpora/{corpus}` + * @param {number} [request.pageSize] + * Optional. The maximum number of `Permission`s to return (per page). + * The service may return fewer permissions. + * + * If unspecified, at most 10 permissions will be returned. + * This method returns at most 1000 permissions per page, even if you pass + * larger page_size. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListPermissions` call. + * + * Provide the `page_token` returned by one request as an argument to the + * next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListPermissions` + * must match the call that provided the page token. + * @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.ai.generativelanguage.v1alpha.Permission|Permission} 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 `listPermissionsAsync()` + * 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. + */ listPermissionsStream( - request?: protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest, + 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['listPermissions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listPermissions stream %j', request); return this.descriptors.page.listPermissions.createStream( this.innerApiCalls.listPermissions as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listPermissions`, 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 of the permissions. - * Formats: - * `tunedModels/{tuned_model}` - * `corpora/{corpus}` - * @param {number} [request.pageSize] - * Optional. The maximum number of `Permission`s to return (per page). - * The service may return fewer permissions. - * - * If unspecified, at most 10 permissions will be returned. - * This method returns at most 1000 permissions per page, even if you pass - * larger page_size. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListPermissions` call. - * - * Provide the `page_token` returned by one request as an argument to the - * next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListPermissions` - * must match the call that provided the 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 protos.google.ai.generativelanguage.v1alpha.Permission|Permission}. 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 include:samples/generated/v1alpha/permission_service.list_permissions.js - * region_tag:generativelanguage_v1alpha_generated_PermissionService_ListPermissions_async - */ + /** + * Equivalent to `listPermissions`, 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 of the permissions. + * Formats: + * `tunedModels/{tuned_model}` + * `corpora/{corpus}` + * @param {number} [request.pageSize] + * Optional. The maximum number of `Permission`s to return (per page). + * The service may return fewer permissions. + * + * If unspecified, at most 10 permissions will be returned. + * This method returns at most 1000 permissions per page, even if you pass + * larger page_size. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListPermissions` call. + * + * Provide the `page_token` returned by one request as an argument to the + * next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListPermissions` + * must match the call that provided the 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 protos.google.ai.generativelanguage.v1alpha.Permission|Permission}. 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 include:samples/generated/v1alpha/permission_service.list_permissions.js + * region_tag:generativelanguage_v1alpha_generated_PermissionService_ListPermissions_async + */ listPermissionsAsync( - request?: protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ai.generativelanguage.v1alpha.IListPermissionsRequest, + 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['listPermissions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listPermissions iterate %j', request); return this.descriptors.page.listPermissions.asyncIterate( this.innerApiCalls['listPermissions'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1096,7 +1419,7 @@ export class PermissionServiceClient { * @param {string} id * @returns {string} Resource name string. */ - cachedContentPath(id:string) { + cachedContentPath(id: string) { return this.pathTemplates.cachedContentPathTemplate.render({ id: id, }); @@ -1110,7 +1433,8 @@ export class PermissionServiceClient { * @returns {string} A string representing the id. */ matchIdFromCachedContentName(cachedContentName: string) { - return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName).id; + return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName) + .id; } /** @@ -1121,7 +1445,7 @@ export class PermissionServiceClient { * @param {string} chunk * @returns {string} Resource name string. */ - chunkPath(corpus:string,document:string,chunk:string) { + chunkPath(corpus: string, document: string, chunk: string) { return this.pathTemplates.chunkPathTemplate.render({ corpus: corpus, document: document, @@ -1168,7 +1492,7 @@ export class PermissionServiceClient { * @param {string} corpus * @returns {string} Resource name string. */ - corpusPath(corpus:string) { + corpusPath(corpus: string) { return this.pathTemplates.corpusPathTemplate.render({ corpus: corpus, }); @@ -1192,7 +1516,7 @@ export class PermissionServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - corpusPermissionsPath(corpus:string,permission:string) { + corpusPermissionsPath(corpus: string, permission: string) { return this.pathTemplates.corpusPermissionsPathTemplate.render({ corpus: corpus, permission: permission, @@ -1207,7 +1531,9 @@ export class PermissionServiceClient { * @returns {string} A string representing the corpus. */ matchCorpusFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).corpus; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).corpus; } /** @@ -1218,7 +1544,9 @@ export class PermissionServiceClient { * @returns {string} A string representing the permission. */ matchPermissionFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).permission; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).permission; } /** @@ -1228,7 +1556,7 @@ export class PermissionServiceClient { * @param {string} document * @returns {string} Resource name string. */ - documentPath(corpus:string,document:string) { + documentPath(corpus: string, document: string) { return this.pathTemplates.documentPathTemplate.render({ corpus: corpus, document: document, @@ -1263,7 +1591,7 @@ export class PermissionServiceClient { * @param {string} file * @returns {string} Resource name string. */ - filePath(file:string) { + filePath(file: string) { return this.pathTemplates.filePathTemplate.render({ file: file, }); @@ -1286,7 +1614,7 @@ export class PermissionServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -1309,7 +1637,7 @@ export class PermissionServiceClient { * @param {string} tuned_model * @returns {string} Resource name string. */ - tunedModelPath(tunedModel:string) { + tunedModelPath(tunedModel: string) { return this.pathTemplates.tunedModelPathTemplate.render({ tuned_model: tunedModel, }); @@ -1323,7 +1651,8 @@ export class PermissionServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromTunedModelName(tunedModelName: string) { - return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName).tuned_model; + return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName) + .tuned_model; } /** @@ -1333,7 +1662,7 @@ export class PermissionServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - tunedModelPermissionsPath(tunedModel:string,permission:string) { + tunedModelPermissionsPath(tunedModel: string, permission: string) { return this.pathTemplates.tunedModelPermissionsPathTemplate.render({ tuned_model: tunedModel, permission: permission, @@ -1347,8 +1676,12 @@ export class PermissionServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the tuned_model. */ - matchTunedModelFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).tuned_model; + matchTunedModelFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).tuned_model; } /** @@ -1358,8 +1691,12 @@ export class PermissionServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the permission. */ - matchPermissionFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).permission; + matchPermissionFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).permission; } /** @@ -1370,7 +1707,7 @@ export class PermissionServiceClient { */ close(): Promise { if (this.permissionServiceStub && !this._terminated) { - return this.permissionServiceStub.then(stub => { + return this.permissionServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1378,4 +1715,4 @@ export class PermissionServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1alpha/prediction_service_client.ts b/packages/google-ai-generativelanguage/src/v1alpha/prediction_service_client.ts index 320ba650df0d..95ce204f1091 100644 --- a/packages/google-ai-generativelanguage/src/v1alpha/prediction_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1alpha/prediction_service_client.ts @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +49,7 @@ export class PredictionServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -57,9 +62,9 @@ export class PredictionServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - predictionServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + predictionServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of PredictionServiceClient. @@ -100,21 +105,42 @@ export class PredictionServiceClient { * const client = new PredictionServiceClient({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 PredictionServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -139,7 +165,7 @@ export class PredictionServiceClient { 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; @@ -153,10 +179,7 @@ export class PredictionServiceClient { } // 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 { @@ -178,38 +201,35 @@ export class PredictionServiceClient { // Create useful helper objects for these. this.pathTemplates = { cachedContentPathTemplate: new this._gaxModule.PathTemplate( - 'cachedContents/{id}' + 'cachedContents/{id}', ), chunkPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}/chunks/{chunk}' - ), - corpusPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}' + 'corpora/{corpus}/documents/{document}/chunks/{chunk}', ), + corpusPathTemplate: new this._gaxModule.PathTemplate('corpora/{corpus}'), corpusPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/permissions/{permission}' + 'corpora/{corpus}/permissions/{permission}', ), documentPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}' - ), - filePathTemplate: new this._gaxModule.PathTemplate( - 'files/{file}' - ), - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' + 'corpora/{corpus}/documents/{document}', ), + filePathTemplate: new this._gaxModule.PathTemplate('files/{file}'), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), tunedModelPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}' + 'tunedModels/{tuned_model}', ), tunedModelPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}/permissions/{permission}' + 'tunedModels/{tuned_model}/permissions/{permission}', ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1alpha.PredictionService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1alpha.PredictionService', + 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 @@ -240,36 +260,41 @@ export class PredictionServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1alpha.PredictionService. this.predictionServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1alpha.PredictionService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1alpha.PredictionService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1alpha.PredictionService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1alpha + .PredictionService, + 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 predictionServiceStubMethods = - ['predict']; + const predictionServiceStubMethods = ['predict']; for (const methodName of predictionServiceStubMethods) { const callPromise = this.predictionServiceStub.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 = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -284,8 +309,14 @@ export class PredictionServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -296,8 +327,14 @@ export class PredictionServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -337,8 +374,9 @@ export class PredictionServiceClient { * 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; @@ -349,101 +387,144 @@ export class PredictionServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Performs a prediction request. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The name of the model for prediction. - * Format: `name=models/{model}`. - * @param {number[]} request.instances - * Required. The instances that are the input to the prediction call. - * @param {google.protobuf.Value} [request.parameters] - * Optional. The parameters that govern the prediction call. - * @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.ai.generativelanguage.v1alpha.PredictResponse|PredictResponse}. - * 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/v1alpha/prediction_service.predict.js - * region_tag:generativelanguage_v1alpha_generated_PredictionService_Predict_async - */ + /** + * Performs a prediction request. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The name of the model for prediction. + * Format: `name=models/{model}`. + * @param {number[]} request.instances + * Required. The instances that are the input to the prediction call. + * @param {google.protobuf.Value} [request.parameters] + * Optional. The parameters that govern the prediction call. + * @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.ai.generativelanguage.v1alpha.PredictResponse|PredictResponse}. + * 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/v1alpha/prediction_service.predict.js + * region_tag:generativelanguage_v1alpha_generated_PredictionService_Predict_async + */ predict( - request?: protos.google.ai.generativelanguage.v1alpha.IPredictRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IPredictResponse, - protos.google.ai.generativelanguage.v1alpha.IPredictRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IPredictRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IPredictResponse, + protos.google.ai.generativelanguage.v1alpha.IPredictRequest | undefined, + {} | undefined, + ] + >; predict( - request: protos.google.ai.generativelanguage.v1alpha.IPredictRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IPredictResponse, - protos.google.ai.generativelanguage.v1alpha.IPredictRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IPredictRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IPredictResponse, + | protos.google.ai.generativelanguage.v1alpha.IPredictRequest + | null + | undefined, + {} | null | undefined + >, + ): void; predict( - request: protos.google.ai.generativelanguage.v1alpha.IPredictRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IPredictResponse, - protos.google.ai.generativelanguage.v1alpha.IPredictRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IPredictRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IPredictResponse, + | protos.google.ai.generativelanguage.v1alpha.IPredictRequest + | null + | undefined, + {} | null | undefined + >, + ): void; predict( - request?: protos.google.ai.generativelanguage.v1alpha.IPredictRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.IPredictResponse, - protos.google.ai.generativelanguage.v1alpha.IPredictRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IPredictRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IPredictResponse, - protos.google.ai.generativelanguage.v1alpha.IPredictRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IPredictResponse, - protos.google.ai.generativelanguage.v1alpha.IPredictRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IPredictRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IPredictResponse, + | protos.google.ai.generativelanguage.v1alpha.IPredictRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IPredictResponse, + protos.google.ai.generativelanguage.v1alpha.IPredictRequest | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('predict request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.IPredictResponse, - protos.google.ai.generativelanguage.v1alpha.IPredictRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IPredictResponse, + | protos.google.ai.generativelanguage.v1alpha.IPredictRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('predict response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.predict(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.IPredictResponse, - protos.google.ai.generativelanguage.v1alpha.IPredictRequest|undefined, - {}|undefined - ]) => { - this._log.info('predict response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .predict(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IPredictResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IPredictRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('predict response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -459,7 +540,7 @@ export class PredictionServiceClient { * @param {string} id * @returns {string} Resource name string. */ - cachedContentPath(id:string) { + cachedContentPath(id: string) { return this.pathTemplates.cachedContentPathTemplate.render({ id: id, }); @@ -473,7 +554,8 @@ export class PredictionServiceClient { * @returns {string} A string representing the id. */ matchIdFromCachedContentName(cachedContentName: string) { - return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName).id; + return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName) + .id; } /** @@ -484,7 +566,7 @@ export class PredictionServiceClient { * @param {string} chunk * @returns {string} Resource name string. */ - chunkPath(corpus:string,document:string,chunk:string) { + chunkPath(corpus: string, document: string, chunk: string) { return this.pathTemplates.chunkPathTemplate.render({ corpus: corpus, document: document, @@ -531,7 +613,7 @@ export class PredictionServiceClient { * @param {string} corpus * @returns {string} Resource name string. */ - corpusPath(corpus:string) { + corpusPath(corpus: string) { return this.pathTemplates.corpusPathTemplate.render({ corpus: corpus, }); @@ -555,7 +637,7 @@ export class PredictionServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - corpusPermissionsPath(corpus:string,permission:string) { + corpusPermissionsPath(corpus: string, permission: string) { return this.pathTemplates.corpusPermissionsPathTemplate.render({ corpus: corpus, permission: permission, @@ -570,7 +652,9 @@ export class PredictionServiceClient { * @returns {string} A string representing the corpus. */ matchCorpusFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).corpus; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).corpus; } /** @@ -581,7 +665,9 @@ export class PredictionServiceClient { * @returns {string} A string representing the permission. */ matchPermissionFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).permission; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).permission; } /** @@ -591,7 +677,7 @@ export class PredictionServiceClient { * @param {string} document * @returns {string} Resource name string. */ - documentPath(corpus:string,document:string) { + documentPath(corpus: string, document: string) { return this.pathTemplates.documentPathTemplate.render({ corpus: corpus, document: document, @@ -626,7 +712,7 @@ export class PredictionServiceClient { * @param {string} file * @returns {string} Resource name string. */ - filePath(file:string) { + filePath(file: string) { return this.pathTemplates.filePathTemplate.render({ file: file, }); @@ -649,7 +735,7 @@ export class PredictionServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -672,7 +758,7 @@ export class PredictionServiceClient { * @param {string} tuned_model * @returns {string} Resource name string. */ - tunedModelPath(tunedModel:string) { + tunedModelPath(tunedModel: string) { return this.pathTemplates.tunedModelPathTemplate.render({ tuned_model: tunedModel, }); @@ -686,7 +772,8 @@ export class PredictionServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromTunedModelName(tunedModelName: string) { - return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName).tuned_model; + return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName) + .tuned_model; } /** @@ -696,7 +783,7 @@ export class PredictionServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - tunedModelPermissionsPath(tunedModel:string,permission:string) { + tunedModelPermissionsPath(tunedModel: string, permission: string) { return this.pathTemplates.tunedModelPermissionsPathTemplate.render({ tuned_model: tunedModel, permission: permission, @@ -710,8 +797,12 @@ export class PredictionServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the tuned_model. */ - matchTunedModelFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).tuned_model; + matchTunedModelFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).tuned_model; } /** @@ -721,8 +812,12 @@ export class PredictionServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the permission. */ - matchPermissionFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).permission; + matchPermissionFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).permission; } /** @@ -733,7 +828,7 @@ export class PredictionServiceClient { */ close(): Promise { if (this.predictionServiceStub && !this._terminated) { - return this.predictionServiceStub.then(stub => { + return this.predictionServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -741,4 +836,4 @@ export class PredictionServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1alpha/retriever_service_client.ts b/packages/google-ai-generativelanguage/src/v1alpha/retriever_service_client.ts index 6f367cd1adaa..5afaf0300246 100644 --- a/packages/google-ai-generativelanguage/src/v1alpha/retriever_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1alpha/retriever_service_client.ts @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class RetrieverServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -57,9 +64,9 @@ export class RetrieverServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - retrieverServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + retrieverServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of RetrieverServiceClient. @@ -100,21 +107,42 @@ export class RetrieverServiceClient { * const client = new RetrieverServiceClient({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 RetrieverServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -139,7 +167,7 @@ export class RetrieverServiceClient { 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; @@ -153,10 +181,7 @@ export class RetrieverServiceClient { } // 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 { @@ -178,31 +203,25 @@ export class RetrieverServiceClient { // Create useful helper objects for these. this.pathTemplates = { cachedContentPathTemplate: new this._gaxModule.PathTemplate( - 'cachedContents/{id}' + 'cachedContents/{id}', ), chunkPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}/chunks/{chunk}' - ), - corpusPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}' + 'corpora/{corpus}/documents/{document}/chunks/{chunk}', ), + corpusPathTemplate: new this._gaxModule.PathTemplate('corpora/{corpus}'), corpusPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/permissions/{permission}' + 'corpora/{corpus}/permissions/{permission}', ), documentPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}' - ), - filePathTemplate: new this._gaxModule.PathTemplate( - 'files/{file}' - ), - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' + 'corpora/{corpus}/documents/{document}', ), + filePathTemplate: new this._gaxModule.PathTemplate('files/{file}'), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), tunedModelPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}' + 'tunedModels/{tuned_model}', ), tunedModelPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}/permissions/{permission}' + 'tunedModels/{tuned_model}/permissions/{permission}', ), }; @@ -210,18 +229,30 @@ export class RetrieverServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listCorpora: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'corpora'), - listDocuments: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'documents'), - listChunks: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'chunks') + listCorpora: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'corpora', + ), + listDocuments: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'documents', + ), + listChunks: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'chunks', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1alpha.RetrieverService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1alpha.RetrieverService', + 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 @@ -252,37 +283,62 @@ export class RetrieverServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1alpha.RetrieverService. this.retrieverServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1alpha.RetrieverService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1alpha.RetrieverService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1alpha.RetrieverService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1alpha + .RetrieverService, + 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 retrieverServiceStubMethods = - ['createCorpus', 'getCorpus', 'updateCorpus', 'deleteCorpus', 'listCorpora', 'queryCorpus', 'createDocument', 'getDocument', 'updateDocument', 'deleteDocument', 'listDocuments', 'queryDocument', 'createChunk', 'batchCreateChunks', 'getChunk', 'updateChunk', 'batchUpdateChunks', 'deleteChunk', 'batchDeleteChunks', 'listChunks']; + const retrieverServiceStubMethods = [ + 'createCorpus', + 'getCorpus', + 'updateCorpus', + 'deleteCorpus', + 'listCorpora', + 'queryCorpus', + 'createDocument', + 'getDocument', + 'updateDocument', + 'deleteDocument', + 'listDocuments', + 'queryDocument', + 'createChunk', + 'batchCreateChunks', + 'getChunk', + 'updateChunk', + 'batchUpdateChunks', + 'deleteChunk', + 'batchDeleteChunks', + 'listChunks', + ]; for (const methodName of retrieverServiceStubMethods) { const callPromise = this.retrieverServiceStub.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] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -297,8 +353,14 @@ export class RetrieverServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -309,8 +371,14 @@ export class RetrieverServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -350,8 +418,9 @@ export class RetrieverServiceClient { * 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; @@ -362,1814 +431,2662 @@ export class RetrieverServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates an empty `Corpus`. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ai.generativelanguage.v1alpha.Corpus} request.corpus - * Required. The `Corpus` 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.ai.generativelanguage.v1alpha.Corpus|Corpus}. - * 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/v1alpha/retriever_service.create_corpus.js - * region_tag:generativelanguage_v1alpha_generated_RetrieverService_CreateCorpus_async - */ + /** + * Creates an empty `Corpus`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ai.generativelanguage.v1alpha.Corpus} request.corpus + * Required. The `Corpus` 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.ai.generativelanguage.v1alpha.Corpus|Corpus}. + * 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/v1alpha/retriever_service.create_corpus.js + * region_tag:generativelanguage_v1alpha_generated_RetrieverService_CreateCorpus_async + */ createCorpus( - request?: protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICorpus, + ( + | protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest + | undefined + ), + {} | undefined, + ] + >; createCorpus( - request: protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ICorpus, + | protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createCorpus( - request: protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ICorpus, + | protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createCorpus( - request?: protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.ICorpus, + | protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICorpus, + ( + | protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest + | 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 || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createCorpus request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.ICorpus, + | protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createCorpus response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createCorpus(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest|undefined, - {}|undefined - ]) => { - this._log.info('createCorpus response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createCorpus(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.ICorpus, + ( + | protos.google.ai.generativelanguage.v1alpha.ICreateCorpusRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createCorpus response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets information about a specific `Corpus`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the `Corpus`. - * Example: `corpora/my-corpus-123` - * @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.ai.generativelanguage.v1alpha.Corpus|Corpus}. - * 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/v1alpha/retriever_service.get_corpus.js - * region_tag:generativelanguage_v1alpha_generated_RetrieverService_GetCorpus_async - */ + /** + * Gets information about a specific `Corpus`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the `Corpus`. + * Example: `corpora/my-corpus-123` + * @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.ai.generativelanguage.v1alpha.Corpus|Corpus}. + * 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/v1alpha/retriever_service.get_corpus.js + * region_tag:generativelanguage_v1alpha_generated_RetrieverService_GetCorpus_async + */ getCorpus( - request?: protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICorpus, + protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest | undefined, + {} | undefined, + ] + >; getCorpus( - request: protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ICorpus, + | protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getCorpus( - request: protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ICorpus, + | protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getCorpus( - request?: protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.ICorpus, + | protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICorpus, + protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest | 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('getCorpus request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.ICorpus, + | protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getCorpus response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getCorpus(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest|undefined, - {}|undefined - ]) => { - this._log.info('getCorpus response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getCorpus(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.ICorpus, + ( + | protos.google.ai.generativelanguage.v1alpha.IGetCorpusRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getCorpus response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a `Corpus`. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ai.generativelanguage.v1alpha.Corpus} request.corpus - * Required. The `Corpus` to update. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to update. - * Currently, this only supports updating `display_name`. - * @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.ai.generativelanguage.v1alpha.Corpus|Corpus}. - * 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/v1alpha/retriever_service.update_corpus.js - * region_tag:generativelanguage_v1alpha_generated_RetrieverService_UpdateCorpus_async - */ + /** + * Updates a `Corpus`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ai.generativelanguage.v1alpha.Corpus} request.corpus + * Required. The `Corpus` to update. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to update. + * Currently, this only supports updating `display_name`. + * @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.ai.generativelanguage.v1alpha.Corpus|Corpus}. + * 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/v1alpha/retriever_service.update_corpus.js + * region_tag:generativelanguage_v1alpha_generated_RetrieverService_UpdateCorpus_async + */ updateCorpus( - request?: protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICorpus, + ( + | protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest + | undefined + ), + {} | undefined, + ] + >; updateCorpus( - request: protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ICorpus, + | protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCorpus( - request: protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ICorpus, + | protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCorpus( - request?: protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.ICorpus, + | protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICorpus, + ( + | protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest + | 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({ - 'corpus.name': request.corpus!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'corpus.name': request.corpus!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateCorpus request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.ICorpus, + | protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateCorpus response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateCorpus(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.ICorpus, - protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateCorpus response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateCorpus(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.ICorpus, + ( + | protos.google.ai.generativelanguage.v1alpha.IUpdateCorpusRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateCorpus response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a `Corpus`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the `Corpus`. - * Example: `corpora/my-corpus-123` - * @param {boolean} [request.force] - * Optional. If set to true, any `Document`s and objects related to this - * `Corpus` will also be deleted. - * - * If false (the default), a `FAILED_PRECONDITION` error will be returned if - * `Corpus` contains any `Document`s. - * @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/v1alpha/retriever_service.delete_corpus.js - * region_tag:generativelanguage_v1alpha_generated_RetrieverService_DeleteCorpus_async - */ + /** + * Deletes a `Corpus`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the `Corpus`. + * Example: `corpora/my-corpus-123` + * @param {boolean} [request.force] + * Optional. If set to true, any `Document`s and objects related to this + * `Corpus` will also be deleted. + * + * If false (the default), a `FAILED_PRECONDITION` error will be returned if + * `Corpus` contains any `Document`s. + * @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/v1alpha/retriever_service.delete_corpus.js + * region_tag:generativelanguage_v1alpha_generated_RetrieverService_DeleteCorpus_async + */ deleteCorpus( - request?: protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest + | undefined + ), + {} | undefined, + ] + >; deleteCorpus( - request: protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteCorpus( - request: protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteCorpus( - request?: protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest + | 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('deleteCorpus request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteCorpus response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteCorpus(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteCorpus response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteCorpus(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.IDeleteCorpusRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteCorpus response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Performs semantic search over a `Corpus`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the `Corpus` to query. - * Example: `corpora/my-corpus-123` - * @param {string} request.query - * Required. Query string to perform semantic search. - * @param {number[]} [request.metadataFilters] - * Optional. Filter for `Chunk` and `Document` metadata. Each `MetadataFilter` - * object should correspond to a unique key. Multiple `MetadataFilter` objects - * are joined by logical "AND"s. - * - * Example query at document level: - * (year >= 2020 OR year < 2010) AND (genre = drama OR genre = action) - * - * `MetadataFilter` object list: - * metadata_filters = [ - * {key = "document.custom_metadata.year" - * conditions = [{int_value = 2020, operation = GREATER_EQUAL}, - * {int_value = 2010, operation = LESS}]}, - * {key = "document.custom_metadata.year" - * conditions = [{int_value = 2020, operation = GREATER_EQUAL}, - * {int_value = 2010, operation = LESS}]}, - * {key = "document.custom_metadata.genre" - * conditions = [{string_value = "drama", operation = EQUAL}, - * {string_value = "action", operation = EQUAL}]}] - * - * Example query at chunk level for a numeric range of values: - * (year > 2015 AND year <= 2020) - * - * `MetadataFilter` object list: - * metadata_filters = [ - * {key = "chunk.custom_metadata.year" - * conditions = [{int_value = 2015, operation = GREATER}]}, - * {key = "chunk.custom_metadata.year" - * conditions = [{int_value = 2020, operation = LESS_EQUAL}]}] - * - * Note: "AND"s for the same key are only supported for numeric values. String - * values only support "OR"s for the same key. - * @param {number} [request.resultsCount] - * Optional. The maximum number of `Chunk`s to return. - * The service may return fewer `Chunk`s. - * - * If unspecified, at most 10 `Chunk`s will be returned. - * The maximum specified result count is 100. - * @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.ai.generativelanguage.v1alpha.QueryCorpusResponse|QueryCorpusResponse}. - * 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/v1alpha/retriever_service.query_corpus.js - * region_tag:generativelanguage_v1alpha_generated_RetrieverService_QueryCorpus_async - */ + /** + * Performs semantic search over a `Corpus`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the `Corpus` to query. + * Example: `corpora/my-corpus-123` + * @param {string} request.query + * Required. Query string to perform semantic search. + * @param {number[]} [request.metadataFilters] + * Optional. Filter for `Chunk` and `Document` metadata. Each `MetadataFilter` + * object should correspond to a unique key. Multiple `MetadataFilter` objects + * are joined by logical "AND"s. + * + * Example query at document level: + * (year >= 2020 OR year < 2010) AND (genre = drama OR genre = action) + * + * `MetadataFilter` object list: + * metadata_filters = [ + * {key = "document.custom_metadata.year" + * conditions = [{int_value = 2020, operation = GREATER_EQUAL}, + * {int_value = 2010, operation = LESS}]}, + * {key = "document.custom_metadata.year" + * conditions = [{int_value = 2020, operation = GREATER_EQUAL}, + * {int_value = 2010, operation = LESS}]}, + * {key = "document.custom_metadata.genre" + * conditions = [{string_value = "drama", operation = EQUAL}, + * {string_value = "action", operation = EQUAL}]}] + * + * Example query at chunk level for a numeric range of values: + * (year > 2015 AND year <= 2020) + * + * `MetadataFilter` object list: + * metadata_filters = [ + * {key = "chunk.custom_metadata.year" + * conditions = [{int_value = 2015, operation = GREATER}]}, + * {key = "chunk.custom_metadata.year" + * conditions = [{int_value = 2020, operation = LESS_EQUAL}]}] + * + * Note: "AND"s for the same key are only supported for numeric values. String + * values only support "OR"s for the same key. + * @param {number} [request.resultsCount] + * Optional. The maximum number of `Chunk`s to return. + * The service may return fewer `Chunk`s. + * + * If unspecified, at most 10 `Chunk`s will be returned. + * The maximum specified result count is 100. + * @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.ai.generativelanguage.v1alpha.QueryCorpusResponse|QueryCorpusResponse}. + * 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/v1alpha/retriever_service.query_corpus.js + * region_tag:generativelanguage_v1alpha_generated_RetrieverService_QueryCorpus_async + */ queryCorpus( - request?: protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IQueryCorpusResponse, - protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IQueryCorpusResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest + | undefined + ), + {} | undefined, + ] + >; queryCorpus( - request: protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IQueryCorpusResponse, - protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IQueryCorpusResponse, + | protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): void; queryCorpus( - request: protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IQueryCorpusResponse, - protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IQueryCorpusResponse, + | protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): void; queryCorpus( - request?: protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.IQueryCorpusResponse, - protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IQueryCorpusResponse, - protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IQueryCorpusResponse, - protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IQueryCorpusResponse, + | protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IQueryCorpusResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest + | 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('queryCorpus request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.IQueryCorpusResponse, - protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IQueryCorpusResponse, + | protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('queryCorpus response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.queryCorpus(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.IQueryCorpusResponse, - protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest|undefined, - {}|undefined - ]) => { - this._log.info('queryCorpus response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .queryCorpus(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IQueryCorpusResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IQueryCorpusRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('queryCorpus response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates an empty `Document`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the `Corpus` where this `Document` will be created. - * Example: `corpora/my-corpus-123` - * @param {google.ai.generativelanguage.v1alpha.Document} request.document - * Required. The `Document` 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.ai.generativelanguage.v1alpha.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/v1alpha/retriever_service.create_document.js - * region_tag:generativelanguage_v1alpha_generated_RetrieverService_CreateDocument_async - */ + /** + * Creates an empty `Document`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the `Corpus` where this `Document` will be created. + * Example: `corpora/my-corpus-123` + * @param {google.ai.generativelanguage.v1alpha.Document} request.document + * Required. The `Document` 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.ai.generativelanguage.v1alpha.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/v1alpha/retriever_service.create_document.js + * region_tag:generativelanguage_v1alpha_generated_RetrieverService_CreateDocument_async + */ createDocument( - request?: protos.google.ai.generativelanguage.v1alpha.ICreateDocumentRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.ICreateDocumentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.ICreateDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IDocument, + ( + | protos.google.ai.generativelanguage.v1alpha.ICreateDocumentRequest + | undefined + ), + {} | undefined, + ] + >; createDocument( - request: protos.google.ai.generativelanguage.v1alpha.ICreateDocumentRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.ICreateDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.ICreateDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IDocument, + | protos.google.ai.generativelanguage.v1alpha.ICreateDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createDocument( - request: protos.google.ai.generativelanguage.v1alpha.ICreateDocumentRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.ICreateDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.ICreateDocumentRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IDocument, + | protos.google.ai.generativelanguage.v1alpha.ICreateDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createDocument( - request?: protos.google.ai.generativelanguage.v1alpha.ICreateDocumentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.ICreateDocumentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.ICreateDocumentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.ICreateDocumentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.ICreateDocumentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.ICreateDocumentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IDocument, + | protos.google.ai.generativelanguage.v1alpha.ICreateDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IDocument, + ( + | protos.google.ai.generativelanguage.v1alpha.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 ?? '', + 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('createDocument request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.ICreateDocumentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IDocument, + | protos.google.ai.generativelanguage.v1alpha.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.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.ICreateDocumentRequest|undefined, - {}|undefined - ]) => { - this._log.info('createDocument response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createDocument(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IDocument, + ( + | protos.google.ai.generativelanguage.v1alpha.ICreateDocumentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createDocument response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets information about a specific `Document`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the `Document` to retrieve. - * Example: `corpora/my-corpus-123/documents/the-doc-abc` - * @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.ai.generativelanguage.v1alpha.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/v1alpha/retriever_service.get_document.js - * region_tag:generativelanguage_v1alpha_generated_RetrieverService_GetDocument_async - */ + /** + * Gets information about a specific `Document`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the `Document` to retrieve. + * Example: `corpora/my-corpus-123/documents/the-doc-abc` + * @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.ai.generativelanguage.v1alpha.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/v1alpha/retriever_service.get_document.js + * region_tag:generativelanguage_v1alpha_generated_RetrieverService_GetDocument_async + */ getDocument( - request?: protos.google.ai.generativelanguage.v1alpha.IGetDocumentRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.IGetDocumentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IGetDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IDocument, + ( + | protos.google.ai.generativelanguage.v1alpha.IGetDocumentRequest + | undefined + ), + {} | undefined, + ] + >; getDocument( - request: protos.google.ai.generativelanguage.v1alpha.IGetDocumentRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.IGetDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGetDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IDocument, + | protos.google.ai.generativelanguage.v1alpha.IGetDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDocument( - request: protos.google.ai.generativelanguage.v1alpha.IGetDocumentRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.IGetDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGetDocumentRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IDocument, + | protos.google.ai.generativelanguage.v1alpha.IGetDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDocument( - request?: protos.google.ai.generativelanguage.v1alpha.IGetDocumentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.IGetDocumentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IGetDocumentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.IGetDocumentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.IGetDocumentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IGetDocumentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IDocument, + | protos.google.ai.generativelanguage.v1alpha.IGetDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IDocument, + ( + | protos.google.ai.generativelanguage.v1alpha.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.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.IGetDocumentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IDocument, + | protos.google.ai.generativelanguage.v1alpha.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.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.IGetDocumentRequest|undefined, - {}|undefined - ]) => { - this._log.info('getDocument response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getDocument(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IDocument, + ( + | protos.google.ai.generativelanguage.v1alpha.IGetDocumentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getDocument response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a `Document`. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ai.generativelanguage.v1alpha.Document} request.document - * Required. The `Document` to update. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to update. - * Currently, this only supports updating `display_name` and - * `custom_metadata`. - * @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.ai.generativelanguage.v1alpha.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/v1alpha/retriever_service.update_document.js - * region_tag:generativelanguage_v1alpha_generated_RetrieverService_UpdateDocument_async - */ + /** + * Updates a `Document`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ai.generativelanguage.v1alpha.Document} request.document + * Required. The `Document` to update. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to update. + * Currently, this only supports updating `display_name` and + * `custom_metadata`. + * @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.ai.generativelanguage.v1alpha.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/v1alpha/retriever_service.update_document.js + * region_tag:generativelanguage_v1alpha_generated_RetrieverService_UpdateDocument_async + */ updateDocument( - request?: protos.google.ai.generativelanguage.v1alpha.IUpdateDocumentRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.IUpdateDocumentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IUpdateDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IDocument, + ( + | protos.google.ai.generativelanguage.v1alpha.IUpdateDocumentRequest + | undefined + ), + {} | undefined, + ] + >; updateDocument( - request: protos.google.ai.generativelanguage.v1alpha.IUpdateDocumentRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.IUpdateDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IUpdateDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IDocument, + | protos.google.ai.generativelanguage.v1alpha.IUpdateDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDocument( - request: protos.google.ai.generativelanguage.v1alpha.IUpdateDocumentRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.IUpdateDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IUpdateDocumentRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IDocument, + | protos.google.ai.generativelanguage.v1alpha.IUpdateDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDocument( - request?: protos.google.ai.generativelanguage.v1alpha.IUpdateDocumentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.IUpdateDocumentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IUpdateDocumentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.IUpdateDocumentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.IUpdateDocumentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IUpdateDocumentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IDocument, + | protos.google.ai.generativelanguage.v1alpha.IUpdateDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IDocument, + ( + | protos.google.ai.generativelanguage.v1alpha.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.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.IUpdateDocumentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IDocument, + | protos.google.ai.generativelanguage.v1alpha.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.ai.generativelanguage.v1alpha.IDocument, - protos.google.ai.generativelanguage.v1alpha.IUpdateDocumentRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateDocument response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateDocument(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IDocument, + ( + | protos.google.ai.generativelanguage.v1alpha.IUpdateDocumentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateDocument response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * 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. - * Example: `corpora/my-corpus-123/documents/the-doc-abc` - * @param {boolean} [request.force] - * Optional. If set to true, any `Chunk`s and objects related to this - * `Document` will also be deleted. - * - * If false (the default), a `FAILED_PRECONDITION` error will be returned if - * `Document` contains any `Chunk`s. - * @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/v1alpha/retriever_service.delete_document.js - * region_tag:generativelanguage_v1alpha_generated_RetrieverService_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. + * Example: `corpora/my-corpus-123/documents/the-doc-abc` + * @param {boolean} [request.force] + * Optional. If set to true, any `Chunk`s and objects related to this + * `Document` will also be deleted. + * + * If false (the default), a `FAILED_PRECONDITION` error will be returned if + * `Document` contains any `Chunk`s. + * @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/v1alpha/retriever_service.delete_document.js + * region_tag:generativelanguage_v1alpha_generated_RetrieverService_DeleteDocument_async + */ deleteDocument( - request?: protos.google.ai.generativelanguage.v1alpha.IDeleteDocumentRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteDocumentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IDeleteDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.IDeleteDocumentRequest + | undefined + ), + {} | undefined, + ] + >; deleteDocument( - request: protos.google.ai.generativelanguage.v1alpha.IDeleteDocumentRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IDeleteDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeleteDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteDocument( - request: protos.google.ai.generativelanguage.v1alpha.IDeleteDocumentRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IDeleteDocumentRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeleteDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteDocument( - request?: protos.google.ai.generativelanguage.v1alpha.IDeleteDocumentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteDocumentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IDeleteDocumentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteDocumentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteDocumentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IDeleteDocumentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeleteDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.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.ai.generativelanguage.v1alpha.IDeleteDocumentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.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.ai.generativelanguage.v1alpha.IDeleteDocumentRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteDocument response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteDocument(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.IDeleteDocumentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteDocument response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Performs semantic search over a `Document`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the `Document` to query. - * Example: `corpora/my-corpus-123/documents/the-doc-abc` - * @param {string} request.query - * Required. Query string to perform semantic search. - * @param {number} [request.resultsCount] - * Optional. The maximum number of `Chunk`s to return. - * The service may return fewer `Chunk`s. - * - * If unspecified, at most 10 `Chunk`s will be returned. - * The maximum specified result count is 100. - * @param {number[]} [request.metadataFilters] - * Optional. Filter for `Chunk` metadata. Each `MetadataFilter` object should - * correspond to a unique key. Multiple `MetadataFilter` objects are joined by - * logical "AND"s. - * - * Note: `Document`-level filtering is not supported for this request because - * a `Document` name is already specified. - * - * Example query: - * (year >= 2020 OR year < 2010) AND (genre = drama OR genre = action) - * - * `MetadataFilter` object list: - * metadata_filters = [ - * {key = "chunk.custom_metadata.year" - * conditions = [{int_value = 2020, operation = GREATER_EQUAL}, - * {int_value = 2010, operation = LESS}}, - * {key = "chunk.custom_metadata.genre" - * conditions = [{string_value = "drama", operation = EQUAL}, - * {string_value = "action", operation = EQUAL}}] - * - * Example query for a numeric range of values: - * (year > 2015 AND year <= 2020) - * - * `MetadataFilter` object list: - * metadata_filters = [ - * {key = "chunk.custom_metadata.year" - * conditions = [{int_value = 2015, operation = GREATER}]}, - * {key = "chunk.custom_metadata.year" - * conditions = [{int_value = 2020, operation = LESS_EQUAL}]}] - * - * Note: "AND"s for the same key are only supported for numeric values. String - * values only support "OR"s for the same key. - * @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.ai.generativelanguage.v1alpha.QueryDocumentResponse|QueryDocumentResponse}. - * 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/v1alpha/retriever_service.query_document.js - * region_tag:generativelanguage_v1alpha_generated_RetrieverService_QueryDocument_async - */ + /** + * Performs semantic search over a `Document`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the `Document` to query. + * Example: `corpora/my-corpus-123/documents/the-doc-abc` + * @param {string} request.query + * Required. Query string to perform semantic search. + * @param {number} [request.resultsCount] + * Optional. The maximum number of `Chunk`s to return. + * The service may return fewer `Chunk`s. + * + * If unspecified, at most 10 `Chunk`s will be returned. + * The maximum specified result count is 100. + * @param {number[]} [request.metadataFilters] + * Optional. Filter for `Chunk` metadata. Each `MetadataFilter` object should + * correspond to a unique key. Multiple `MetadataFilter` objects are joined by + * logical "AND"s. + * + * Note: `Document`-level filtering is not supported for this request because + * a `Document` name is already specified. + * + * Example query: + * (year >= 2020 OR year < 2010) AND (genre = drama OR genre = action) + * + * `MetadataFilter` object list: + * metadata_filters = [ + * {key = "chunk.custom_metadata.year" + * conditions = [{int_value = 2020, operation = GREATER_EQUAL}, + * {int_value = 2010, operation = LESS}}, + * {key = "chunk.custom_metadata.genre" + * conditions = [{string_value = "drama", operation = EQUAL}, + * {string_value = "action", operation = EQUAL}}] + * + * Example query for a numeric range of values: + * (year > 2015 AND year <= 2020) + * + * `MetadataFilter` object list: + * metadata_filters = [ + * {key = "chunk.custom_metadata.year" + * conditions = [{int_value = 2015, operation = GREATER}]}, + * {key = "chunk.custom_metadata.year" + * conditions = [{int_value = 2020, operation = LESS_EQUAL}]}] + * + * Note: "AND"s for the same key are only supported for numeric values. String + * values only support "OR"s for the same key. + * @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.ai.generativelanguage.v1alpha.QueryDocumentResponse|QueryDocumentResponse}. + * 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/v1alpha/retriever_service.query_document.js + * region_tag:generativelanguage_v1alpha_generated_RetrieverService_QueryDocument_async + */ queryDocument( - request?: protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IQueryDocumentResponse, - protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IQueryDocumentResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest + | undefined + ), + {} | undefined, + ] + >; queryDocument( - request: protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IQueryDocumentResponse, - protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IQueryDocumentResponse, + | protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; queryDocument( - request: protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IQueryDocumentResponse, - protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IQueryDocumentResponse, + | protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; queryDocument( - request?: protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.IQueryDocumentResponse, - protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IQueryDocumentResponse, - protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IQueryDocumentResponse, - protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IQueryDocumentResponse, + | protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IQueryDocumentResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest + | 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('queryDocument request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.IQueryDocumentResponse, - protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IQueryDocumentResponse, + | protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('queryDocument response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.queryDocument(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.IQueryDocumentResponse, - protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest|undefined, - {}|undefined - ]) => { - this._log.info('queryDocument response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .queryDocument(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IQueryDocumentResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IQueryDocumentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('queryDocument response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a `Chunk`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the `Document` where this `Chunk` will be created. - * Example: `corpora/my-corpus-123/documents/the-doc-abc` - * @param {google.ai.generativelanguage.v1alpha.Chunk} request.chunk - * Required. The `Chunk` 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.ai.generativelanguage.v1alpha.Chunk|Chunk}. - * 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/v1alpha/retriever_service.create_chunk.js - * region_tag:generativelanguage_v1alpha_generated_RetrieverService_CreateChunk_async - */ + /** + * Creates a `Chunk`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the `Document` where this `Chunk` will be created. + * Example: `corpora/my-corpus-123/documents/the-doc-abc` + * @param {google.ai.generativelanguage.v1alpha.Chunk} request.chunk + * Required. The `Chunk` 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.ai.generativelanguage.v1alpha.Chunk|Chunk}. + * 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/v1alpha/retriever_service.create_chunk.js + * region_tag:generativelanguage_v1alpha_generated_RetrieverService_CreateChunk_async + */ createChunk( - request?: protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IChunk, + ( + | protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest + | undefined + ), + {} | undefined, + ] + >; createChunk( - request: protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IChunk, + | protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createChunk( - request: protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IChunk, + | protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createChunk( - request?: protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IChunk, + | protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IChunk, + ( + | protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest + | 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('createChunk request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IChunk, + | protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createChunk response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createChunk(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest|undefined, - {}|undefined - ]) => { - this._log.info('createChunk response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createChunk(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IChunk, + ( + | protos.google.ai.generativelanguage.v1alpha.ICreateChunkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createChunk response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Batch create `Chunk`s. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} [request.parent] - * Optional. The name of the `Document` where this batch of `Chunk`s will be - * created. The parent field in every `CreateChunkRequest` must match this - * value. Example: `corpora/my-corpus-123/documents/the-doc-abc` - * @param {number[]} request.requests - * Required. The request messages specifying the `Chunk`s to create. - * A maximum of 100 `Chunk`s can be created in a batch. - * @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.ai.generativelanguage.v1alpha.BatchCreateChunksResponse|BatchCreateChunksResponse}. - * 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/v1alpha/retriever_service.batch_create_chunks.js - * region_tag:generativelanguage_v1alpha_generated_RetrieverService_BatchCreateChunks_async - */ + /** + * Batch create `Chunk`s. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} [request.parent] + * Optional. The name of the `Document` where this batch of `Chunk`s will be + * created. The parent field in every `CreateChunkRequest` must match this + * value. Example: `corpora/my-corpus-123/documents/the-doc-abc` + * @param {number[]} request.requests + * Required. The request messages specifying the `Chunk`s to create. + * A maximum of 100 `Chunk`s can be created in a batch. + * @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.ai.generativelanguage.v1alpha.BatchCreateChunksResponse|BatchCreateChunksResponse}. + * 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/v1alpha/retriever_service.batch_create_chunks.js + * region_tag:generativelanguage_v1alpha_generated_RetrieverService_BatchCreateChunks_async + */ batchCreateChunks( - request?: protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest + | undefined + ), + {} | undefined, + ] + >; batchCreateChunks( - request: protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksResponse, + | protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchCreateChunks( - request: protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksResponse, + | protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchCreateChunks( - request?: protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksResponse, + | protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest + | 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('batchCreateChunks request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksResponse, + | protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchCreateChunks response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.batchCreateChunks(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest|undefined, - {}|undefined - ]) => { - this._log.info('batchCreateChunks response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchCreateChunks(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchCreateChunks response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets information about a specific `Chunk`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the `Chunk` to retrieve. - * Example: `corpora/my-corpus-123/documents/the-doc-abc/chunks/some-chunk` - * @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.ai.generativelanguage.v1alpha.Chunk|Chunk}. - * 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/v1alpha/retriever_service.get_chunk.js - * region_tag:generativelanguage_v1alpha_generated_RetrieverService_GetChunk_async - */ + /** + * Gets information about a specific `Chunk`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the `Chunk` to retrieve. + * Example: `corpora/my-corpus-123/documents/the-doc-abc/chunks/some-chunk` + * @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.ai.generativelanguage.v1alpha.Chunk|Chunk}. + * 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/v1alpha/retriever_service.get_chunk.js + * region_tag:generativelanguage_v1alpha_generated_RetrieverService_GetChunk_async + */ getChunk( - request?: protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IChunk, + protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest | undefined, + {} | undefined, + ] + >; getChunk( - request: protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IChunk, + | protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getChunk( - request: protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IChunk, + | protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getChunk( - request?: protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IChunk, + | protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IChunk, + protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest | 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('getChunk request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IChunk, + | protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getChunk response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getChunk(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest|undefined, - {}|undefined - ]) => { - this._log.info('getChunk response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getChunk(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IChunk, + ( + | protos.google.ai.generativelanguage.v1alpha.IGetChunkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getChunk response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a `Chunk`. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ai.generativelanguage.v1alpha.Chunk} request.chunk - * Required. The `Chunk` to update. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to update. - * Currently, this only supports updating `custom_metadata` and `data`. - * @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.ai.generativelanguage.v1alpha.Chunk|Chunk}. - * 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/v1alpha/retriever_service.update_chunk.js - * region_tag:generativelanguage_v1alpha_generated_RetrieverService_UpdateChunk_async - */ + /** + * Updates a `Chunk`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ai.generativelanguage.v1alpha.Chunk} request.chunk + * Required. The `Chunk` to update. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to update. + * Currently, this only supports updating `custom_metadata` and `data`. + * @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.ai.generativelanguage.v1alpha.Chunk|Chunk}. + * 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/v1alpha/retriever_service.update_chunk.js + * region_tag:generativelanguage_v1alpha_generated_RetrieverService_UpdateChunk_async + */ updateChunk( - request?: protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IChunk, + ( + | protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest + | undefined + ), + {} | undefined, + ] + >; updateChunk( - request: protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IChunk, + | protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateChunk( - request: protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IChunk, + | protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateChunk( - request?: protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IChunk, + | protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IChunk, + ( + | protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest + | 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({ - 'chunk.name': request.chunk!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'chunk.name': request.chunk!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateChunk request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IChunk, + | protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateChunk response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateChunk(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.IChunk, - protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateChunk response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateChunk(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IChunk, + ( + | protos.google.ai.generativelanguage.v1alpha.IUpdateChunkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateChunk response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Batch update `Chunk`s. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} [request.parent] - * Optional. The name of the `Document` containing the `Chunk`s to update. - * The parent field in every `UpdateChunkRequest` must match this value. - * Example: `corpora/my-corpus-123/documents/the-doc-abc` - * @param {number[]} request.requests - * Required. The request messages specifying the `Chunk`s to update. - * A maximum of 100 `Chunk`s can be updated in a batch. - * @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.ai.generativelanguage.v1alpha.BatchUpdateChunksResponse|BatchUpdateChunksResponse}. - * 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/v1alpha/retriever_service.batch_update_chunks.js - * region_tag:generativelanguage_v1alpha_generated_RetrieverService_BatchUpdateChunks_async - */ + /** + * Batch update `Chunk`s. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} [request.parent] + * Optional. The name of the `Document` containing the `Chunk`s to update. + * The parent field in every `UpdateChunkRequest` must match this value. + * Example: `corpora/my-corpus-123/documents/the-doc-abc` + * @param {number[]} request.requests + * Required. The request messages specifying the `Chunk`s to update. + * A maximum of 100 `Chunk`s can be updated in a batch. + * @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.ai.generativelanguage.v1alpha.BatchUpdateChunksResponse|BatchUpdateChunksResponse}. + * 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/v1alpha/retriever_service.batch_update_chunks.js + * region_tag:generativelanguage_v1alpha_generated_RetrieverService_BatchUpdateChunks_async + */ batchUpdateChunks( - request?: protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest + | undefined + ), + {} | undefined, + ] + >; batchUpdateChunks( - request: protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksResponse, + | protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchUpdateChunks( - request: protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksResponse, + | protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchUpdateChunks( - request?: protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksResponse, + | protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest + | 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('batchUpdateChunks request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksResponse, + | protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchUpdateChunks response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.batchUpdateChunks(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest|undefined, - {}|undefined - ]) => { - this._log.info('batchUpdateChunks response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchUpdateChunks(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchUpdateChunks response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a `Chunk`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the `Chunk` to delete. - * Example: `corpora/my-corpus-123/documents/the-doc-abc/chunks/some-chunk` - * @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/v1alpha/retriever_service.delete_chunk.js - * region_tag:generativelanguage_v1alpha_generated_RetrieverService_DeleteChunk_async - */ + /** + * Deletes a `Chunk`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the `Chunk` to delete. + * Example: `corpora/my-corpus-123/documents/the-doc-abc/chunks/some-chunk` + * @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/v1alpha/retriever_service.delete_chunk.js + * region_tag:generativelanguage_v1alpha_generated_RetrieverService_DeleteChunk_async + */ deleteChunk( - request?: protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest + | undefined + ), + {} | undefined, + ] + >; deleteChunk( - request: protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteChunk( - request: protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteChunk( - request?: protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest + | 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('deleteChunk request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteChunk response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteChunk(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteChunk response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteChunk(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.IDeleteChunkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteChunk response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Batch delete `Chunk`s. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} [request.parent] - * Optional. The name of the `Document` containing the `Chunk`s to delete. - * The parent field in every `DeleteChunkRequest` must match this value. - * Example: `corpora/my-corpus-123/documents/the-doc-abc` - * @param {number[]} request.requests - * Required. The request messages specifying the `Chunk`s to delete. - * @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/v1alpha/retriever_service.batch_delete_chunks.js - * region_tag:generativelanguage_v1alpha_generated_RetrieverService_BatchDeleteChunks_async - */ + /** + * Batch delete `Chunk`s. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} [request.parent] + * Optional. The name of the `Document` containing the `Chunk`s to delete. + * The parent field in every `DeleteChunkRequest` must match this value. + * Example: `corpora/my-corpus-123/documents/the-doc-abc` + * @param {number[]} request.requests + * Required. The request messages specifying the `Chunk`s to delete. + * @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/v1alpha/retriever_service.batch_delete_chunks.js + * region_tag:generativelanguage_v1alpha_generated_RetrieverService_BatchDeleteChunks_async + */ batchDeleteChunks( - request?: protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest + | undefined + ), + {} | undefined, + ] + >; batchDeleteChunks( - request: protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchDeleteChunks( - request: protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchDeleteChunks( - request?: protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest + | 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('batchDeleteChunks request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchDeleteChunks response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.batchDeleteChunks(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest|undefined, - {}|undefined - ]) => { - this._log.info('batchDeleteChunks response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchDeleteChunks(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1alpha.IBatchDeleteChunksRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchDeleteChunks response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all `Corpora` owned by the user. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of `Corpora` to return (per page). - * The service may return fewer `Corpora`. - * - * If unspecified, at most 10 `Corpora` will be returned. - * The maximum size limit is 20 `Corpora` per page. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListCorpora` call. - * - * Provide the `next_page_token` returned in the response as an argument to - * the next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListCorpora` - * must match the call that provided the page token. - * @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.ai.generativelanguage.v1alpha.Corpus|Corpus}. - * 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 `listCorporaAsync()` - * 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 `Corpora` owned by the user. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of `Corpora` to return (per page). + * The service may return fewer `Corpora`. + * + * If unspecified, at most 10 `Corpora` will be returned. + * The maximum size limit is 20 `Corpora` per page. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListCorpora` call. + * + * Provide the `next_page_token` returned in the response as an argument to + * the next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListCorpora` + * must match the call that provided the page token. + * @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.ai.generativelanguage.v1alpha.Corpus|Corpus}. + * 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 `listCorporaAsync()` + * 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. + */ listCorpora( - request?: protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICorpus[], - protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListCorporaResponse - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICorpus[], + protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest | null, + protos.google.ai.generativelanguage.v1alpha.IListCorporaResponse, + ] + >; listCorpora( - request: protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest, - protos.google.ai.generativelanguage.v1alpha.IListCorporaResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.ICorpus>): void; + request: protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest, + | protos.google.ai.generativelanguage.v1alpha.IListCorporaResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.ICorpus + >, + ): void; listCorpora( - request: protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest, - protos.google.ai.generativelanguage.v1alpha.IListCorporaResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.ICorpus>): void; + request: protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest, + | protos.google.ai.generativelanguage.v1alpha.IListCorporaResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.ICorpus + >, + ): void; listCorpora( - request?: protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest, - protos.google.ai.generativelanguage.v1alpha.IListCorporaResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.ICorpus>, - callback?: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest, - protos.google.ai.generativelanguage.v1alpha.IListCorporaResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.ICorpus>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICorpus[], - protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListCorporaResponse - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IListCorporaResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.ICorpus + >, + callback?: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest, + | protos.google.ai.generativelanguage.v1alpha.IListCorporaResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.ICorpus + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICorpus[], + protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest | null, + protos.google.ai.generativelanguage.v1alpha.IListCorporaResponse, + ] + > | 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 || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest, - protos.google.ai.generativelanguage.v1alpha.IListCorporaResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.ICorpus>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest, + | protos.google.ai.generativelanguage.v1alpha.IListCorporaResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.ICorpus + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listCorpora values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -2178,206 +3095,237 @@ export class RetrieverServiceClient { this._log.info('listCorpora request %j', request); return this.innerApiCalls .listCorpora(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ai.generativelanguage.v1alpha.ICorpus[], - protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListCorporaResponse - ]) => { - this._log.info('listCorpora values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ai.generativelanguage.v1alpha.ICorpus[], + protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest | null, + protos.google.ai.generativelanguage.v1alpha.IListCorporaResponse, + ]) => { + this._log.info('listCorpora values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listCorpora`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of `Corpora` to return (per page). - * The service may return fewer `Corpora`. - * - * If unspecified, at most 10 `Corpora` will be returned. - * The maximum size limit is 20 `Corpora` per page. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListCorpora` call. - * - * Provide the `next_page_token` returned in the response as an argument to - * the next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListCorpora` - * must match the call that provided the page token. - * @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.ai.generativelanguage.v1alpha.Corpus|Corpus} 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 `listCorporaAsync()` - * 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 `listCorpora`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of `Corpora` to return (per page). + * The service may return fewer `Corpora`. + * + * If unspecified, at most 10 `Corpora` will be returned. + * The maximum size limit is 20 `Corpora` per page. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListCorpora` call. + * + * Provide the `next_page_token` returned in the response as an argument to + * the next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListCorpora` + * must match the call that provided the page token. + * @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.ai.generativelanguage.v1alpha.Corpus|Corpus} 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 `listCorporaAsync()` + * 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. + */ listCorporaStream( - request?: protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listCorpora']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCorpora stream %j', request); return this.descriptors.page.listCorpora.createStream( this.innerApiCalls.listCorpora as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listCorpora`, 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 {number} [request.pageSize] - * Optional. The maximum number of `Corpora` to return (per page). - * The service may return fewer `Corpora`. - * - * If unspecified, at most 10 `Corpora` will be returned. - * The maximum size limit is 20 `Corpora` per page. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListCorpora` call. - * - * Provide the `next_page_token` returned in the response as an argument to - * the next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListCorpora` - * must match the call that provided the 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 protos.google.ai.generativelanguage.v1alpha.Corpus|Corpus}. 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 include:samples/generated/v1alpha/retriever_service.list_corpora.js - * region_tag:generativelanguage_v1alpha_generated_RetrieverService_ListCorpora_async - */ + /** + * Equivalent to `listCorpora`, 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 {number} [request.pageSize] + * Optional. The maximum number of `Corpora` to return (per page). + * The service may return fewer `Corpora`. + * + * If unspecified, at most 10 `Corpora` will be returned. + * The maximum size limit is 20 `Corpora` per page. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListCorpora` call. + * + * Provide the `next_page_token` returned in the response as an argument to + * the next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListCorpora` + * must match the call that provided the 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 protos.google.ai.generativelanguage.v1alpha.Corpus|Corpus}. 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 include:samples/generated/v1alpha/retriever_service.list_corpora.js + * region_tag:generativelanguage_v1alpha_generated_RetrieverService_ListCorpora_async + */ listCorporaAsync( - request?: protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ai.generativelanguage.v1alpha.IListCorporaRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listCorpora']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCorpora iterate %j', request); return this.descriptors.page.listCorpora.asyncIterate( this.innerApiCalls['listCorpora'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists all `Document`s in a `Corpus`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the `Corpus` containing `Document`s. - * Example: `corpora/my-corpus-123` - * @param {number} [request.pageSize] - * Optional. The maximum number of `Document`s to return (per page). - * The service may return fewer `Document`s. - * - * If unspecified, at most 10 `Document`s will be returned. - * The maximum size limit is 20 `Document`s per page. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListDocuments` call. - * - * Provide the `next_page_token` returned in the response as an argument to - * the next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListDocuments` - * must match the call that provided the page token. - * @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.ai.generativelanguage.v1alpha.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 all `Document`s in a `Corpus`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the `Corpus` containing `Document`s. + * Example: `corpora/my-corpus-123` + * @param {number} [request.pageSize] + * Optional. The maximum number of `Document`s to return (per page). + * The service may return fewer `Document`s. + * + * If unspecified, at most 10 `Document`s will be returned. + * The maximum size limit is 20 `Document`s per page. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListDocuments` call. + * + * Provide the `next_page_token` returned in the response as an argument to + * the next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListDocuments` + * must match the call that provided the page token. + * @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.ai.generativelanguage.v1alpha.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.ai.generativelanguage.v1alpha.IListDocumentsRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IDocument[], - protos.google.ai.generativelanguage.v1alpha.IListDocumentsRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListDocumentsResponse - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IListDocumentsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IDocument[], + protos.google.ai.generativelanguage.v1alpha.IListDocumentsRequest | null, + protos.google.ai.generativelanguage.v1alpha.IListDocumentsResponse, + ] + >; listDocuments( - request: protos.google.ai.generativelanguage.v1alpha.IListDocumentsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListDocumentsRequest, - protos.google.ai.generativelanguage.v1alpha.IListDocumentsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IDocument>): void; + request: protos.google.ai.generativelanguage.v1alpha.IListDocumentsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListDocumentsRequest, + | protos.google.ai.generativelanguage.v1alpha.IListDocumentsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IDocument + >, + ): void; listDocuments( - request: protos.google.ai.generativelanguage.v1alpha.IListDocumentsRequest, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListDocumentsRequest, - protos.google.ai.generativelanguage.v1alpha.IListDocumentsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IDocument>): void; + request: protos.google.ai.generativelanguage.v1alpha.IListDocumentsRequest, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListDocumentsRequest, + | protos.google.ai.generativelanguage.v1alpha.IListDocumentsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IDocument + >, + ): void; listDocuments( - request?: protos.google.ai.generativelanguage.v1alpha.IListDocumentsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.ai.generativelanguage.v1alpha.IListDocumentsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ai.generativelanguage.v1alpha.IListDocumentsRequest, - protos.google.ai.generativelanguage.v1alpha.IListDocumentsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IDocument>, - callback?: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListDocumentsRequest, - protos.google.ai.generativelanguage.v1alpha.IListDocumentsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IDocument>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IDocument[], - protos.google.ai.generativelanguage.v1alpha.IListDocumentsRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListDocumentsResponse - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IListDocumentsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IDocument + >, + callback?: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListDocumentsRequest, + | protos.google.ai.generativelanguage.v1alpha.IListDocumentsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IDocument + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IDocument[], + protos.google.ai.generativelanguage.v1alpha.IListDocumentsRequest | null, + protos.google.ai.generativelanguage.v1alpha.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 ?? '', + 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.ai.generativelanguage.v1alpha.IListDocumentsRequest, - protos.google.ai.generativelanguage.v1alpha.IListDocumentsResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IDocument>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListDocumentsRequest, + | protos.google.ai.generativelanguage.v1alpha.IListDocumentsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IDocument + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listDocuments values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -2386,222 +3334,251 @@ export class RetrieverServiceClient { this._log.info('listDocuments request %j', request); return this.innerApiCalls .listDocuments(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ai.generativelanguage.v1alpha.IDocument[], - protos.google.ai.generativelanguage.v1alpha.IListDocumentsRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListDocumentsResponse - ]) => { - this._log.info('listDocuments values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ai.generativelanguage.v1alpha.IDocument[], + protos.google.ai.generativelanguage.v1alpha.IListDocumentsRequest | null, + protos.google.ai.generativelanguage.v1alpha.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 name of the `Corpus` containing `Document`s. - * Example: `corpora/my-corpus-123` - * @param {number} [request.pageSize] - * Optional. The maximum number of `Document`s to return (per page). - * The service may return fewer `Document`s. - * - * If unspecified, at most 10 `Document`s will be returned. - * The maximum size limit is 20 `Document`s per page. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListDocuments` call. - * - * Provide the `next_page_token` returned in the response as an argument to - * the next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListDocuments` - * must match the call that provided the page token. - * @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.ai.generativelanguage.v1alpha.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 name of the `Corpus` containing `Document`s. + * Example: `corpora/my-corpus-123` + * @param {number} [request.pageSize] + * Optional. The maximum number of `Document`s to return (per page). + * The service may return fewer `Document`s. + * + * If unspecified, at most 10 `Document`s will be returned. + * The maximum size limit is 20 `Document`s per page. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListDocuments` call. + * + * Provide the `next_page_token` returned in the response as an argument to + * the next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListDocuments` + * must match the call that provided the page token. + * @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.ai.generativelanguage.v1alpha.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.ai.generativelanguage.v1alpha.IListDocumentsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ai.generativelanguage.v1alpha.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 ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); 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, request, - callSettings + callSettings, ); } -/** - * 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 name of the `Corpus` containing `Document`s. - * Example: `corpora/my-corpus-123` - * @param {number} [request.pageSize] - * Optional. The maximum number of `Document`s to return (per page). - * The service may return fewer `Document`s. - * - * If unspecified, at most 10 `Document`s will be returned. - * The maximum size limit is 20 `Document`s per page. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListDocuments` call. - * - * Provide the `next_page_token` returned in the response as an argument to - * the next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListDocuments` - * must match the call that provided the 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 protos.google.ai.generativelanguage.v1alpha.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 include:samples/generated/v1alpha/retriever_service.list_documents.js - * region_tag:generativelanguage_v1alpha_generated_RetrieverService_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 name of the `Corpus` containing `Document`s. + * Example: `corpora/my-corpus-123` + * @param {number} [request.pageSize] + * Optional. The maximum number of `Document`s to return (per page). + * The service may return fewer `Document`s. + * + * If unspecified, at most 10 `Document`s will be returned. + * The maximum size limit is 20 `Document`s per page. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListDocuments` call. + * + * Provide the `next_page_token` returned in the response as an argument to + * the next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListDocuments` + * must match the call that provided the 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 protos.google.ai.generativelanguage.v1alpha.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 include:samples/generated/v1alpha/retriever_service.list_documents.js + * region_tag:generativelanguage_v1alpha_generated_RetrieverService_ListDocuments_async + */ listDocumentsAsync( - request?: protos.google.ai.generativelanguage.v1alpha.IListDocumentsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ai.generativelanguage.v1alpha.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 ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); 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, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists all `Chunk`s in a `Document`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the `Document` containing `Chunk`s. - * Example: `corpora/my-corpus-123/documents/the-doc-abc` - * @param {number} [request.pageSize] - * Optional. The maximum number of `Chunk`s to return (per page). - * The service may return fewer `Chunk`s. - * - * If unspecified, at most 10 `Chunk`s will be returned. - * The maximum size limit is 100 `Chunk`s per page. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListChunks` call. - * - * Provide the `next_page_token` returned in the response as an argument to - * the next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListChunks` - * must match the call that provided the page token. - * @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.ai.generativelanguage.v1alpha.Chunk|Chunk}. - * 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 `listChunksAsync()` - * 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 `Chunk`s in a `Document`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the `Document` containing `Chunk`s. + * Example: `corpora/my-corpus-123/documents/the-doc-abc` + * @param {number} [request.pageSize] + * Optional. The maximum number of `Chunk`s to return (per page). + * The service may return fewer `Chunk`s. + * + * If unspecified, at most 10 `Chunk`s will be returned. + * The maximum size limit is 100 `Chunk`s per page. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListChunks` call. + * + * Provide the `next_page_token` returned in the response as an argument to + * the next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListChunks` + * must match the call that provided the page token. + * @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.ai.generativelanguage.v1alpha.Chunk|Chunk}. + * 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 `listChunksAsync()` + * 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. + */ listChunks( - request?: protos.google.ai.generativelanguage.v1alpha.IListChunksRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IChunk[], - protos.google.ai.generativelanguage.v1alpha.IListChunksRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListChunksResponse - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IListChunksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IChunk[], + protos.google.ai.generativelanguage.v1alpha.IListChunksRequest | null, + protos.google.ai.generativelanguage.v1alpha.IListChunksResponse, + ] + >; listChunks( - request: protos.google.ai.generativelanguage.v1alpha.IListChunksRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListChunksRequest, - protos.google.ai.generativelanguage.v1alpha.IListChunksResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IChunk>): void; + request: protos.google.ai.generativelanguage.v1alpha.IListChunksRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListChunksRequest, + | protos.google.ai.generativelanguage.v1alpha.IListChunksResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IChunk + >, + ): void; listChunks( - request: protos.google.ai.generativelanguage.v1alpha.IListChunksRequest, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListChunksRequest, - protos.google.ai.generativelanguage.v1alpha.IListChunksResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IChunk>): void; + request: protos.google.ai.generativelanguage.v1alpha.IListChunksRequest, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListChunksRequest, + | protos.google.ai.generativelanguage.v1alpha.IListChunksResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IChunk + >, + ): void; listChunks( - request?: protos.google.ai.generativelanguage.v1alpha.IListChunksRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.ai.generativelanguage.v1alpha.IListChunksRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ai.generativelanguage.v1alpha.IListChunksRequest, - protos.google.ai.generativelanguage.v1alpha.IListChunksResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IChunk>, - callback?: PaginationCallback< - protos.google.ai.generativelanguage.v1alpha.IListChunksRequest, - protos.google.ai.generativelanguage.v1alpha.IListChunksResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IChunk>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IChunk[], - protos.google.ai.generativelanguage.v1alpha.IListChunksRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListChunksResponse - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IListChunksResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IChunk + >, + callback?: PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListChunksRequest, + | protos.google.ai.generativelanguage.v1alpha.IListChunksResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IChunk + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IChunk[], + protos.google.ai.generativelanguage.v1alpha.IListChunksRequest | null, + protos.google.ai.generativelanguage.v1alpha.IListChunksResponse, + ] + > | 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.ai.generativelanguage.v1alpha.IListChunksRequest, - protos.google.ai.generativelanguage.v1alpha.IListChunksResponse|null|undefined, - protos.google.ai.generativelanguage.v1alpha.IChunk>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.ai.generativelanguage.v1alpha.IListChunksRequest, + | protos.google.ai.generativelanguage.v1alpha.IListChunksResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1alpha.IChunk + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listChunks values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -2610,128 +3587,132 @@ export class RetrieverServiceClient { this._log.info('listChunks request %j', request); return this.innerApiCalls .listChunks(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ai.generativelanguage.v1alpha.IChunk[], - protos.google.ai.generativelanguage.v1alpha.IListChunksRequest|null, - protos.google.ai.generativelanguage.v1alpha.IListChunksResponse - ]) => { - this._log.info('listChunks values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ai.generativelanguage.v1alpha.IChunk[], + protos.google.ai.generativelanguage.v1alpha.IListChunksRequest | null, + protos.google.ai.generativelanguage.v1alpha.IListChunksResponse, + ]) => { + this._log.info('listChunks values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listChunks`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the `Document` containing `Chunk`s. - * Example: `corpora/my-corpus-123/documents/the-doc-abc` - * @param {number} [request.pageSize] - * Optional. The maximum number of `Chunk`s to return (per page). - * The service may return fewer `Chunk`s. - * - * If unspecified, at most 10 `Chunk`s will be returned. - * The maximum size limit is 100 `Chunk`s per page. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListChunks` call. - * - * Provide the `next_page_token` returned in the response as an argument to - * the next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListChunks` - * must match the call that provided the page token. - * @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.ai.generativelanguage.v1alpha.Chunk|Chunk} 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 `listChunksAsync()` - * 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 `listChunks`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the `Document` containing `Chunk`s. + * Example: `corpora/my-corpus-123/documents/the-doc-abc` + * @param {number} [request.pageSize] + * Optional. The maximum number of `Chunk`s to return (per page). + * The service may return fewer `Chunk`s. + * + * If unspecified, at most 10 `Chunk`s will be returned. + * The maximum size limit is 100 `Chunk`s per page. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListChunks` call. + * + * Provide the `next_page_token` returned in the response as an argument to + * the next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListChunks` + * must match the call that provided the page token. + * @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.ai.generativelanguage.v1alpha.Chunk|Chunk} 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 `listChunksAsync()` + * 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. + */ listChunksStream( - request?: protos.google.ai.generativelanguage.v1alpha.IListChunksRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ai.generativelanguage.v1alpha.IListChunksRequest, + 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['listChunks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listChunks stream %j', request); return this.descriptors.page.listChunks.createStream( this.innerApiCalls.listChunks as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listChunks`, 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 name of the `Document` containing `Chunk`s. - * Example: `corpora/my-corpus-123/documents/the-doc-abc` - * @param {number} [request.pageSize] - * Optional. The maximum number of `Chunk`s to return (per page). - * The service may return fewer `Chunk`s. - * - * If unspecified, at most 10 `Chunk`s will be returned. - * The maximum size limit is 100 `Chunk`s per page. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListChunks` call. - * - * Provide the `next_page_token` returned in the response as an argument to - * the next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListChunks` - * must match the call that provided the 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 protos.google.ai.generativelanguage.v1alpha.Chunk|Chunk}. 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 include:samples/generated/v1alpha/retriever_service.list_chunks.js - * region_tag:generativelanguage_v1alpha_generated_RetrieverService_ListChunks_async - */ + /** + * Equivalent to `listChunks`, 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 name of the `Document` containing `Chunk`s. + * Example: `corpora/my-corpus-123/documents/the-doc-abc` + * @param {number} [request.pageSize] + * Optional. The maximum number of `Chunk`s to return (per page). + * The service may return fewer `Chunk`s. + * + * If unspecified, at most 10 `Chunk`s will be returned. + * The maximum size limit is 100 `Chunk`s per page. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListChunks` call. + * + * Provide the `next_page_token` returned in the response as an argument to + * the next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListChunks` + * must match the call that provided the 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 protos.google.ai.generativelanguage.v1alpha.Chunk|Chunk}. 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 include:samples/generated/v1alpha/retriever_service.list_chunks.js + * region_tag:generativelanguage_v1alpha_generated_RetrieverService_ListChunks_async + */ listChunksAsync( - request?: protos.google.ai.generativelanguage.v1alpha.IListChunksRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ai.generativelanguage.v1alpha.IListChunksRequest, + 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['listChunks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listChunks iterate %j', request); return this.descriptors.page.listChunks.asyncIterate( this.innerApiCalls['listChunks'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -2744,7 +3725,7 @@ export class RetrieverServiceClient { * @param {string} id * @returns {string} Resource name string. */ - cachedContentPath(id:string) { + cachedContentPath(id: string) { return this.pathTemplates.cachedContentPathTemplate.render({ id: id, }); @@ -2758,7 +3739,8 @@ export class RetrieverServiceClient { * @returns {string} A string representing the id. */ matchIdFromCachedContentName(cachedContentName: string) { - return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName).id; + return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName) + .id; } /** @@ -2769,7 +3751,7 @@ export class RetrieverServiceClient { * @param {string} chunk * @returns {string} Resource name string. */ - chunkPath(corpus:string,document:string,chunk:string) { + chunkPath(corpus: string, document: string, chunk: string) { return this.pathTemplates.chunkPathTemplate.render({ corpus: corpus, document: document, @@ -2816,7 +3798,7 @@ export class RetrieverServiceClient { * @param {string} corpus * @returns {string} Resource name string. */ - corpusPath(corpus:string) { + corpusPath(corpus: string) { return this.pathTemplates.corpusPathTemplate.render({ corpus: corpus, }); @@ -2840,7 +3822,7 @@ export class RetrieverServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - corpusPermissionsPath(corpus:string,permission:string) { + corpusPermissionsPath(corpus: string, permission: string) { return this.pathTemplates.corpusPermissionsPathTemplate.render({ corpus: corpus, permission: permission, @@ -2855,7 +3837,9 @@ export class RetrieverServiceClient { * @returns {string} A string representing the corpus. */ matchCorpusFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).corpus; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).corpus; } /** @@ -2866,7 +3850,9 @@ export class RetrieverServiceClient { * @returns {string} A string representing the permission. */ matchPermissionFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).permission; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).permission; } /** @@ -2876,7 +3862,7 @@ export class RetrieverServiceClient { * @param {string} document * @returns {string} Resource name string. */ - documentPath(corpus:string,document:string) { + documentPath(corpus: string, document: string) { return this.pathTemplates.documentPathTemplate.render({ corpus: corpus, document: document, @@ -2911,7 +3897,7 @@ export class RetrieverServiceClient { * @param {string} file * @returns {string} Resource name string. */ - filePath(file:string) { + filePath(file: string) { return this.pathTemplates.filePathTemplate.render({ file: file, }); @@ -2934,7 +3920,7 @@ export class RetrieverServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -2957,7 +3943,7 @@ export class RetrieverServiceClient { * @param {string} tuned_model * @returns {string} Resource name string. */ - tunedModelPath(tunedModel:string) { + tunedModelPath(tunedModel: string) { return this.pathTemplates.tunedModelPathTemplate.render({ tuned_model: tunedModel, }); @@ -2971,7 +3957,8 @@ export class RetrieverServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromTunedModelName(tunedModelName: string) { - return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName).tuned_model; + return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName) + .tuned_model; } /** @@ -2981,7 +3968,7 @@ export class RetrieverServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - tunedModelPermissionsPath(tunedModel:string,permission:string) { + tunedModelPermissionsPath(tunedModel: string, permission: string) { return this.pathTemplates.tunedModelPermissionsPathTemplate.render({ tuned_model: tunedModel, permission: permission, @@ -2995,8 +3982,12 @@ export class RetrieverServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the tuned_model. */ - matchTunedModelFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).tuned_model; + matchTunedModelFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).tuned_model; } /** @@ -3006,8 +3997,12 @@ export class RetrieverServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the permission. */ - matchPermissionFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).permission; + matchPermissionFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).permission; } /** @@ -3018,7 +4013,7 @@ export class RetrieverServiceClient { */ close(): Promise { if (this.retrieverServiceStub && !this._terminated) { - return this.retrieverServiceStub.then(stub => { + return this.retrieverServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -3026,4 +4021,4 @@ export class RetrieverServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1alpha/text_service_client.ts b/packages/google-ai-generativelanguage/src/v1alpha/text_service_client.ts index 2b1beb805834..ef397e3ec7ec 100644 --- a/packages/google-ai-generativelanguage/src/v1alpha/text_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1alpha/text_service_client.ts @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +52,7 @@ export class TextServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -60,9 +65,9 @@ export class TextServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - textServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + textServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of TextServiceClient. @@ -103,21 +108,42 @@ export class TextServiceClient { * const client = new TextServiceClient({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 TextServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -142,7 +168,7 @@ export class TextServiceClient { 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; @@ -156,10 +182,7 @@ export class TextServiceClient { } // 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 { @@ -181,38 +204,35 @@ export class TextServiceClient { // Create useful helper objects for these. this.pathTemplates = { cachedContentPathTemplate: new this._gaxModule.PathTemplate( - 'cachedContents/{id}' + 'cachedContents/{id}', ), chunkPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}/chunks/{chunk}' - ), - corpusPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}' + 'corpora/{corpus}/documents/{document}/chunks/{chunk}', ), + corpusPathTemplate: new this._gaxModule.PathTemplate('corpora/{corpus}'), corpusPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/permissions/{permission}' + 'corpora/{corpus}/permissions/{permission}', ), documentPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}' - ), - filePathTemplate: new this._gaxModule.PathTemplate( - 'files/{file}' - ), - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' + 'corpora/{corpus}/documents/{document}', ), + filePathTemplate: new this._gaxModule.PathTemplate('files/{file}'), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), tunedModelPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}' + 'tunedModels/{tuned_model}', ), tunedModelPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}/permissions/{permission}' + 'tunedModels/{tuned_model}/permissions/{permission}', ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1alpha.TextService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1alpha.TextService', + 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 @@ -243,36 +263,46 @@ export class TextServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1alpha.TextService. this.textServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1alpha.TextService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1alpha.TextService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1alpha.TextService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1alpha + .TextService, + 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 textServiceStubMethods = - ['generateText', 'embedText', 'batchEmbedText', 'countTextTokens']; + const textServiceStubMethods = [ + 'generateText', + 'embedText', + 'batchEmbedText', + 'countTextTokens', + ]; for (const methodName of textServiceStubMethods) { const callPromise = this.textServiceStub.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 = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -287,8 +317,14 @@ export class TextServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -299,8 +335,14 @@ export class TextServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -340,8 +382,9 @@ export class TextServiceClient { * 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; @@ -352,468 +395,658 @@ export class TextServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Generates a response from the model given an input message. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The name of the `Model` or `TunedModel` to use for generating the - * completion. - * Examples: - * models/text-bison-001 - * tunedModels/sentence-translator-u3b7m - * @param {google.ai.generativelanguage.v1alpha.TextPrompt} request.prompt - * Required. The free-form input text given to the model as a prompt. - * - * Given a prompt, the model will generate a TextCompletion response it - * predicts as the completion of the input text. - * @param {number} [request.temperature] - * Optional. Controls the randomness of the output. - * Note: The default value varies by model, see the `Model.temperature` - * attribute of the `Model` returned the `getModel` function. - * - * Values can range from [0.0,1.0], - * inclusive. A value closer to 1.0 will produce responses that are more - * varied and creative, while a value closer to 0.0 will typically result in - * more straightforward responses from the model. - * @param {number} [request.candidateCount] - * Optional. Number of generated responses to return. - * - * This value must be between [1, 8], inclusive. If unset, this will default - * to 1. - * @param {number} [request.maxOutputTokens] - * Optional. The maximum number of tokens to include in a candidate. - * - * If unset, this will default to output_token_limit specified in the `Model` - * specification. - * @param {number} [request.topP] - * Optional. The maximum cumulative probability of tokens to consider when - * sampling. - * - * The model uses combined Top-k and nucleus sampling. - * - * Tokens are sorted based on their assigned probabilities so that only the - * most likely tokens are considered. Top-k sampling directly limits the - * maximum number of tokens to consider, while Nucleus sampling limits number - * of tokens based on the cumulative probability. - * - * Note: The default value varies by model, see the `Model.top_p` - * attribute of the `Model` returned the `getModel` function. - * @param {number} [request.topK] - * Optional. The maximum number of tokens to consider when sampling. - * - * The model uses combined Top-k and nucleus sampling. - * - * Top-k sampling considers the set of `top_k` most probable tokens. - * Defaults to 40. - * - * Note: The default value varies by model, see the `Model.top_k` - * attribute of the `Model` returned the `getModel` function. - * @param {number[]} [request.safetySettings] - * Optional. A list of unique `SafetySetting` instances for blocking unsafe - * content. - * - * that will be enforced on the `GenerateTextRequest.prompt` and - * `GenerateTextResponse.candidates`. There should not be more than one - * setting for each `SafetyCategory` type. The API will block any prompts and - * responses that fail to meet the thresholds set by these settings. This list - * overrides the default settings for each `SafetyCategory` specified in the - * safety_settings. If there is no `SafetySetting` for a given - * `SafetyCategory` provided in the list, the API will use the default safety - * setting for that category. Harm categories HARM_CATEGORY_DEROGATORY, - * HARM_CATEGORY_TOXICITY, HARM_CATEGORY_VIOLENCE, HARM_CATEGORY_SEXUAL, - * HARM_CATEGORY_MEDICAL, HARM_CATEGORY_DANGEROUS are supported in text - * service. - * @param {string[]} request.stopSequences - * The set of character sequences (up to 5) that will stop output generation. - * If specified, the API will stop at the first appearance of a stop - * sequence. The stop sequence will not be included as part of 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.ai.generativelanguage.v1alpha.GenerateTextResponse|GenerateTextResponse}. - * 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/v1alpha/text_service.generate_text.js - * region_tag:generativelanguage_v1alpha_generated_TextService_GenerateText_async - */ + /** + * Generates a response from the model given an input message. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The name of the `Model` or `TunedModel` to use for generating the + * completion. + * Examples: + * models/text-bison-001 + * tunedModels/sentence-translator-u3b7m + * @param {google.ai.generativelanguage.v1alpha.TextPrompt} request.prompt + * Required. The free-form input text given to the model as a prompt. + * + * Given a prompt, the model will generate a TextCompletion response it + * predicts as the completion of the input text. + * @param {number} [request.temperature] + * Optional. Controls the randomness of the output. + * Note: The default value varies by model, see the `Model.temperature` + * attribute of the `Model` returned the `getModel` function. + * + * Values can range from [0.0,1.0], + * inclusive. A value closer to 1.0 will produce responses that are more + * varied and creative, while a value closer to 0.0 will typically result in + * more straightforward responses from the model. + * @param {number} [request.candidateCount] + * Optional. Number of generated responses to return. + * + * This value must be between [1, 8], inclusive. If unset, this will default + * to 1. + * @param {number} [request.maxOutputTokens] + * Optional. The maximum number of tokens to include in a candidate. + * + * If unset, this will default to output_token_limit specified in the `Model` + * specification. + * @param {number} [request.topP] + * Optional. The maximum cumulative probability of tokens to consider when + * sampling. + * + * The model uses combined Top-k and nucleus sampling. + * + * Tokens are sorted based on their assigned probabilities so that only the + * most likely tokens are considered. Top-k sampling directly limits the + * maximum number of tokens to consider, while Nucleus sampling limits number + * of tokens based on the cumulative probability. + * + * Note: The default value varies by model, see the `Model.top_p` + * attribute of the `Model` returned the `getModel` function. + * @param {number} [request.topK] + * Optional. The maximum number of tokens to consider when sampling. + * + * The model uses combined Top-k and nucleus sampling. + * + * Top-k sampling considers the set of `top_k` most probable tokens. + * Defaults to 40. + * + * Note: The default value varies by model, see the `Model.top_k` + * attribute of the `Model` returned the `getModel` function. + * @param {number[]} [request.safetySettings] + * Optional. A list of unique `SafetySetting` instances for blocking unsafe + * content. + * + * that will be enforced on the `GenerateTextRequest.prompt` and + * `GenerateTextResponse.candidates`. There should not be more than one + * setting for each `SafetyCategory` type. The API will block any prompts and + * responses that fail to meet the thresholds set by these settings. This list + * overrides the default settings for each `SafetyCategory` specified in the + * safety_settings. If there is no `SafetySetting` for a given + * `SafetyCategory` provided in the list, the API will use the default safety + * setting for that category. Harm categories HARM_CATEGORY_DEROGATORY, + * HARM_CATEGORY_TOXICITY, HARM_CATEGORY_VIOLENCE, HARM_CATEGORY_SEXUAL, + * HARM_CATEGORY_MEDICAL, HARM_CATEGORY_DANGEROUS are supported in text + * service. + * @param {string[]} request.stopSequences + * The set of character sequences (up to 5) that will stop output generation. + * If specified, the API will stop at the first appearance of a stop + * sequence. The stop sequence will not be included as part of 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.ai.generativelanguage.v1alpha.GenerateTextResponse|GenerateTextResponse}. + * 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/v1alpha/text_service.generate_text.js + * region_tag:generativelanguage_v1alpha_generated_TextService_GenerateText_async + */ generateText( - request?: protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IGenerateTextResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest + | undefined + ), + {} | undefined, + ] + >; generateText( - request: protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IGenerateTextResponse, + | protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateText( - request: protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IGenerateTextResponse, + | protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateText( - request?: protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IGenerateTextResponse, + | protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IGenerateTextResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('generateText request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IGenerateTextResponse, + | protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('generateText response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.generateText(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest|undefined, - {}|undefined - ]) => { - this._log.info('generateText response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .generateText(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IGenerateTextResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IGenerateTextRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('generateText response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Generates an embedding from the model given an input message. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The model name to use with the format model=models/{model}. - * @param {string} [request.text] - * Optional. The free-form input text that the model will turn into an - * embedding. - * @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.ai.generativelanguage.v1alpha.EmbedTextResponse|EmbedTextResponse}. - * 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/v1alpha/text_service.embed_text.js - * region_tag:generativelanguage_v1alpha_generated_TextService_EmbedText_async - */ + /** + * Generates an embedding from the model given an input message. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The model name to use with the format model=models/{model}. + * @param {string} [request.text] + * Optional. The free-form input text that the model will turn into an + * embedding. + * @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.ai.generativelanguage.v1alpha.EmbedTextResponse|EmbedTextResponse}. + * 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/v1alpha/text_service.embed_text.js + * region_tag:generativelanguage_v1alpha_generated_TextService_EmbedText_async + */ embedText( - request?: protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IEmbedTextResponse, + protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest | undefined, + {} | undefined, + ] + >; embedText( - request: protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IEmbedTextResponse, + | protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; embedText( - request: protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IEmbedTextResponse, + | protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; embedText( - request?: protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IEmbedTextResponse, + | protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IEmbedTextResponse, + protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('embedText request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IEmbedTextResponse, + | protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('embedText response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.embedText(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest|undefined, - {}|undefined - ]) => { - this._log.info('embedText response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .embedText(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IEmbedTextResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IEmbedTextRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('embedText response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Generates multiple embeddings from the model given input text in a - * synchronous call. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The name of the `Model` to use for generating the embedding. - * Examples: - * models/embedding-gecko-001 - * @param {string[]} [request.texts] - * Optional. The free-form input texts that the model will turn into an - * embedding. The current limit is 100 texts, over which an error will be - * thrown. - * @param {number[]} [request.requests] - * Optional. Embed requests for the batch. Only one of `texts` or `requests` - * can be set. - * @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.ai.generativelanguage.v1alpha.BatchEmbedTextResponse|BatchEmbedTextResponse}. - * 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/v1alpha/text_service.batch_embed_text.js - * region_tag:generativelanguage_v1alpha_generated_TextService_BatchEmbedText_async - */ + /** + * Generates multiple embeddings from the model given input text in a + * synchronous call. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The name of the `Model` to use for generating the embedding. + * Examples: + * models/embedding-gecko-001 + * @param {string[]} [request.texts] + * Optional. The free-form input texts that the model will turn into an + * embedding. The current limit is 100 texts, over which an error will be + * thrown. + * @param {number[]} [request.requests] + * Optional. Embed requests for the batch. Only one of `texts` or `requests` + * can be set. + * @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.ai.generativelanguage.v1alpha.BatchEmbedTextResponse|BatchEmbedTextResponse}. + * 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/v1alpha/text_service.batch_embed_text.js + * region_tag:generativelanguage_v1alpha_generated_TextService_BatchEmbedText_async + */ batchEmbedText( - request?: protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest + | undefined + ), + {} | undefined, + ] + >; batchEmbedText( - request: protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextResponse, + | protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchEmbedText( - request: protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextResponse, + | protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchEmbedText( - request?: protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextResponse, + | protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('batchEmbedText request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextResponse, + | protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchEmbedText response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.batchEmbedText(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest|undefined, - {}|undefined - ]) => { - this._log.info('batchEmbedText response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchEmbedText(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchEmbedText response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Runs a model's tokenizer on a text and returns the token count. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The model's resource name. This serves as an ID for the Model to - * use. - * - * This name should match a model name returned by the `ListModels` method. - * - * Format: `models/{model}` - * @param {google.ai.generativelanguage.v1alpha.TextPrompt} request.prompt - * Required. The free-form input text given to the model as a prompt. - * @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.ai.generativelanguage.v1alpha.CountTextTokensResponse|CountTextTokensResponse}. - * 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/v1alpha/text_service.count_text_tokens.js - * region_tag:generativelanguage_v1alpha_generated_TextService_CountTextTokens_async - */ + /** + * Runs a model's tokenizer on a text and returns the token count. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The model's resource name. This serves as an ID for the Model to + * use. + * + * This name should match a model name returned by the `ListModels` method. + * + * Format: `models/{model}` + * @param {google.ai.generativelanguage.v1alpha.TextPrompt} request.prompt + * Required. The free-form input text given to the model as a prompt. + * @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.ai.generativelanguage.v1alpha.CountTextTokensResponse|CountTextTokensResponse}. + * 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/v1alpha/text_service.count_text_tokens.js + * region_tag:generativelanguage_v1alpha_generated_TextService_CountTextTokens_async + */ countTextTokens( - request?: protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICountTextTokensResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest + | undefined + ), + {} | undefined, + ] + >; countTextTokens( - request: protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ICountTextTokensResponse, + | protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): void; countTextTokens( - request: protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1alpha.ICountTextTokensResponse, + | protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): void; countTextTokens( - request?: protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1alpha.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1alpha.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1alpha.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1alpha.ICountTextTokensResponse, + | protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1alpha.ICountTextTokensResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('countTextTokens request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1alpha.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1alpha.ICountTextTokensResponse, + | protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('countTextTokens response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.countTextTokens(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1alpha.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest|undefined, - {}|undefined - ]) => { - this._log.info('countTextTokens response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .countTextTokens(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1alpha.ICountTextTokensResponse, + ( + | protos.google.ai.generativelanguage.v1alpha.ICountTextTokensRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('countTextTokens response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -829,7 +1062,7 @@ export class TextServiceClient { * @param {string} id * @returns {string} Resource name string. */ - cachedContentPath(id:string) { + cachedContentPath(id: string) { return this.pathTemplates.cachedContentPathTemplate.render({ id: id, }); @@ -843,7 +1076,8 @@ export class TextServiceClient { * @returns {string} A string representing the id. */ matchIdFromCachedContentName(cachedContentName: string) { - return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName).id; + return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName) + .id; } /** @@ -854,7 +1088,7 @@ export class TextServiceClient { * @param {string} chunk * @returns {string} Resource name string. */ - chunkPath(corpus:string,document:string,chunk:string) { + chunkPath(corpus: string, document: string, chunk: string) { return this.pathTemplates.chunkPathTemplate.render({ corpus: corpus, document: document, @@ -901,7 +1135,7 @@ export class TextServiceClient { * @param {string} corpus * @returns {string} Resource name string. */ - corpusPath(corpus:string) { + corpusPath(corpus: string) { return this.pathTemplates.corpusPathTemplate.render({ corpus: corpus, }); @@ -925,7 +1159,7 @@ export class TextServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - corpusPermissionsPath(corpus:string,permission:string) { + corpusPermissionsPath(corpus: string, permission: string) { return this.pathTemplates.corpusPermissionsPathTemplate.render({ corpus: corpus, permission: permission, @@ -940,7 +1174,9 @@ export class TextServiceClient { * @returns {string} A string representing the corpus. */ matchCorpusFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).corpus; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).corpus; } /** @@ -951,7 +1187,9 @@ export class TextServiceClient { * @returns {string} A string representing the permission. */ matchPermissionFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).permission; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).permission; } /** @@ -961,7 +1199,7 @@ export class TextServiceClient { * @param {string} document * @returns {string} Resource name string. */ - documentPath(corpus:string,document:string) { + documentPath(corpus: string, document: string) { return this.pathTemplates.documentPathTemplate.render({ corpus: corpus, document: document, @@ -996,7 +1234,7 @@ export class TextServiceClient { * @param {string} file * @returns {string} Resource name string. */ - filePath(file:string) { + filePath(file: string) { return this.pathTemplates.filePathTemplate.render({ file: file, }); @@ -1019,7 +1257,7 @@ export class TextServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -1042,7 +1280,7 @@ export class TextServiceClient { * @param {string} tuned_model * @returns {string} Resource name string. */ - tunedModelPath(tunedModel:string) { + tunedModelPath(tunedModel: string) { return this.pathTemplates.tunedModelPathTemplate.render({ tuned_model: tunedModel, }); @@ -1056,7 +1294,8 @@ export class TextServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromTunedModelName(tunedModelName: string) { - return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName).tuned_model; + return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName) + .tuned_model; } /** @@ -1066,7 +1305,7 @@ export class TextServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - tunedModelPermissionsPath(tunedModel:string,permission:string) { + tunedModelPermissionsPath(tunedModel: string, permission: string) { return this.pathTemplates.tunedModelPermissionsPathTemplate.render({ tuned_model: tunedModel, permission: permission, @@ -1080,8 +1319,12 @@ export class TextServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the tuned_model. */ - matchTunedModelFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).tuned_model; + matchTunedModelFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).tuned_model; } /** @@ -1091,8 +1334,12 @@ export class TextServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the permission. */ - matchPermissionFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).permission; + matchPermissionFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).permission; } /** @@ -1103,7 +1350,7 @@ export class TextServiceClient { */ close(): Promise { if (this.textServiceStub && !this._terminated) { - return this.textServiceStub.then(stub => { + return this.textServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1111,4 +1358,4 @@ export class TextServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1beta/cache_service_client.ts b/packages/google-ai-generativelanguage/src/v1beta/cache_service_client.ts index 0880e35f5b7d..0d527c9d1f03 100644 --- a/packages/google-ai-generativelanguage/src/v1beta/cache_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1beta/cache_service_client.ts @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +54,7 @@ export class CacheServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -60,9 +67,9 @@ export class CacheServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - cacheServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + cacheServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of CacheServiceClient. @@ -103,21 +110,42 @@ export class CacheServiceClient { * const client = new CacheServiceClient({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 CacheServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -142,7 +170,7 @@ export class CacheServiceClient { 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; @@ -156,10 +184,7 @@ export class CacheServiceClient { } // 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 { @@ -181,31 +206,25 @@ export class CacheServiceClient { // Create useful helper objects for these. this.pathTemplates = { cachedContentPathTemplate: new this._gaxModule.PathTemplate( - 'cachedContents/{id}' + 'cachedContents/{id}', ), chunkPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}/chunks/{chunk}' - ), - corpusPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}' + 'corpora/{corpus}/documents/{document}/chunks/{chunk}', ), + corpusPathTemplate: new this._gaxModule.PathTemplate('corpora/{corpus}'), corpusPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/permissions/{permission}' + 'corpora/{corpus}/permissions/{permission}', ), documentPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}' - ), - filePathTemplate: new this._gaxModule.PathTemplate( - 'files/{file}' - ), - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' + 'corpora/{corpus}/documents/{document}', ), + filePathTemplate: new this._gaxModule.PathTemplate('files/{file}'), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), tunedModelPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}' + 'tunedModels/{tuned_model}', ), tunedModelPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}/permissions/{permission}' + 'tunedModels/{tuned_model}/permissions/{permission}', ), }; @@ -213,14 +232,20 @@ export class CacheServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listCachedContents: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'cachedContents') + listCachedContents: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'cachedContents', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1beta.CacheService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1beta.CacheService', + 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 @@ -251,37 +276,47 @@ export class CacheServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1beta.CacheService. this.cacheServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1beta.CacheService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1beta.CacheService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1beta.CacheService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1beta + .CacheService, + 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 cacheServiceStubMethods = - ['listCachedContents', 'createCachedContent', 'getCachedContent', 'updateCachedContent', 'deleteCachedContent']; + const cacheServiceStubMethods = [ + 'listCachedContents', + 'createCachedContent', + 'getCachedContent', + 'updateCachedContent', + 'deleteCachedContent', + ]; for (const methodName of cacheServiceStubMethods) { const callPromise = this.cacheServiceStub.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] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -296,8 +331,14 @@ export class CacheServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -308,8 +349,14 @@ export class CacheServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -349,8 +396,9 @@ export class CacheServiceClient { * 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; @@ -361,463 +409,686 @@ export class CacheServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates CachedContent resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ai.generativelanguage.v1beta.CachedContent} request.cachedContent - * Required. The cached content 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.ai.generativelanguage.v1beta.CachedContent|CachedContent}. - * 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/v1beta/cache_service.create_cached_content.js - * region_tag:generativelanguage_v1beta_generated_CacheService_CreateCachedContent_async - */ + /** + * Creates CachedContent resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ai.generativelanguage.v1beta.CachedContent} request.cachedContent + * Required. The cached content 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.ai.generativelanguage.v1beta.CachedContent|CachedContent}. + * 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/v1beta/cache_service.create_cached_content.js + * region_tag:generativelanguage_v1beta_generated_CacheService_CreateCachedContent_async + */ createCachedContent( - request?: protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICachedContent, + ( + | protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest + | undefined + ), + {} | undefined, + ] + >; createCachedContent( - request: protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ICachedContent, + | protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createCachedContent( - request: protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ICachedContent, + | protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createCachedContent( - request?: protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.ICachedContent, + | protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICachedContent, + ( + | protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest + | 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 || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createCachedContent request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.ICachedContent, + | protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createCachedContent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createCachedContent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest|undefined, - {}|undefined - ]) => { - this._log.info('createCachedContent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createCachedContent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.ICachedContent, + ( + | protos.google.ai.generativelanguage.v1beta.ICreateCachedContentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createCachedContent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Reads CachedContent resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name referring to the content cache entry. - * Format: `cachedContents/{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.ai.generativelanguage.v1beta.CachedContent|CachedContent}. - * 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/v1beta/cache_service.get_cached_content.js - * region_tag:generativelanguage_v1beta_generated_CacheService_GetCachedContent_async - */ + /** + * Reads CachedContent resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name referring to the content cache entry. + * Format: `cachedContents/{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.ai.generativelanguage.v1beta.CachedContent|CachedContent}. + * 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/v1beta/cache_service.get_cached_content.js + * region_tag:generativelanguage_v1beta_generated_CacheService_GetCachedContent_async + */ getCachedContent( - request?: protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICachedContent, + ( + | protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest + | undefined + ), + {} | undefined, + ] + >; getCachedContent( - request: protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ICachedContent, + | protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getCachedContent( - request: protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ICachedContent, + | protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getCachedContent( - request?: protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.ICachedContent, + | protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICachedContent, + ( + | protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest + | 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('getCachedContent request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.ICachedContent, + | protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getCachedContent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getCachedContent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest|undefined, - {}|undefined - ]) => { - this._log.info('getCachedContent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getCachedContent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.ICachedContent, + ( + | protos.google.ai.generativelanguage.v1beta.IGetCachedContentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getCachedContent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates CachedContent resource (only expiration is updatable). - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ai.generativelanguage.v1beta.CachedContent} request.cachedContent - * Required. The content cache entry to update - * @param {google.protobuf.FieldMask} request.updateMask - * The list of fields to update. - * @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.ai.generativelanguage.v1beta.CachedContent|CachedContent}. - * 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/v1beta/cache_service.update_cached_content.js - * region_tag:generativelanguage_v1beta_generated_CacheService_UpdateCachedContent_async - */ + /** + * Updates CachedContent resource (only expiration is updatable). + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ai.generativelanguage.v1beta.CachedContent} request.cachedContent + * Required. The content cache entry to update + * @param {google.protobuf.FieldMask} request.updateMask + * The list of fields to update. + * @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.ai.generativelanguage.v1beta.CachedContent|CachedContent}. + * 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/v1beta/cache_service.update_cached_content.js + * region_tag:generativelanguage_v1beta_generated_CacheService_UpdateCachedContent_async + */ updateCachedContent( - request?: protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICachedContent, + ( + | protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest + | undefined + ), + {} | undefined, + ] + >; updateCachedContent( - request: protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ICachedContent, + | protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCachedContent( - request: protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ICachedContent, + | protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCachedContent( - request?: protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.ICachedContent, + | protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICachedContent, + ( + | protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest + | 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({ - 'cached_content.name': request.cachedContent!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'cached_content.name': request.cachedContent!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateCachedContent request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.ICachedContent, + | protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateCachedContent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateCachedContent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.ICachedContent, - protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateCachedContent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateCachedContent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.ICachedContent, + ( + | protos.google.ai.generativelanguage.v1beta.IUpdateCachedContentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateCachedContent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes CachedContent resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name referring to the content cache entry - * Format: `cachedContents/{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 include:samples/generated/v1beta/cache_service.delete_cached_content.js - * region_tag:generativelanguage_v1beta_generated_CacheService_DeleteCachedContent_async - */ + /** + * Deletes CachedContent resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name referring to the content cache entry + * Format: `cachedContents/{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 include:samples/generated/v1beta/cache_service.delete_cached_content.js + * region_tag:generativelanguage_v1beta_generated_CacheService_DeleteCachedContent_async + */ deleteCachedContent( - request?: protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest + | undefined + ), + {} | undefined, + ] + >; deleteCachedContent( - request: protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteCachedContent( - request: protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteCachedContent( - request?: protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest + | 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('deleteCachedContent request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteCachedContent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteCachedContent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteCachedContent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteCachedContent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta.IDeleteCachedContentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteCachedContent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists CachedContents. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of cached contents to return. The service may - * return fewer than this value. If unspecified, some default (under maximum) - * number of items will be returned. The maximum value is 1000; values above - * 1000 will be coerced to 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListCachedContents` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListCachedContents` must - * match the call that provided the page token. - * @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.ai.generativelanguage.v1beta.CachedContent|CachedContent}. - * 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 `listCachedContentsAsync()` - * 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 CachedContents. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of cached contents to return. The service may + * return fewer than this value. If unspecified, some default (under maximum) + * number of items will be returned. The maximum value is 1000; values above + * 1000 will be coerced to 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListCachedContents` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListCachedContents` must + * match the call that provided the page token. + * @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.ai.generativelanguage.v1beta.CachedContent|CachedContent}. + * 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 `listCachedContentsAsync()` + * 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. + */ listCachedContents( - request?: protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICachedContent[], - protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest|null, - protos.google.ai.generativelanguage.v1beta.IListCachedContentsResponse - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICachedContent[], + protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest | null, + protos.google.ai.generativelanguage.v1beta.IListCachedContentsResponse, + ] + >; listCachedContents( - request: protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest, - protos.google.ai.generativelanguage.v1beta.IListCachedContentsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.ICachedContent>): void; + request: protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest, + | protos.google.ai.generativelanguage.v1beta.IListCachedContentsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.ICachedContent + >, + ): void; listCachedContents( - request: protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest, - protos.google.ai.generativelanguage.v1beta.IListCachedContentsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.ICachedContent>): void; + request: protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest, + | protos.google.ai.generativelanguage.v1beta.IListCachedContentsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.ICachedContent + >, + ): void; listCachedContents( - request?: protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest, - protos.google.ai.generativelanguage.v1beta.IListCachedContentsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.ICachedContent>, - callback?: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest, - protos.google.ai.generativelanguage.v1beta.IListCachedContentsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.ICachedContent>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICachedContent[], - protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest|null, - protos.google.ai.generativelanguage.v1beta.IListCachedContentsResponse - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IListCachedContentsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.ICachedContent + >, + callback?: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest, + | protos.google.ai.generativelanguage.v1beta.IListCachedContentsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.ICachedContent + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICachedContent[], + protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest | null, + protos.google.ai.generativelanguage.v1beta.IListCachedContentsResponse, + ] + > | 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 || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest, - protos.google.ai.generativelanguage.v1beta.IListCachedContentsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.ICachedContent>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest, + | protos.google.ai.generativelanguage.v1beta.IListCachedContentsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.ICachedContent + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listCachedContents values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -826,106 +1097,112 @@ export class CacheServiceClient { this._log.info('listCachedContents request %j', request); return this.innerApiCalls .listCachedContents(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ai.generativelanguage.v1beta.ICachedContent[], - protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest|null, - protos.google.ai.generativelanguage.v1beta.IListCachedContentsResponse - ]) => { - this._log.info('listCachedContents values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ai.generativelanguage.v1beta.ICachedContent[], + protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest | null, + protos.google.ai.generativelanguage.v1beta.IListCachedContentsResponse, + ]) => { + this._log.info('listCachedContents values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listCachedContents`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of cached contents to return. The service may - * return fewer than this value. If unspecified, some default (under maximum) - * number of items will be returned. The maximum value is 1000; values above - * 1000 will be coerced to 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListCachedContents` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListCachedContents` must - * match the call that provided the page token. - * @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.ai.generativelanguage.v1beta.CachedContent|CachedContent} 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 `listCachedContentsAsync()` - * 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 `listCachedContents`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of cached contents to return. The service may + * return fewer than this value. If unspecified, some default (under maximum) + * number of items will be returned. The maximum value is 1000; values above + * 1000 will be coerced to 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListCachedContents` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListCachedContents` must + * match the call that provided the page token. + * @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.ai.generativelanguage.v1beta.CachedContent|CachedContent} 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 `listCachedContentsAsync()` + * 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. + */ listCachedContentsStream( - request?: protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listCachedContents']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCachedContents stream %j', request); return this.descriptors.page.listCachedContents.createStream( this.innerApiCalls.listCachedContents as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listCachedContents`, 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 {number} [request.pageSize] - * Optional. The maximum number of cached contents to return. The service may - * return fewer than this value. If unspecified, some default (under maximum) - * number of items will be returned. The maximum value is 1000; values above - * 1000 will be coerced to 1000. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListCachedContents` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListCachedContents` must - * match the call that provided the 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 protos.google.ai.generativelanguage.v1beta.CachedContent|CachedContent}. 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 include:samples/generated/v1beta/cache_service.list_cached_contents.js - * region_tag:generativelanguage_v1beta_generated_CacheService_ListCachedContents_async - */ + /** + * Equivalent to `listCachedContents`, 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 {number} [request.pageSize] + * Optional. The maximum number of cached contents to return. The service may + * return fewer than this value. If unspecified, some default (under maximum) + * number of items will be returned. The maximum value is 1000; values above + * 1000 will be coerced to 1000. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListCachedContents` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListCachedContents` must + * match the call that provided the 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 protos.google.ai.generativelanguage.v1beta.CachedContent|CachedContent}. 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 include:samples/generated/v1beta/cache_service.list_cached_contents.js + * region_tag:generativelanguage_v1beta_generated_CacheService_ListCachedContents_async + */ listCachedContentsAsync( - request?: protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ai.generativelanguage.v1beta.IListCachedContentsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listCachedContents']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCachedContents iterate %j', request); return this.descriptors.page.listCachedContents.asyncIterate( this.innerApiCalls['listCachedContents'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -938,7 +1215,7 @@ export class CacheServiceClient { * @param {string} id * @returns {string} Resource name string. */ - cachedContentPath(id:string) { + cachedContentPath(id: string) { return this.pathTemplates.cachedContentPathTemplate.render({ id: id, }); @@ -952,7 +1229,8 @@ export class CacheServiceClient { * @returns {string} A string representing the id. */ matchIdFromCachedContentName(cachedContentName: string) { - return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName).id; + return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName) + .id; } /** @@ -963,7 +1241,7 @@ export class CacheServiceClient { * @param {string} chunk * @returns {string} Resource name string. */ - chunkPath(corpus:string,document:string,chunk:string) { + chunkPath(corpus: string, document: string, chunk: string) { return this.pathTemplates.chunkPathTemplate.render({ corpus: corpus, document: document, @@ -1010,7 +1288,7 @@ export class CacheServiceClient { * @param {string} corpus * @returns {string} Resource name string. */ - corpusPath(corpus:string) { + corpusPath(corpus: string) { return this.pathTemplates.corpusPathTemplate.render({ corpus: corpus, }); @@ -1034,7 +1312,7 @@ export class CacheServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - corpusPermissionsPath(corpus:string,permission:string) { + corpusPermissionsPath(corpus: string, permission: string) { return this.pathTemplates.corpusPermissionsPathTemplate.render({ corpus: corpus, permission: permission, @@ -1049,7 +1327,9 @@ export class CacheServiceClient { * @returns {string} A string representing the corpus. */ matchCorpusFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).corpus; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).corpus; } /** @@ -1060,7 +1340,9 @@ export class CacheServiceClient { * @returns {string} A string representing the permission. */ matchPermissionFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).permission; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).permission; } /** @@ -1070,7 +1352,7 @@ export class CacheServiceClient { * @param {string} document * @returns {string} Resource name string. */ - documentPath(corpus:string,document:string) { + documentPath(corpus: string, document: string) { return this.pathTemplates.documentPathTemplate.render({ corpus: corpus, document: document, @@ -1105,7 +1387,7 @@ export class CacheServiceClient { * @param {string} file * @returns {string} Resource name string. */ - filePath(file:string) { + filePath(file: string) { return this.pathTemplates.filePathTemplate.render({ file: file, }); @@ -1128,7 +1410,7 @@ export class CacheServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -1151,7 +1433,7 @@ export class CacheServiceClient { * @param {string} tuned_model * @returns {string} Resource name string. */ - tunedModelPath(tunedModel:string) { + tunedModelPath(tunedModel: string) { return this.pathTemplates.tunedModelPathTemplate.render({ tuned_model: tunedModel, }); @@ -1165,7 +1447,8 @@ export class CacheServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromTunedModelName(tunedModelName: string) { - return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName).tuned_model; + return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName) + .tuned_model; } /** @@ -1175,7 +1458,7 @@ export class CacheServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - tunedModelPermissionsPath(tunedModel:string,permission:string) { + tunedModelPermissionsPath(tunedModel: string, permission: string) { return this.pathTemplates.tunedModelPermissionsPathTemplate.render({ tuned_model: tunedModel, permission: permission, @@ -1189,8 +1472,12 @@ export class CacheServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the tuned_model. */ - matchTunedModelFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).tuned_model; + matchTunedModelFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).tuned_model; } /** @@ -1200,8 +1487,12 @@ export class CacheServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the permission. */ - matchPermissionFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).permission; + matchPermissionFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).permission; } /** @@ -1212,7 +1503,7 @@ export class CacheServiceClient { */ close(): Promise { if (this.cacheServiceStub && !this._terminated) { - return this.cacheServiceStub.then(stub => { + return this.cacheServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1220,4 +1511,4 @@ export class CacheServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1beta/discuss_service_client.ts b/packages/google-ai-generativelanguage/src/v1beta/discuss_service_client.ts index 75269175315e..3053a7d2204a 100644 --- a/packages/google-ai-generativelanguage/src/v1beta/discuss_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1beta/discuss_service_client.ts @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +52,7 @@ export class DiscussServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -60,9 +65,9 @@ export class DiscussServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - discussServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + discussServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of DiscussServiceClient. @@ -103,21 +108,42 @@ export class DiscussServiceClient { * const client = new DiscussServiceClient({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 DiscussServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -142,7 +168,7 @@ export class DiscussServiceClient { 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; @@ -156,10 +182,7 @@ export class DiscussServiceClient { } // 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 { @@ -181,38 +204,35 @@ export class DiscussServiceClient { // Create useful helper objects for these. this.pathTemplates = { cachedContentPathTemplate: new this._gaxModule.PathTemplate( - 'cachedContents/{id}' + 'cachedContents/{id}', ), chunkPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}/chunks/{chunk}' - ), - corpusPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}' + 'corpora/{corpus}/documents/{document}/chunks/{chunk}', ), + corpusPathTemplate: new this._gaxModule.PathTemplate('corpora/{corpus}'), corpusPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/permissions/{permission}' + 'corpora/{corpus}/permissions/{permission}', ), documentPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}' - ), - filePathTemplate: new this._gaxModule.PathTemplate( - 'files/{file}' - ), - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' + 'corpora/{corpus}/documents/{document}', ), + filePathTemplate: new this._gaxModule.PathTemplate('files/{file}'), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), tunedModelPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}' + 'tunedModels/{tuned_model}', ), tunedModelPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}/permissions/{permission}' + 'tunedModels/{tuned_model}/permissions/{permission}', ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1beta.DiscussService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1beta.DiscussService', + 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 @@ -243,36 +263,41 @@ export class DiscussServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1beta.DiscussService. this.discussServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1beta.DiscussService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1beta.DiscussService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1beta.DiscussService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1beta + .DiscussService, + 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 discussServiceStubMethods = - ['generateMessage', 'countMessageTokens']; + const discussServiceStubMethods = ['generateMessage', 'countMessageTokens']; for (const methodName of discussServiceStubMethods) { const callPromise = this.discussServiceStub.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 = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -287,8 +312,14 @@ export class DiscussServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -299,8 +330,14 @@ export class DiscussServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -340,8 +377,9 @@ export class DiscussServiceClient { * 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; @@ -352,231 +390,329 @@ export class DiscussServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Generates a response from the model given an input `MessagePrompt`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The name of the model to use. - * - * Format: `name=models/{model}`. - * @param {google.ai.generativelanguage.v1beta.MessagePrompt} request.prompt - * Required. The structured textual input given to the model as a prompt. - * - * Given a - * prompt, the model will return what it predicts is the next message in the - * discussion. - * @param {number} [request.temperature] - * Optional. Controls the randomness of the output. - * - * Values can range over `[0.0,1.0]`, - * inclusive. A value closer to `1.0` will produce responses that are more - * varied, while a value closer to `0.0` will typically result in - * less surprising responses from the model. - * @param {number} [request.candidateCount] - * Optional. The number of generated response messages to return. - * - * This value must be between - * `[1, 8]`, inclusive. If unset, this will default to `1`. - * @param {number} [request.topP] - * Optional. The maximum cumulative probability of tokens to consider when - * sampling. - * - * The model uses combined Top-k and nucleus sampling. - * - * Nucleus sampling considers the smallest set of tokens whose probability - * sum is at least `top_p`. - * @param {number} [request.topK] - * Optional. The maximum number of tokens to consider when sampling. - * - * The model uses combined Top-k and nucleus sampling. - * - * Top-k sampling considers the set of `top_k` most probable tokens. - * @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.ai.generativelanguage.v1beta.GenerateMessageResponse|GenerateMessageResponse}. - * 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/v1beta/discuss_service.generate_message.js - * region_tag:generativelanguage_v1beta_generated_DiscussService_GenerateMessage_async - */ + /** + * Generates a response from the model given an input `MessagePrompt`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The name of the model to use. + * + * Format: `name=models/{model}`. + * @param {google.ai.generativelanguage.v1beta.MessagePrompt} request.prompt + * Required. The structured textual input given to the model as a prompt. + * + * Given a + * prompt, the model will return what it predicts is the next message in the + * discussion. + * @param {number} [request.temperature] + * Optional. Controls the randomness of the output. + * + * Values can range over `[0.0,1.0]`, + * inclusive. A value closer to `1.0` will produce responses that are more + * varied, while a value closer to `0.0` will typically result in + * less surprising responses from the model. + * @param {number} [request.candidateCount] + * Optional. The number of generated response messages to return. + * + * This value must be between + * `[1, 8]`, inclusive. If unset, this will default to `1`. + * @param {number} [request.topP] + * Optional. The maximum cumulative probability of tokens to consider when + * sampling. + * + * The model uses combined Top-k and nucleus sampling. + * + * Nucleus sampling considers the smallest set of tokens whose probability + * sum is at least `top_p`. + * @param {number} [request.topK] + * Optional. The maximum number of tokens to consider when sampling. + * + * The model uses combined Top-k and nucleus sampling. + * + * Top-k sampling considers the set of `top_k` most probable tokens. + * @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.ai.generativelanguage.v1beta.GenerateMessageResponse|GenerateMessageResponse}. + * 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/v1beta/discuss_service.generate_message.js + * region_tag:generativelanguage_v1beta_generated_DiscussService_GenerateMessage_async + */ generateMessage( - request?: protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IGenerateMessageResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest + | undefined + ), + {} | undefined, + ] + >; generateMessage( - request: protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IGenerateMessageResponse, + | protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateMessage( - request: protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IGenerateMessageResponse, + | protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateMessage( - request?: protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IGenerateMessageResponse, + | protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IGenerateMessageResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('generateMessage request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IGenerateMessageResponse, + | protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('generateMessage response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.generateMessage(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest|undefined, - {}|undefined - ]) => { - this._log.info('generateMessage response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .generateMessage(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IGenerateMessageResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IGenerateMessageRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('generateMessage response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Runs a model's tokenizer on a string and returns the token count. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The model's resource name. This serves as an ID for the Model to - * use. - * - * This name should match a model name returned by the `ListModels` method. - * - * Format: `models/{model}` - * @param {google.ai.generativelanguage.v1beta.MessagePrompt} request.prompt - * Required. The prompt, whose token count is to 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 {@link protos.google.ai.generativelanguage.v1beta.CountMessageTokensResponse|CountMessageTokensResponse}. - * 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/v1beta/discuss_service.count_message_tokens.js - * region_tag:generativelanguage_v1beta_generated_DiscussService_CountMessageTokens_async - */ + /** + * Runs a model's tokenizer on a string and returns the token count. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The model's resource name. This serves as an ID for the Model to + * use. + * + * This name should match a model name returned by the `ListModels` method. + * + * Format: `models/{model}` + * @param {google.ai.generativelanguage.v1beta.MessagePrompt} request.prompt + * Required. The prompt, whose token count is to 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 {@link protos.google.ai.generativelanguage.v1beta.CountMessageTokensResponse|CountMessageTokensResponse}. + * 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/v1beta/discuss_service.count_message_tokens.js + * region_tag:generativelanguage_v1beta_generated_DiscussService_CountMessageTokens_async + */ countMessageTokens( - request?: protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICountMessageTokensResponse, + ( + | protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest + | undefined + ), + {} | undefined, + ] + >; countMessageTokens( - request: protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ICountMessageTokensResponse, + | protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): void; countMessageTokens( - request: protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ICountMessageTokensResponse, + | protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): void; countMessageTokens( - request?: protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.ICountMessageTokensResponse, + | protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICountMessageTokensResponse, + ( + | protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('countMessageTokens request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.ICountMessageTokensResponse, + | protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('countMessageTokens response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.countMessageTokens(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest|undefined, - {}|undefined - ]) => { - this._log.info('countMessageTokens response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .countMessageTokens(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.ICountMessageTokensResponse, + ( + | protos.google.ai.generativelanguage.v1beta.ICountMessageTokensRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('countMessageTokens response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -592,7 +728,7 @@ export class DiscussServiceClient { * @param {string} id * @returns {string} Resource name string. */ - cachedContentPath(id:string) { + cachedContentPath(id: string) { return this.pathTemplates.cachedContentPathTemplate.render({ id: id, }); @@ -606,7 +742,8 @@ export class DiscussServiceClient { * @returns {string} A string representing the id. */ matchIdFromCachedContentName(cachedContentName: string) { - return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName).id; + return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName) + .id; } /** @@ -617,7 +754,7 @@ export class DiscussServiceClient { * @param {string} chunk * @returns {string} Resource name string. */ - chunkPath(corpus:string,document:string,chunk:string) { + chunkPath(corpus: string, document: string, chunk: string) { return this.pathTemplates.chunkPathTemplate.render({ corpus: corpus, document: document, @@ -664,7 +801,7 @@ export class DiscussServiceClient { * @param {string} corpus * @returns {string} Resource name string. */ - corpusPath(corpus:string) { + corpusPath(corpus: string) { return this.pathTemplates.corpusPathTemplate.render({ corpus: corpus, }); @@ -688,7 +825,7 @@ export class DiscussServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - corpusPermissionsPath(corpus:string,permission:string) { + corpusPermissionsPath(corpus: string, permission: string) { return this.pathTemplates.corpusPermissionsPathTemplate.render({ corpus: corpus, permission: permission, @@ -703,7 +840,9 @@ export class DiscussServiceClient { * @returns {string} A string representing the corpus. */ matchCorpusFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).corpus; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).corpus; } /** @@ -714,7 +853,9 @@ export class DiscussServiceClient { * @returns {string} A string representing the permission. */ matchPermissionFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).permission; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).permission; } /** @@ -724,7 +865,7 @@ export class DiscussServiceClient { * @param {string} document * @returns {string} Resource name string. */ - documentPath(corpus:string,document:string) { + documentPath(corpus: string, document: string) { return this.pathTemplates.documentPathTemplate.render({ corpus: corpus, document: document, @@ -759,7 +900,7 @@ export class DiscussServiceClient { * @param {string} file * @returns {string} Resource name string. */ - filePath(file:string) { + filePath(file: string) { return this.pathTemplates.filePathTemplate.render({ file: file, }); @@ -782,7 +923,7 @@ export class DiscussServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -805,7 +946,7 @@ export class DiscussServiceClient { * @param {string} tuned_model * @returns {string} Resource name string. */ - tunedModelPath(tunedModel:string) { + tunedModelPath(tunedModel: string) { return this.pathTemplates.tunedModelPathTemplate.render({ tuned_model: tunedModel, }); @@ -819,7 +960,8 @@ export class DiscussServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromTunedModelName(tunedModelName: string) { - return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName).tuned_model; + return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName) + .tuned_model; } /** @@ -829,7 +971,7 @@ export class DiscussServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - tunedModelPermissionsPath(tunedModel:string,permission:string) { + tunedModelPermissionsPath(tunedModel: string, permission: string) { return this.pathTemplates.tunedModelPermissionsPathTemplate.render({ tuned_model: tunedModel, permission: permission, @@ -843,8 +985,12 @@ export class DiscussServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the tuned_model. */ - matchTunedModelFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).tuned_model; + matchTunedModelFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).tuned_model; } /** @@ -854,8 +1000,12 @@ export class DiscussServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the permission. */ - matchPermissionFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).permission; + matchPermissionFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).permission; } /** @@ -866,7 +1016,7 @@ export class DiscussServiceClient { */ close(): Promise { if (this.discussServiceStub && !this._terminated) { - return this.discussServiceStub.then(stub => { + return this.discussServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -874,4 +1024,4 @@ export class DiscussServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1beta/file_service_client.ts b/packages/google-ai-generativelanguage/src/v1beta/file_service_client.ts index 18e064b60c2a..97eef26389df 100644 --- a/packages/google-ai-generativelanguage/src/v1beta/file_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1beta/file_service_client.ts @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class FileServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -57,9 +64,9 @@ export class FileServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - fileServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + fileServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of FileServiceClient. @@ -100,21 +107,42 @@ export class FileServiceClient { * const client = new FileServiceClient({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 FileServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -139,7 +167,7 @@ export class FileServiceClient { 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; @@ -153,10 +181,7 @@ export class FileServiceClient { } // 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 { @@ -178,31 +203,25 @@ export class FileServiceClient { // Create useful helper objects for these. this.pathTemplates = { cachedContentPathTemplate: new this._gaxModule.PathTemplate( - 'cachedContents/{id}' + 'cachedContents/{id}', ), chunkPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}/chunks/{chunk}' - ), - corpusPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}' + 'corpora/{corpus}/documents/{document}/chunks/{chunk}', ), + corpusPathTemplate: new this._gaxModule.PathTemplate('corpora/{corpus}'), corpusPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/permissions/{permission}' + 'corpora/{corpus}/permissions/{permission}', ), documentPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}' - ), - filePathTemplate: new this._gaxModule.PathTemplate( - 'files/{file}' - ), - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' + 'corpora/{corpus}/documents/{document}', ), + filePathTemplate: new this._gaxModule.PathTemplate('files/{file}'), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), tunedModelPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}' + 'tunedModels/{tuned_model}', ), tunedModelPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}/permissions/{permission}' + 'tunedModels/{tuned_model}/permissions/{permission}', ), }; @@ -210,14 +229,20 @@ export class FileServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listFiles: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'files') + listFiles: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'files', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1beta.FileService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1beta.FileService', + 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 @@ -248,37 +273,46 @@ export class FileServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1beta.FileService. this.fileServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1beta.FileService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1beta.FileService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.ai.generativelanguage.v1beta.FileService, - 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 fileServiceStubMethods = - ['createFile', 'listFiles', 'getFile', 'deleteFile', 'downloadFile']; + const fileServiceStubMethods = [ + 'createFile', + 'listFiles', + 'getFile', + 'deleteFile', + 'downloadFile', + ]; for (const methodName of fileServiceStubMethods) { const callPromise = this.fileServiceStub.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] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -293,8 +327,14 @@ export class FileServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -305,8 +345,14 @@ export class FileServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -346,8 +392,9 @@ export class FileServiceClient { * 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; @@ -358,456 +405,661 @@ export class FileServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates a `File`. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ai.generativelanguage.v1beta.File} [request.file] - * Optional. Metadata for the file 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.ai.generativelanguage.v1beta.CreateFileResponse|CreateFileResponse}. - * 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/v1beta/file_service.create_file.js - * region_tag:generativelanguage_v1beta_generated_FileService_CreateFile_async - */ + /** + * Creates a `File`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ai.generativelanguage.v1beta.File} [request.file] + * Optional. Metadata for the file 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.ai.generativelanguage.v1beta.CreateFileResponse|CreateFileResponse}. + * 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/v1beta/file_service.create_file.js + * region_tag:generativelanguage_v1beta_generated_FileService_CreateFile_async + */ createFile( - request?: protos.google.ai.generativelanguage.v1beta.ICreateFileRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICreateFileResponse, - protos.google.ai.generativelanguage.v1beta.ICreateFileRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.ICreateFileRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICreateFileResponse, + protos.google.ai.generativelanguage.v1beta.ICreateFileRequest | undefined, + {} | undefined, + ] + >; createFile( - request: protos.google.ai.generativelanguage.v1beta.ICreateFileRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ICreateFileResponse, - protos.google.ai.generativelanguage.v1beta.ICreateFileRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.ICreateFileRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ICreateFileResponse, + | protos.google.ai.generativelanguage.v1beta.ICreateFileRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createFile( - request: protos.google.ai.generativelanguage.v1beta.ICreateFileRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ICreateFileResponse, - protos.google.ai.generativelanguage.v1beta.ICreateFileRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.ICreateFileRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ICreateFileResponse, + | protos.google.ai.generativelanguage.v1beta.ICreateFileRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createFile( - request?: protos.google.ai.generativelanguage.v1beta.ICreateFileRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta.ICreateFileRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.ICreateFileResponse, - protos.google.ai.generativelanguage.v1beta.ICreateFileRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1beta.ICreateFileResponse, - protos.google.ai.generativelanguage.v1beta.ICreateFileRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICreateFileResponse, - protos.google.ai.generativelanguage.v1beta.ICreateFileRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.ICreateFileRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.ICreateFileResponse, + | protos.google.ai.generativelanguage.v1beta.ICreateFileRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICreateFileResponse, + protos.google.ai.generativelanguage.v1beta.ICreateFileRequest | 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 || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createFile request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.ICreateFileResponse, - protos.google.ai.generativelanguage.v1beta.ICreateFileRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.ICreateFileResponse, + | protos.google.ai.generativelanguage.v1beta.ICreateFileRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createFile response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createFile(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.ICreateFileResponse, - protos.google.ai.generativelanguage.v1beta.ICreateFileRequest|undefined, - {}|undefined - ]) => { - this._log.info('createFile response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createFile(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.ICreateFileResponse, + ( + | protos.google.ai.generativelanguage.v1beta.ICreateFileRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createFile response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets the metadata for the given `File`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the `File` to get. - * Example: `files/abc-123` - * @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.ai.generativelanguage.v1beta.File|File}. - * 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/v1beta/file_service.get_file.js - * region_tag:generativelanguage_v1beta_generated_FileService_GetFile_async - */ + /** + * Gets the metadata for the given `File`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the `File` to get. + * Example: `files/abc-123` + * @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.ai.generativelanguage.v1beta.File|File}. + * 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/v1beta/file_service.get_file.js + * region_tag:generativelanguage_v1beta_generated_FileService_GetFile_async + */ getFile( - request?: protos.google.ai.generativelanguage.v1beta.IGetFileRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IFile, - protos.google.ai.generativelanguage.v1beta.IGetFileRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IGetFileRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IFile, + protos.google.ai.generativelanguage.v1beta.IGetFileRequest | undefined, + {} | undefined, + ] + >; getFile( - request: protos.google.ai.generativelanguage.v1beta.IGetFileRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IFile, - protos.google.ai.generativelanguage.v1beta.IGetFileRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGetFileRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IFile, + | protos.google.ai.generativelanguage.v1beta.IGetFileRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getFile( - request: protos.google.ai.generativelanguage.v1beta.IGetFileRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IFile, - protos.google.ai.generativelanguage.v1beta.IGetFileRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGetFileRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IFile, + | protos.google.ai.generativelanguage.v1beta.IGetFileRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getFile( - request?: protos.google.ai.generativelanguage.v1beta.IGetFileRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta.IGetFileRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IFile, - protos.google.ai.generativelanguage.v1beta.IGetFileRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1beta.IFile, - protos.google.ai.generativelanguage.v1beta.IGetFileRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IFile, - protos.google.ai.generativelanguage.v1beta.IGetFileRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IGetFileRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IFile, + | protos.google.ai.generativelanguage.v1beta.IGetFileRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IFile, + protos.google.ai.generativelanguage.v1beta.IGetFileRequest | 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('getFile request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.IFile, - protos.google.ai.generativelanguage.v1beta.IGetFileRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IFile, + | protos.google.ai.generativelanguage.v1beta.IGetFileRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getFile response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getFile(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.IFile, - protos.google.ai.generativelanguage.v1beta.IGetFileRequest|undefined, - {}|undefined - ]) => { - this._log.info('getFile response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getFile(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IFile, + ( + | protos.google.ai.generativelanguage.v1beta.IGetFileRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getFile response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes the `File`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the `File` to delete. - * Example: `files/abc-123` - * @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/v1beta/file_service.delete_file.js - * region_tag:generativelanguage_v1beta_generated_FileService_DeleteFile_async - */ + /** + * Deletes the `File`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the `File` to delete. + * Example: `files/abc-123` + * @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/v1beta/file_service.delete_file.js + * region_tag:generativelanguage_v1beta_generated_FileService_DeleteFile_async + */ deleteFile( - request?: protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest | undefined, + {} | undefined, + ] + >; deleteFile( - request: protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteFile( - request: protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteFile( - request?: protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest | 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('deleteFile request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteFile response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteFile(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteFile response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteFile(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta.IDeleteFileRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteFile response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Download the `File`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the `File` to download. - * Example: `files/abc-123` - * @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.ai.generativelanguage.v1beta.DownloadFileResponse|DownloadFileResponse}. - * 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/v1beta/file_service.download_file.js - * region_tag:generativelanguage_v1beta_generated_FileService_DownloadFile_async - */ + /** + * Download the `File`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the `File` to download. + * Example: `files/abc-123` + * @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.ai.generativelanguage.v1beta.DownloadFileResponse|DownloadFileResponse}. + * 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/v1beta/file_service.download_file.js + * region_tag:generativelanguage_v1beta_generated_FileService_DownloadFile_async + */ downloadFile( - request?: protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IDownloadFileResponse, - protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IDownloadFileResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest + | undefined + ), + {} | undefined, + ] + >; downloadFile( - request: protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IDownloadFileResponse, - protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IDownloadFileResponse, + | protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest + | null + | undefined, + {} | null | undefined + >, + ): void; downloadFile( - request: protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IDownloadFileResponse, - protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IDownloadFileResponse, + | protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest + | null + | undefined, + {} | null | undefined + >, + ): void; downloadFile( - request?: protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.IDownloadFileResponse, - protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IDownloadFileResponse, - protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IDownloadFileResponse, - protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IDownloadFileResponse, + | protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IDownloadFileResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest + | 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('downloadFile request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.IDownloadFileResponse, - protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IDownloadFileResponse, + | protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('downloadFile response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.downloadFile(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.IDownloadFileResponse, - protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest|undefined, - {}|undefined - ]) => { - this._log.info('downloadFile response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .downloadFile(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IDownloadFileResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IDownloadFileRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('downloadFile response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists the metadata for `File`s owned by the requesting project. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. Maximum number of `File`s to return per page. - * If unspecified, defaults to 10. Maximum `page_size` is 100. - * @param {string} [request.pageToken] - * Optional. A page token from a previous `ListFiles` call. - * @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.ai.generativelanguage.v1beta.File|File}. - * 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 `listFilesAsync()` - * 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 metadata for `File`s owned by the requesting project. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. Maximum number of `File`s to return per page. + * If unspecified, defaults to 10. Maximum `page_size` is 100. + * @param {string} [request.pageToken] + * Optional. A page token from a previous `ListFiles` call. + * @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.ai.generativelanguage.v1beta.File|File}. + * 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 `listFilesAsync()` + * 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. + */ listFiles( - request?: protos.google.ai.generativelanguage.v1beta.IListFilesRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IFile[], - protos.google.ai.generativelanguage.v1beta.IListFilesRequest|null, - protos.google.ai.generativelanguage.v1beta.IListFilesResponse - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IListFilesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IFile[], + protos.google.ai.generativelanguage.v1beta.IListFilesRequest | null, + protos.google.ai.generativelanguage.v1beta.IListFilesResponse, + ] + >; listFiles( - request: protos.google.ai.generativelanguage.v1beta.IListFilesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListFilesRequest, - protos.google.ai.generativelanguage.v1beta.IListFilesResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IFile>): void; + request: protos.google.ai.generativelanguage.v1beta.IListFilesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListFilesRequest, + | protos.google.ai.generativelanguage.v1beta.IListFilesResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IFile + >, + ): void; listFiles( - request: protos.google.ai.generativelanguage.v1beta.IListFilesRequest, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListFilesRequest, - protos.google.ai.generativelanguage.v1beta.IListFilesResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IFile>): void; + request: protos.google.ai.generativelanguage.v1beta.IListFilesRequest, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListFilesRequest, + | protos.google.ai.generativelanguage.v1beta.IListFilesResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IFile + >, + ): void; listFiles( - request?: protos.google.ai.generativelanguage.v1beta.IListFilesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListFilesRequest, - protos.google.ai.generativelanguage.v1beta.IListFilesResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IFile>, - callback?: PaginationCallback< + request?: protos.google.ai.generativelanguage.v1beta.IListFilesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ai.generativelanguage.v1beta.IListFilesRequest, - protos.google.ai.generativelanguage.v1beta.IListFilesResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IFile>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IFile[], - protos.google.ai.generativelanguage.v1beta.IListFilesRequest|null, - protos.google.ai.generativelanguage.v1beta.IListFilesResponse - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IListFilesResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IFile + >, + callback?: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListFilesRequest, + | protos.google.ai.generativelanguage.v1beta.IListFilesResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IFile + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IFile[], + protos.google.ai.generativelanguage.v1beta.IListFilesRequest | null, + protos.google.ai.generativelanguage.v1beta.IListFilesResponse, + ] + > | 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 || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListFilesRequest, - protos.google.ai.generativelanguage.v1beta.IListFilesResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IFile>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListFilesRequest, + | protos.google.ai.generativelanguage.v1beta.IListFilesResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IFile + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listFiles values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -816,94 +1068,100 @@ export class FileServiceClient { this._log.info('listFiles request %j', request); return this.innerApiCalls .listFiles(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ai.generativelanguage.v1beta.IFile[], - protos.google.ai.generativelanguage.v1beta.IListFilesRequest|null, - protos.google.ai.generativelanguage.v1beta.IListFilesResponse - ]) => { - this._log.info('listFiles values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ai.generativelanguage.v1beta.IFile[], + protos.google.ai.generativelanguage.v1beta.IListFilesRequest | null, + protos.google.ai.generativelanguage.v1beta.IListFilesResponse, + ]) => { + this._log.info('listFiles values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listFiles`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. Maximum number of `File`s to return per page. - * If unspecified, defaults to 10. Maximum `page_size` is 100. - * @param {string} [request.pageToken] - * Optional. A page token from a previous `ListFiles` call. - * @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.ai.generativelanguage.v1beta.File|File} 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 `listFilesAsync()` - * 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 `listFiles`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. Maximum number of `File`s to return per page. + * If unspecified, defaults to 10. Maximum `page_size` is 100. + * @param {string} [request.pageToken] + * Optional. A page token from a previous `ListFiles` call. + * @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.ai.generativelanguage.v1beta.File|File} 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 `listFilesAsync()` + * 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. + */ listFilesStream( - request?: protos.google.ai.generativelanguage.v1beta.IListFilesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ai.generativelanguage.v1beta.IListFilesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listFiles']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listFiles stream %j', request); return this.descriptors.page.listFiles.createStream( this.innerApiCalls.listFiles as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listFiles`, 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 {number} [request.pageSize] - * Optional. Maximum number of `File`s to return per page. - * If unspecified, defaults to 10. Maximum `page_size` is 100. - * @param {string} [request.pageToken] - * Optional. A page token from a previous `ListFiles` call. - * @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.ai.generativelanguage.v1beta.File|File}. 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 include:samples/generated/v1beta/file_service.list_files.js - * region_tag:generativelanguage_v1beta_generated_FileService_ListFiles_async - */ + /** + * Equivalent to `listFiles`, 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 {number} [request.pageSize] + * Optional. Maximum number of `File`s to return per page. + * If unspecified, defaults to 10. Maximum `page_size` is 100. + * @param {string} [request.pageToken] + * Optional. A page token from a previous `ListFiles` call. + * @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.ai.generativelanguage.v1beta.File|File}. 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 include:samples/generated/v1beta/file_service.list_files.js + * region_tag:generativelanguage_v1beta_generated_FileService_ListFiles_async + */ listFilesAsync( - request?: protos.google.ai.generativelanguage.v1beta.IListFilesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ai.generativelanguage.v1beta.IListFilesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listFiles']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listFiles iterate %j', request); return this.descriptors.page.listFiles.asyncIterate( this.innerApiCalls['listFiles'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -916,7 +1174,7 @@ export class FileServiceClient { * @param {string} id * @returns {string} Resource name string. */ - cachedContentPath(id:string) { + cachedContentPath(id: string) { return this.pathTemplates.cachedContentPathTemplate.render({ id: id, }); @@ -930,7 +1188,8 @@ export class FileServiceClient { * @returns {string} A string representing the id. */ matchIdFromCachedContentName(cachedContentName: string) { - return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName).id; + return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName) + .id; } /** @@ -941,7 +1200,7 @@ export class FileServiceClient { * @param {string} chunk * @returns {string} Resource name string. */ - chunkPath(corpus:string,document:string,chunk:string) { + chunkPath(corpus: string, document: string, chunk: string) { return this.pathTemplates.chunkPathTemplate.render({ corpus: corpus, document: document, @@ -988,7 +1247,7 @@ export class FileServiceClient { * @param {string} corpus * @returns {string} Resource name string. */ - corpusPath(corpus:string) { + corpusPath(corpus: string) { return this.pathTemplates.corpusPathTemplate.render({ corpus: corpus, }); @@ -1012,7 +1271,7 @@ export class FileServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - corpusPermissionsPath(corpus:string,permission:string) { + corpusPermissionsPath(corpus: string, permission: string) { return this.pathTemplates.corpusPermissionsPathTemplate.render({ corpus: corpus, permission: permission, @@ -1027,7 +1286,9 @@ export class FileServiceClient { * @returns {string} A string representing the corpus. */ matchCorpusFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).corpus; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).corpus; } /** @@ -1038,7 +1299,9 @@ export class FileServiceClient { * @returns {string} A string representing the permission. */ matchPermissionFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).permission; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).permission; } /** @@ -1048,7 +1311,7 @@ export class FileServiceClient { * @param {string} document * @returns {string} Resource name string. */ - documentPath(corpus:string,document:string) { + documentPath(corpus: string, document: string) { return this.pathTemplates.documentPathTemplate.render({ corpus: corpus, document: document, @@ -1083,7 +1346,7 @@ export class FileServiceClient { * @param {string} file * @returns {string} Resource name string. */ - filePath(file:string) { + filePath(file: string) { return this.pathTemplates.filePathTemplate.render({ file: file, }); @@ -1106,7 +1369,7 @@ export class FileServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -1129,7 +1392,7 @@ export class FileServiceClient { * @param {string} tuned_model * @returns {string} Resource name string. */ - tunedModelPath(tunedModel:string) { + tunedModelPath(tunedModel: string) { return this.pathTemplates.tunedModelPathTemplate.render({ tuned_model: tunedModel, }); @@ -1143,7 +1406,8 @@ export class FileServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromTunedModelName(tunedModelName: string) { - return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName).tuned_model; + return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName) + .tuned_model; } /** @@ -1153,7 +1417,7 @@ export class FileServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - tunedModelPermissionsPath(tunedModel:string,permission:string) { + tunedModelPermissionsPath(tunedModel: string, permission: string) { return this.pathTemplates.tunedModelPermissionsPathTemplate.render({ tuned_model: tunedModel, permission: permission, @@ -1167,8 +1431,12 @@ export class FileServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the tuned_model. */ - matchTunedModelFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).tuned_model; + matchTunedModelFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).tuned_model; } /** @@ -1178,8 +1446,12 @@ export class FileServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the permission. */ - matchPermissionFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).permission; + matchPermissionFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).permission; } /** @@ -1190,7 +1462,7 @@ export class FileServiceClient { */ close(): Promise { if (this.fileServiceStub && !this._terminated) { - return this.fileServiceStub.then(stub => { + return this.fileServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1198,4 +1470,4 @@ export class FileServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1beta/generative_service_client.ts b/packages/google-ai-generativelanguage/src/v1beta/generative_service_client.ts index 74351b7c9111..d2d92ed9cf74 100644 --- a/packages/google-ai-generativelanguage/src/v1beta/generative_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1beta/generative_service_client.ts @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; -import {PassThrough} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; +import { PassThrough } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -45,7 +50,7 @@ export class GenerativeServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -58,9 +63,9 @@ export class GenerativeServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - generativeServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + generativeServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of GenerativeServiceClient. @@ -101,21 +106,42 @@ export class GenerativeServiceClient { * const client = new GenerativeServiceClient({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 GenerativeServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -140,7 +166,7 @@ export class GenerativeServiceClient { 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; @@ -154,10 +180,7 @@ export class GenerativeServiceClient { } // 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 { @@ -179,45 +202,50 @@ export class GenerativeServiceClient { // Create useful helper objects for these. this.pathTemplates = { cachedContentPathTemplate: new this._gaxModule.PathTemplate( - 'cachedContents/{id}' + 'cachedContents/{id}', ), chunkPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}/chunks/{chunk}' - ), - corpusPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}' + 'corpora/{corpus}/documents/{document}/chunks/{chunk}', ), + corpusPathTemplate: new this._gaxModule.PathTemplate('corpora/{corpus}'), corpusPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/permissions/{permission}' + 'corpora/{corpus}/permissions/{permission}', ), documentPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}' - ), - filePathTemplate: new this._gaxModule.PathTemplate( - 'files/{file}' - ), - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' + 'corpora/{corpus}/documents/{document}', ), + filePathTemplate: new this._gaxModule.PathTemplate('files/{file}'), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), tunedModelPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}' + 'tunedModels/{tuned_model}', ), tunedModelPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}/permissions/{permission}' + 'tunedModels/{tuned_model}/permissions/{permission}', ), }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this.descriptors.stream = { - streamGenerateContent: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), - bidiGenerateContent: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries) + streamGenerateContent: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries, + ), + bidiGenerateContent: 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.ai.generativelanguage.v1beta.GenerativeService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1beta.GenerativeService', + 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 @@ -248,44 +276,61 @@ export class GenerativeServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1beta.GenerativeService. this.generativeServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1beta.GenerativeService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1beta.GenerativeService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1beta.GenerativeService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1beta + .GenerativeService, + 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 generativeServiceStubMethods = - ['generateContent', 'generateAnswer', 'streamGenerateContent', 'embedContent', 'batchEmbedContents', 'countTokens', 'bidiGenerateContent']; + const generativeServiceStubMethods = [ + 'generateContent', + 'generateAnswer', + 'streamGenerateContent', + 'embedContent', + 'batchEmbedContents', + 'countTokens', + 'bidiGenerateContent', + ]; for (const methodName of generativeServiceStubMethods) { const callPromise = this.generativeServiceStub.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.stream[methodName] || - undefined; + const descriptor = this.descriptors.stream[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -300,8 +345,14 @@ export class GenerativeServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -312,8 +363,14 @@ export class GenerativeServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -353,8 +410,9 @@ export class GenerativeServiceClient { * 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; @@ -365,742 +423,988 @@ export class GenerativeServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Generates a model response given an input `GenerateContentRequest`. - * Refer to the [text generation - * guide](https://ai.google.dev/gemini-api/docs/text-generation) for detailed - * usage information. Input capabilities differ between models, including - * tuned models. Refer to the [model - * guide](https://ai.google.dev/gemini-api/docs/models/gemini) and [tuning - * guide](https://ai.google.dev/gemini-api/docs/model-tuning) for details. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The name of the `Model` to use for generating the completion. - * - * Format: `models/{model}`. - * @param {google.ai.generativelanguage.v1beta.Content} [request.systemInstruction] - * Optional. Developer set [system - * instruction(s)](https://ai.google.dev/gemini-api/docs/system-instructions). - * Currently, text only. - * @param {number[]} request.contents - * Required. The content of the current conversation with the model. - * - * For single-turn queries, this is a single instance. For multi-turn queries - * like [chat](https://ai.google.dev/gemini-api/docs/text-generation#chat), - * this is a repeated field that contains the conversation history and the - * latest request. - * @param {number[]} [request.tools] - * Optional. A list of `Tools` the `Model` may use to generate the next - * response. - * - * A `Tool` is a piece of code that enables the system to interact with - * external systems to perform an action, or set of actions, outside of - * knowledge and scope of the `Model`. Supported `Tool`s are `Function` and - * `code_execution`. Refer to the [Function - * calling](https://ai.google.dev/gemini-api/docs/function-calling) and the - * [Code execution](https://ai.google.dev/gemini-api/docs/code-execution) - * guides to learn more. - * @param {google.ai.generativelanguage.v1beta.ToolConfig} [request.toolConfig] - * Optional. Tool configuration for any `Tool` specified in the request. Refer - * to the [Function calling - * guide](https://ai.google.dev/gemini-api/docs/function-calling#function_calling_mode) - * for a usage example. - * @param {number[]} [request.safetySettings] - * Optional. A list of unique `SafetySetting` instances for blocking unsafe - * content. - * - * This will be enforced on the `GenerateContentRequest.contents` and - * `GenerateContentResponse.candidates`. There should not be more than one - * setting for each `SafetyCategory` type. The API will block any contents and - * responses that fail to meet the thresholds set by these settings. This list - * overrides the default settings for each `SafetyCategory` specified in the - * safety_settings. If there is no `SafetySetting` for a given - * `SafetyCategory` provided in the list, the API will use the default safety - * setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH, - * HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, - * HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY are supported. - * Refer to the [guide](https://ai.google.dev/gemini-api/docs/safety-settings) - * for detailed information on available safety settings. Also refer to the - * [Safety guidance](https://ai.google.dev/gemini-api/docs/safety-guidance) to - * learn how to incorporate safety considerations in your AI applications. - * @param {google.ai.generativelanguage.v1beta.GenerationConfig} [request.generationConfig] - * Optional. Configuration options for model generation and outputs. - * @param {string} [request.cachedContent] - * Optional. The name of the content - * [cached](https://ai.google.dev/gemini-api/docs/caching) to use as context - * to serve the prediction. Format: `cachedContents/{cachedContent}` - * @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.ai.generativelanguage.v1beta.GenerateContentResponse|GenerateContentResponse}. - * 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/v1beta/generative_service.generate_content.js - * region_tag:generativelanguage_v1beta_generated_GenerativeService_GenerateContent_async - */ + /** + * Generates a model response given an input `GenerateContentRequest`. + * Refer to the [text generation + * guide](https://ai.google.dev/gemini-api/docs/text-generation) for detailed + * usage information. Input capabilities differ between models, including + * tuned models. Refer to the [model + * guide](https://ai.google.dev/gemini-api/docs/models/gemini) and [tuning + * guide](https://ai.google.dev/gemini-api/docs/model-tuning) for details. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The name of the `Model` to use for generating the completion. + * + * Format: `models/{model}`. + * @param {google.ai.generativelanguage.v1beta.Content} [request.systemInstruction] + * Optional. Developer set [system + * instruction(s)](https://ai.google.dev/gemini-api/docs/system-instructions). + * Currently, text only. + * @param {number[]} request.contents + * Required. The content of the current conversation with the model. + * + * For single-turn queries, this is a single instance. For multi-turn queries + * like [chat](https://ai.google.dev/gemini-api/docs/text-generation#chat), + * this is a repeated field that contains the conversation history and the + * latest request. + * @param {number[]} [request.tools] + * Optional. A list of `Tools` the `Model` may use to generate the next + * response. + * + * A `Tool` is a piece of code that enables the system to interact with + * external systems to perform an action, or set of actions, outside of + * knowledge and scope of the `Model`. Supported `Tool`s are `Function` and + * `code_execution`. Refer to the [Function + * calling](https://ai.google.dev/gemini-api/docs/function-calling) and the + * [Code execution](https://ai.google.dev/gemini-api/docs/code-execution) + * guides to learn more. + * @param {google.ai.generativelanguage.v1beta.ToolConfig} [request.toolConfig] + * Optional. Tool configuration for any `Tool` specified in the request. Refer + * to the [Function calling + * guide](https://ai.google.dev/gemini-api/docs/function-calling#function_calling_mode) + * for a usage example. + * @param {number[]} [request.safetySettings] + * Optional. A list of unique `SafetySetting` instances for blocking unsafe + * content. + * + * This will be enforced on the `GenerateContentRequest.contents` and + * `GenerateContentResponse.candidates`. There should not be more than one + * setting for each `SafetyCategory` type. The API will block any contents and + * responses that fail to meet the thresholds set by these settings. This list + * overrides the default settings for each `SafetyCategory` specified in the + * safety_settings. If there is no `SafetySetting` for a given + * `SafetyCategory` provided in the list, the API will use the default safety + * setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH, + * HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, + * HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY are supported. + * Refer to the [guide](https://ai.google.dev/gemini-api/docs/safety-settings) + * for detailed information on available safety settings. Also refer to the + * [Safety guidance](https://ai.google.dev/gemini-api/docs/safety-guidance) to + * learn how to incorporate safety considerations in your AI applications. + * @param {google.ai.generativelanguage.v1beta.GenerationConfig} [request.generationConfig] + * Optional. Configuration options for model generation and outputs. + * @param {string} [request.cachedContent] + * Optional. The name of the content + * [cached](https://ai.google.dev/gemini-api/docs/caching) to use as context + * to serve the prediction. Format: `cachedContents/{cachedContent}` + * @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.ai.generativelanguage.v1beta.GenerateContentResponse|GenerateContentResponse}. + * 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/v1beta/generative_service.generate_content.js + * region_tag:generativelanguage_v1beta_generated_GenerativeService_GenerateContent_async + */ generateContent( - request?: protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IGenerateContentResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest + | undefined + ), + {} | undefined, + ] + >; generateContent( - request: protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IGenerateContentResponse, + | protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateContent( - request: protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IGenerateContentResponse, + | protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateContent( - request?: protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1beta.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IGenerateContentResponse, + | protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IGenerateContentResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('generateContent request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IGenerateContentResponse, + | protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('generateContent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.generateContent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.IGenerateContentResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest|undefined, - {}|undefined - ]) => { - this._log.info('generateContent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .generateContent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IGenerateContentResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('generateContent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Generates a grounded answer from the model given an input - * `GenerateAnswerRequest`. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ai.generativelanguage.v1beta.GroundingPassages} request.inlinePassages - * Passages provided inline with the request. - * @param {google.ai.generativelanguage.v1beta.SemanticRetrieverConfig} request.semanticRetriever - * Content retrieved from resources created via the Semantic Retriever - * API. - * @param {string} request.model - * Required. The name of the `Model` to use for generating the grounded - * response. - * - * Format: `model=models/{model}`. - * @param {number[]} request.contents - * Required. The content of the current conversation with the `Model`. For - * single-turn queries, this is a single question to answer. For multi-turn - * queries, this is a repeated field that contains conversation history and - * the last `Content` in the list containing the question. - * - * Note: `GenerateAnswer` only supports queries in English. - * @param {google.ai.generativelanguage.v1beta.GenerateAnswerRequest.AnswerStyle} request.answerStyle - * Required. Style in which answers should be returned. - * @param {number[]} [request.safetySettings] - * Optional. A list of unique `SafetySetting` instances for blocking unsafe - * content. - * - * This will be enforced on the `GenerateAnswerRequest.contents` and - * `GenerateAnswerResponse.candidate`. There should not be more than one - * setting for each `SafetyCategory` type. The API will block any contents and - * responses that fail to meet the thresholds set by these settings. This list - * overrides the default settings for each `SafetyCategory` specified in the - * safety_settings. If there is no `SafetySetting` for a given - * `SafetyCategory` provided in the list, the API will use the default safety - * setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH, - * HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, - * HARM_CATEGORY_HARASSMENT are supported. - * Refer to the - * [guide](https://ai.google.dev/gemini-api/docs/safety-settings) - * for detailed information on available safety settings. Also refer to the - * [Safety guidance](https://ai.google.dev/gemini-api/docs/safety-guidance) to - * learn how to incorporate safety considerations in your AI applications. - * @param {number} [request.temperature] - * Optional. Controls the randomness of the output. - * - * Values can range from [0.0,1.0], inclusive. A value closer to 1.0 will - * produce responses that are more varied and creative, while a value closer - * to 0.0 will typically result in more straightforward responses from the - * model. A low temperature (~0.2) is usually recommended for - * Attributed-Question-Answering use cases. - * @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.ai.generativelanguage.v1beta.GenerateAnswerResponse|GenerateAnswerResponse}. - * 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/v1beta/generative_service.generate_answer.js - * region_tag:generativelanguage_v1beta_generated_GenerativeService_GenerateAnswer_async - */ + /** + * Generates a grounded answer from the model given an input + * `GenerateAnswerRequest`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ai.generativelanguage.v1beta.GroundingPassages} request.inlinePassages + * Passages provided inline with the request. + * @param {google.ai.generativelanguage.v1beta.SemanticRetrieverConfig} request.semanticRetriever + * Content retrieved from resources created via the Semantic Retriever + * API. + * @param {string} request.model + * Required. The name of the `Model` to use for generating the grounded + * response. + * + * Format: `model=models/{model}`. + * @param {number[]} request.contents + * Required. The content of the current conversation with the `Model`. For + * single-turn queries, this is a single question to answer. For multi-turn + * queries, this is a repeated field that contains conversation history and + * the last `Content` in the list containing the question. + * + * Note: `GenerateAnswer` only supports queries in English. + * @param {google.ai.generativelanguage.v1beta.GenerateAnswerRequest.AnswerStyle} request.answerStyle + * Required. Style in which answers should be returned. + * @param {number[]} [request.safetySettings] + * Optional. A list of unique `SafetySetting` instances for blocking unsafe + * content. + * + * This will be enforced on the `GenerateAnswerRequest.contents` and + * `GenerateAnswerResponse.candidate`. There should not be more than one + * setting for each `SafetyCategory` type. The API will block any contents and + * responses that fail to meet the thresholds set by these settings. This list + * overrides the default settings for each `SafetyCategory` specified in the + * safety_settings. If there is no `SafetySetting` for a given + * `SafetyCategory` provided in the list, the API will use the default safety + * setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH, + * HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, + * HARM_CATEGORY_HARASSMENT are supported. + * Refer to the + * [guide](https://ai.google.dev/gemini-api/docs/safety-settings) + * for detailed information on available safety settings. Also refer to the + * [Safety guidance](https://ai.google.dev/gemini-api/docs/safety-guidance) to + * learn how to incorporate safety considerations in your AI applications. + * @param {number} [request.temperature] + * Optional. Controls the randomness of the output. + * + * Values can range from [0.0,1.0], inclusive. A value closer to 1.0 will + * produce responses that are more varied and creative, while a value closer + * to 0.0 will typically result in more straightforward responses from the + * model. A low temperature (~0.2) is usually recommended for + * Attributed-Question-Answering use cases. + * @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.ai.generativelanguage.v1beta.GenerateAnswerResponse|GenerateAnswerResponse}. + * 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/v1beta/generative_service.generate_answer.js + * region_tag:generativelanguage_v1beta_generated_GenerativeService_GenerateAnswer_async + */ generateAnswer( - request?: protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IGenerateAnswerResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IGenerateAnswerResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest + | undefined + ), + {} | undefined, + ] + >; generateAnswer( - request: protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IGenerateAnswerResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IGenerateAnswerResponse, + | protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateAnswer( - request: protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IGenerateAnswerResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IGenerateAnswerResponse, + | protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateAnswer( - request?: protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.IGenerateAnswerResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IGenerateAnswerResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IGenerateAnswerResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IGenerateAnswerResponse, + | protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IGenerateAnswerResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('generateAnswer request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.IGenerateAnswerResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IGenerateAnswerResponse, + | protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('generateAnswer response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.generateAnswer(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.IGenerateAnswerResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest|undefined, - {}|undefined - ]) => { - this._log.info('generateAnswer response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .generateAnswer(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IGenerateAnswerResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IGenerateAnswerRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('generateAnswer response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Generates a text embedding vector from the input `Content` using the - * specified [Gemini Embedding - * model](https://ai.google.dev/gemini-api/docs/models/gemini#text-embedding). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The model's resource name. This serves as an ID for the Model to - * use. - * - * This name should match a model name returned by the `ListModels` method. - * - * Format: `models/{model}` - * @param {google.ai.generativelanguage.v1beta.Content} request.content - * Required. The content to embed. Only the `parts.text` fields will be - * counted. - * @param {google.ai.generativelanguage.v1beta.TaskType} [request.taskType] - * Optional. Optional task type for which the embeddings will be used. Not - * supported on earlier models (`models/embedding-001`). - * @param {string} [request.title] - * Optional. An optional title for the text. Only applicable when TaskType is - * `RETRIEVAL_DOCUMENT`. - * - * Note: Specifying a `title` for `RETRIEVAL_DOCUMENT` provides better quality - * embeddings for retrieval. - * @param {number} [request.outputDimensionality] - * Optional. Optional reduced dimension for the output embedding. If set, - * excessive values in the output embedding are truncated from the end. - * Supported by newer models since 2024 only. You cannot set this value if - * using the earlier model (`models/embedding-001`). - * @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.ai.generativelanguage.v1beta.EmbedContentResponse|EmbedContentResponse}. - * 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/v1beta/generative_service.embed_content.js - * region_tag:generativelanguage_v1beta_generated_GenerativeService_EmbedContent_async - */ + /** + * Generates a text embedding vector from the input `Content` using the + * specified [Gemini Embedding + * model](https://ai.google.dev/gemini-api/docs/models/gemini#text-embedding). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The model's resource name. This serves as an ID for the Model to + * use. + * + * This name should match a model name returned by the `ListModels` method. + * + * Format: `models/{model}` + * @param {google.ai.generativelanguage.v1beta.Content} request.content + * Required. The content to embed. Only the `parts.text` fields will be + * counted. + * @param {google.ai.generativelanguage.v1beta.TaskType} [request.taskType] + * Optional. Optional task type for which the embeddings will be used. Not + * supported on earlier models (`models/embedding-001`). + * @param {string} [request.title] + * Optional. An optional title for the text. Only applicable when TaskType is + * `RETRIEVAL_DOCUMENT`. + * + * Note: Specifying a `title` for `RETRIEVAL_DOCUMENT` provides better quality + * embeddings for retrieval. + * @param {number} [request.outputDimensionality] + * Optional. Optional reduced dimension for the output embedding. If set, + * excessive values in the output embedding are truncated from the end. + * Supported by newer models since 2024 only. You cannot set this value if + * using the earlier model (`models/embedding-001`). + * @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.ai.generativelanguage.v1beta.EmbedContentResponse|EmbedContentResponse}. + * 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/v1beta/generative_service.embed_content.js + * region_tag:generativelanguage_v1beta_generated_GenerativeService_EmbedContent_async + */ embedContent( - request?: protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IEmbedContentResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest + | undefined + ), + {} | undefined, + ] + >; embedContent( - request: protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IEmbedContentResponse, + | protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; embedContent( - request: protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IEmbedContentResponse, + | protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; embedContent( - request?: protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IEmbedContentResponse, + | protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IEmbedContentResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('embedContent request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IEmbedContentResponse, + | protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('embedContent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.embedContent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.IEmbedContentResponse, - protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest|undefined, - {}|undefined - ]) => { - this._log.info('embedContent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .embedContent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IEmbedContentResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IEmbedContentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('embedContent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Generates multiple embedding vectors from the input `Content` which - * consists of a batch of strings represented as `EmbedContentRequest` - * objects. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The model's resource name. This serves as an ID for the Model to - * use. - * - * This name should match a model name returned by the `ListModels` method. - * - * Format: `models/{model}` - * @param {number[]} request.requests - * Required. Embed requests for the batch. The model in each of these requests - * must match the model specified `BatchEmbedContentsRequest.model`. - * @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.ai.generativelanguage.v1beta.BatchEmbedContentsResponse|BatchEmbedContentsResponse}. - * 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/v1beta/generative_service.batch_embed_contents.js - * region_tag:generativelanguage_v1beta_generated_GenerativeService_BatchEmbedContents_async - */ + /** + * Generates multiple embedding vectors from the input `Content` which + * consists of a batch of strings represented as `EmbedContentRequest` + * objects. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The model's resource name. This serves as an ID for the Model to + * use. + * + * This name should match a model name returned by the `ListModels` method. + * + * Format: `models/{model}` + * @param {number[]} request.requests + * Required. Embed requests for the batch. The model in each of these requests + * must match the model specified `BatchEmbedContentsRequest.model`. + * @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.ai.generativelanguage.v1beta.BatchEmbedContentsResponse|BatchEmbedContentsResponse}. + * 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/v1beta/generative_service.batch_embed_contents.js + * region_tag:generativelanguage_v1beta_generated_GenerativeService_BatchEmbedContents_async + */ batchEmbedContents( - request?: protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest + | undefined + ), + {} | undefined, + ] + >; batchEmbedContents( - request: protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsResponse, + | protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchEmbedContents( - request: protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsResponse, + | protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchEmbedContents( - request?: protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsResponse, + | protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('batchEmbedContents request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsResponse, + | protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchEmbedContents response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.batchEmbedContents(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsResponse, - protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest|undefined, - {}|undefined - ]) => { - this._log.info('batchEmbedContents response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchEmbedContents(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchEmbedContents response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Runs a model's tokenizer on input `Content` and returns the token count. - * Refer to the [tokens guide](https://ai.google.dev/gemini-api/docs/tokens) - * to learn more about tokens. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The model's resource name. This serves as an ID for the Model to - * use. - * - * This name should match a model name returned by the `ListModels` method. - * - * Format: `models/{model}` - * @param {number[]} [request.contents] - * Optional. The input given to the model as a prompt. This field is ignored - * when `generate_content_request` is set. - * @param {google.ai.generativelanguage.v1beta.GenerateContentRequest} [request.generateContentRequest] - * Optional. The overall input given to the `Model`. This includes the prompt - * as well as other model steering information like [system - * instructions](https://ai.google.dev/gemini-api/docs/system-instructions), - * and/or function declarations for [function - * calling](https://ai.google.dev/gemini-api/docs/function-calling). - * `Model`s/`Content`s and `generate_content_request`s are mutually - * exclusive. You can either send `Model` + `Content`s or a - * `generate_content_request`, but never both. - * @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.ai.generativelanguage.v1beta.CountTokensResponse|CountTokensResponse}. - * 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/v1beta/generative_service.count_tokens.js - * region_tag:generativelanguage_v1beta_generated_GenerativeService_CountTokens_async - */ + /** + * Runs a model's tokenizer on input `Content` and returns the token count. + * Refer to the [tokens guide](https://ai.google.dev/gemini-api/docs/tokens) + * to learn more about tokens. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The model's resource name. This serves as an ID for the Model to + * use. + * + * This name should match a model name returned by the `ListModels` method. + * + * Format: `models/{model}` + * @param {number[]} [request.contents] + * Optional. The input given to the model as a prompt. This field is ignored + * when `generate_content_request` is set. + * @param {google.ai.generativelanguage.v1beta.GenerateContentRequest} [request.generateContentRequest] + * Optional. The overall input given to the `Model`. This includes the prompt + * as well as other model steering information like [system + * instructions](https://ai.google.dev/gemini-api/docs/system-instructions), + * and/or function declarations for [function + * calling](https://ai.google.dev/gemini-api/docs/function-calling). + * `Model`s/`Content`s and `generate_content_request`s are mutually + * exclusive. You can either send `Model` + `Content`s or a + * `generate_content_request`, but never both. + * @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.ai.generativelanguage.v1beta.CountTokensResponse|CountTokensResponse}. + * 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/v1beta/generative_service.count_tokens.js + * region_tag:generativelanguage_v1beta_generated_GenerativeService_CountTokens_async + */ countTokens( - request?: protos.google.ai.generativelanguage.v1beta.ICountTokensRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICountTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountTokensRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.ICountTokensRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICountTokensResponse, + ( + | protos.google.ai.generativelanguage.v1beta.ICountTokensRequest + | undefined + ), + {} | undefined, + ] + >; countTokens( - request: protos.google.ai.generativelanguage.v1beta.ICountTokensRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ICountTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountTokensRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.ICountTokensRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ICountTokensResponse, + | protos.google.ai.generativelanguage.v1beta.ICountTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): void; countTokens( - request: protos.google.ai.generativelanguage.v1beta.ICountTokensRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ICountTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountTokensRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.ICountTokensRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ICountTokensResponse, + | protos.google.ai.generativelanguage.v1beta.ICountTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): void; countTokens( - request?: protos.google.ai.generativelanguage.v1beta.ICountTokensRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.ICountTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountTokensRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.ICountTokensRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.ICountTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountTokensRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICountTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountTokensRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.ICountTokensRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.ICountTokensResponse, + | protos.google.ai.generativelanguage.v1beta.ICountTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICountTokensResponse, + ( + | protos.google.ai.generativelanguage.v1beta.ICountTokensRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('countTokens request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.ICountTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountTokensRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.ICountTokensResponse, + | protos.google.ai.generativelanguage.v1beta.ICountTokensRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('countTokens response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.countTokens(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.ICountTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountTokensRequest|undefined, - {}|undefined - ]) => { - this._log.info('countTokens response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .countTokens(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.ICountTokensResponse, + ( + | protos.google.ai.generativelanguage.v1beta.ICountTokensRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('countTokens response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Generates a [streamed - * response](https://ai.google.dev/gemini-api/docs/text-generation?lang=python#generate-a-text-stream) - * from the model given an input `GenerateContentRequest`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The name of the `Model` to use for generating the completion. - * - * Format: `models/{model}`. - * @param {google.ai.generativelanguage.v1beta.Content} [request.systemInstruction] - * Optional. Developer set [system - * instruction(s)](https://ai.google.dev/gemini-api/docs/system-instructions). - * Currently, text only. - * @param {number[]} request.contents - * Required. The content of the current conversation with the model. - * - * For single-turn queries, this is a single instance. For multi-turn queries - * like [chat](https://ai.google.dev/gemini-api/docs/text-generation#chat), - * this is a repeated field that contains the conversation history and the - * latest request. - * @param {number[]} [request.tools] - * Optional. A list of `Tools` the `Model` may use to generate the next - * response. - * - * A `Tool` is a piece of code that enables the system to interact with - * external systems to perform an action, or set of actions, outside of - * knowledge and scope of the `Model`. Supported `Tool`s are `Function` and - * `code_execution`. Refer to the [Function - * calling](https://ai.google.dev/gemini-api/docs/function-calling) and the - * [Code execution](https://ai.google.dev/gemini-api/docs/code-execution) - * guides to learn more. - * @param {google.ai.generativelanguage.v1beta.ToolConfig} [request.toolConfig] - * Optional. Tool configuration for any `Tool` specified in the request. Refer - * to the [Function calling - * guide](https://ai.google.dev/gemini-api/docs/function-calling#function_calling_mode) - * for a usage example. - * @param {number[]} [request.safetySettings] - * Optional. A list of unique `SafetySetting` instances for blocking unsafe - * content. - * - * This will be enforced on the `GenerateContentRequest.contents` and - * `GenerateContentResponse.candidates`. There should not be more than one - * setting for each `SafetyCategory` type. The API will block any contents and - * responses that fail to meet the thresholds set by these settings. This list - * overrides the default settings for each `SafetyCategory` specified in the - * safety_settings. If there is no `SafetySetting` for a given - * `SafetyCategory` provided in the list, the API will use the default safety - * setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH, - * HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, - * HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY are supported. - * Refer to the [guide](https://ai.google.dev/gemini-api/docs/safety-settings) - * for detailed information on available safety settings. Also refer to the - * [Safety guidance](https://ai.google.dev/gemini-api/docs/safety-guidance) to - * learn how to incorporate safety considerations in your AI applications. - * @param {google.ai.generativelanguage.v1beta.GenerationConfig} [request.generationConfig] - * Optional. Configuration options for model generation and outputs. - * @param {string} [request.cachedContent] - * Optional. The name of the content - * [cached](https://ai.google.dev/gemini-api/docs/caching) to use as context - * to serve the prediction. Format: `cachedContents/{cachedContent}` - * @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.ai.generativelanguage.v1beta.GenerateContentResponse|GenerateContentResponse} 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/v1beta/generative_service.stream_generate_content.js - * region_tag:generativelanguage_v1beta_generated_GenerativeService_StreamGenerateContent_async - */ + /** + * Generates a [streamed + * response](https://ai.google.dev/gemini-api/docs/text-generation?lang=python#generate-a-text-stream) + * from the model given an input `GenerateContentRequest`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The name of the `Model` to use for generating the completion. + * + * Format: `models/{model}`. + * @param {google.ai.generativelanguage.v1beta.Content} [request.systemInstruction] + * Optional. Developer set [system + * instruction(s)](https://ai.google.dev/gemini-api/docs/system-instructions). + * Currently, text only. + * @param {number[]} request.contents + * Required. The content of the current conversation with the model. + * + * For single-turn queries, this is a single instance. For multi-turn queries + * like [chat](https://ai.google.dev/gemini-api/docs/text-generation#chat), + * this is a repeated field that contains the conversation history and the + * latest request. + * @param {number[]} [request.tools] + * Optional. A list of `Tools` the `Model` may use to generate the next + * response. + * + * A `Tool` is a piece of code that enables the system to interact with + * external systems to perform an action, or set of actions, outside of + * knowledge and scope of the `Model`. Supported `Tool`s are `Function` and + * `code_execution`. Refer to the [Function + * calling](https://ai.google.dev/gemini-api/docs/function-calling) and the + * [Code execution](https://ai.google.dev/gemini-api/docs/code-execution) + * guides to learn more. + * @param {google.ai.generativelanguage.v1beta.ToolConfig} [request.toolConfig] + * Optional. Tool configuration for any `Tool` specified in the request. Refer + * to the [Function calling + * guide](https://ai.google.dev/gemini-api/docs/function-calling#function_calling_mode) + * for a usage example. + * @param {number[]} [request.safetySettings] + * Optional. A list of unique `SafetySetting` instances for blocking unsafe + * content. + * + * This will be enforced on the `GenerateContentRequest.contents` and + * `GenerateContentResponse.candidates`. There should not be more than one + * setting for each `SafetyCategory` type. The API will block any contents and + * responses that fail to meet the thresholds set by these settings. This list + * overrides the default settings for each `SafetyCategory` specified in the + * safety_settings. If there is no `SafetySetting` for a given + * `SafetyCategory` provided in the list, the API will use the default safety + * setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH, + * HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, + * HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY are supported. + * Refer to the [guide](https://ai.google.dev/gemini-api/docs/safety-settings) + * for detailed information on available safety settings. Also refer to the + * [Safety guidance](https://ai.google.dev/gemini-api/docs/safety-guidance) to + * learn how to incorporate safety considerations in your AI applications. + * @param {google.ai.generativelanguage.v1beta.GenerationConfig} [request.generationConfig] + * Optional. Configuration options for model generation and outputs. + * @param {string} [request.cachedContent] + * Optional. The name of the content + * [cached](https://ai.google.dev/gemini-api/docs/caching) to use as context + * to serve the prediction. Format: `cachedContents/{cachedContent}` + * @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.ai.generativelanguage.v1beta.GenerateContentResponse|GenerateContentResponse} 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/v1beta/generative_service.stream_generate_content.js + * region_tag:generativelanguage_v1beta_generated_GenerativeService_StreamGenerateContent_async + */ streamGenerateContent( - request?: protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest, - options?: CallOptions): - gax.CancellableStream{ + request?: protos.google.ai.generativelanguage.v1beta.IGenerateContentRequest, + 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('streamGenerateContent stream %j', options); return this.innerApiCalls.streamGenerateContent(request, options); } -/** - * Low-Latency bidirectional streaming API that supports audio and video - * streaming inputs can produce multimodal output streams (audio and text). - * - * @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.ai.generativelanguage.v1beta.BidiGenerateContentClientMessage|BidiGenerateContentClientMessage} for write() method, and - * will emit objects representing {@link protos.google.ai.generativelanguage.v1beta.BidiGenerateContentServerMessage|BidiGenerateContentServerMessage} 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/v1beta/generative_service.bidi_generate_content.js - * region_tag:generativelanguage_v1beta_generated_GenerativeService_BidiGenerateContent_async - */ - bidiGenerateContent( - options?: CallOptions): - gax.CancellableStream { - this.initialize().catch(err => {throw err}); + /** + * Low-Latency bidirectional streaming API that supports audio and video + * streaming inputs can produce multimodal output streams (audio and text). + * + * @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.ai.generativelanguage.v1beta.BidiGenerateContentClientMessage|BidiGenerateContentClientMessage} for write() method, and + * will emit objects representing {@link protos.google.ai.generativelanguage.v1beta.BidiGenerateContentServerMessage|BidiGenerateContentServerMessage} 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/v1beta/generative_service.bidi_generate_content.js + * region_tag:generativelanguage_v1beta_generated_GenerativeService_BidiGenerateContent_async + */ + bidiGenerateContent(options?: CallOptions): gax.CancellableStream { + this.initialize().catch((err) => { + throw err; + }); this._log.info('bidiGenerateContent stream %j', options); return this.innerApiCalls.bidiGenerateContent(null, options); } @@ -1115,7 +1419,7 @@ export class GenerativeServiceClient { * @param {string} id * @returns {string} Resource name string. */ - cachedContentPath(id:string) { + cachedContentPath(id: string) { return this.pathTemplates.cachedContentPathTemplate.render({ id: id, }); @@ -1129,7 +1433,8 @@ export class GenerativeServiceClient { * @returns {string} A string representing the id. */ matchIdFromCachedContentName(cachedContentName: string) { - return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName).id; + return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName) + .id; } /** @@ -1140,7 +1445,7 @@ export class GenerativeServiceClient { * @param {string} chunk * @returns {string} Resource name string. */ - chunkPath(corpus:string,document:string,chunk:string) { + chunkPath(corpus: string, document: string, chunk: string) { return this.pathTemplates.chunkPathTemplate.render({ corpus: corpus, document: document, @@ -1187,7 +1492,7 @@ export class GenerativeServiceClient { * @param {string} corpus * @returns {string} Resource name string. */ - corpusPath(corpus:string) { + corpusPath(corpus: string) { return this.pathTemplates.corpusPathTemplate.render({ corpus: corpus, }); @@ -1211,7 +1516,7 @@ export class GenerativeServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - corpusPermissionsPath(corpus:string,permission:string) { + corpusPermissionsPath(corpus: string, permission: string) { return this.pathTemplates.corpusPermissionsPathTemplate.render({ corpus: corpus, permission: permission, @@ -1226,7 +1531,9 @@ export class GenerativeServiceClient { * @returns {string} A string representing the corpus. */ matchCorpusFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).corpus; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).corpus; } /** @@ -1237,7 +1544,9 @@ export class GenerativeServiceClient { * @returns {string} A string representing the permission. */ matchPermissionFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).permission; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).permission; } /** @@ -1247,7 +1556,7 @@ export class GenerativeServiceClient { * @param {string} document * @returns {string} Resource name string. */ - documentPath(corpus:string,document:string) { + documentPath(corpus: string, document: string) { return this.pathTemplates.documentPathTemplate.render({ corpus: corpus, document: document, @@ -1282,7 +1591,7 @@ export class GenerativeServiceClient { * @param {string} file * @returns {string} Resource name string. */ - filePath(file:string) { + filePath(file: string) { return this.pathTemplates.filePathTemplate.render({ file: file, }); @@ -1305,7 +1614,7 @@ export class GenerativeServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -1328,7 +1637,7 @@ export class GenerativeServiceClient { * @param {string} tuned_model * @returns {string} Resource name string. */ - tunedModelPath(tunedModel:string) { + tunedModelPath(tunedModel: string) { return this.pathTemplates.tunedModelPathTemplate.render({ tuned_model: tunedModel, }); @@ -1342,7 +1651,8 @@ export class GenerativeServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromTunedModelName(tunedModelName: string) { - return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName).tuned_model; + return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName) + .tuned_model; } /** @@ -1352,7 +1662,7 @@ export class GenerativeServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - tunedModelPermissionsPath(tunedModel:string,permission:string) { + tunedModelPermissionsPath(tunedModel: string, permission: string) { return this.pathTemplates.tunedModelPermissionsPathTemplate.render({ tuned_model: tunedModel, permission: permission, @@ -1366,8 +1676,12 @@ export class GenerativeServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the tuned_model. */ - matchTunedModelFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).tuned_model; + matchTunedModelFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).tuned_model; } /** @@ -1377,8 +1691,12 @@ export class GenerativeServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the permission. */ - matchPermissionFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).permission; + matchPermissionFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).permission; } /** @@ -1389,7 +1707,7 @@ export class GenerativeServiceClient { */ close(): Promise { if (this.generativeServiceStub && !this._terminated) { - return this.generativeServiceStub.then(stub => { + return this.generativeServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1397,4 +1715,4 @@ export class GenerativeServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1beta/index.ts b/packages/google-ai-generativelanguage/src/v1beta/index.ts index 0990437bcba5..0cd29f98b444 100644 --- a/packages/google-ai-generativelanguage/src/v1beta/index.ts +++ b/packages/google-ai-generativelanguage/src/v1beta/index.ts @@ -16,12 +16,12 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {CacheServiceClient} from './cache_service_client'; -export {DiscussServiceClient} from './discuss_service_client'; -export {FileServiceClient} from './file_service_client'; -export {GenerativeServiceClient} from './generative_service_client'; -export {ModelServiceClient} from './model_service_client'; -export {PermissionServiceClient} from './permission_service_client'; -export {PredictionServiceClient} from './prediction_service_client'; -export {RetrieverServiceClient} from './retriever_service_client'; -export {TextServiceClient} from './text_service_client'; +export { CacheServiceClient } from './cache_service_client'; +export { DiscussServiceClient } from './discuss_service_client'; +export { FileServiceClient } from './file_service_client'; +export { GenerativeServiceClient } from './generative_service_client'; +export { ModelServiceClient } from './model_service_client'; +export { PermissionServiceClient } from './permission_service_client'; +export { PredictionServiceClient } from './prediction_service_client'; +export { RetrieverServiceClient } from './retriever_service_client'; +export { TextServiceClient } from './text_service_client'; diff --git a/packages/google-ai-generativelanguage/src/v1beta/model_service_client.ts b/packages/google-ai-generativelanguage/src/v1beta/model_service_client.ts index ea71c3139636..0e414b017a22 100644 --- a/packages/google-ai-generativelanguage/src/v1beta/model_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1beta/model_service_client.ts @@ -18,11 +18,20 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +53,7 @@ export class ModelServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -57,10 +66,10 @@ export class ModelServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - modelServiceStub?: Promise<{[name: string]: Function}>; + modelServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ModelServiceClient. @@ -101,21 +110,42 @@ export class ModelServiceClient { * const client = new ModelServiceClient({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 ModelServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -140,7 +170,7 @@ export class ModelServiceClient { 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; @@ -154,10 +184,7 @@ export class ModelServiceClient { } // 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 { @@ -179,31 +206,25 @@ export class ModelServiceClient { // Create useful helper objects for these. this.pathTemplates = { cachedContentPathTemplate: new this._gaxModule.PathTemplate( - 'cachedContents/{id}' + 'cachedContents/{id}', ), chunkPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}/chunks/{chunk}' - ), - corpusPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}' + 'corpora/{corpus}/documents/{document}/chunks/{chunk}', ), + corpusPathTemplate: new this._gaxModule.PathTemplate('corpora/{corpus}'), corpusPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/permissions/{permission}' + 'corpora/{corpus}/permissions/{permission}', ), documentPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}' - ), - filePathTemplate: new this._gaxModule.PathTemplate( - 'files/{file}' - ), - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' + 'corpora/{corpus}/documents/{document}', ), + filePathTemplate: new this._gaxModule.PathTemplate('files/{file}'), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), tunedModelPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}' + 'tunedModels/{tuned_model}', ), tunedModelPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}/permissions/{permission}' + 'tunedModels/{tuned_model}/permissions/{permission}', ), }; @@ -211,10 +232,16 @@ export class ModelServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listModels: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'models'), - listTunedModels: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'tunedModels') + listModels: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'models', + ), + listTunedModels: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'tunedModels', + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -223,31 +250,64 @@ export class ModelServiceClient { // 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: '/v1beta/{name=batches/*}:cancel',},{selector: 'google.longrunning.Operations.DeleteOperation',delete: '/v1beta/{name=batches/*}',},{selector: 'google.longrunning.Operations.GetOperation',get: '/v1beta/{name=tunedModels/*/operations/*}',additional_bindings: [{get: '/v1beta/{name=generatedFiles/*/operations/*}',},{get: '/v1beta/{name=batches/*}',},{get: '/v1beta/{name=models/*/operations/*}',},{get: '/v1beta/{name=corpora/*/operations/*}',}], - },{selector: 'google.longrunning.Operations.ListOperations',get: '/v1beta/{name=tunedModels/*}/operations',additional_bindings: [{get: '/v1beta/{name=batches}',},{get: '/v1beta/{name=models/*}/operations',}], - }]; + lroOptions.httpRules = [ + { + selector: 'google.longrunning.Operations.CancelOperation', + post: '/v1beta/{name=batches/*}:cancel', + }, + { + selector: 'google.longrunning.Operations.DeleteOperation', + delete: '/v1beta/{name=batches/*}', + }, + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v1beta/{name=tunedModels/*/operations/*}', + additional_bindings: [ + { get: '/v1beta/{name=generatedFiles/*/operations/*}' }, + { get: '/v1beta/{name=batches/*}' }, + { get: '/v1beta/{name=models/*/operations/*}' }, + { get: '/v1beta/{name=corpora/*/operations/*}' }, + ], + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v1beta/{name=tunedModels/*}/operations', + additional_bindings: [ + { get: '/v1beta/{name=batches}' }, + { get: '/v1beta/{name=models/*}/operations' }, + ], + }, + ]; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const createTunedModelResponse = protoFilesRoot.lookup( - '.google.ai.generativelanguage.v1beta.TunedModel') as gax.protobuf.Type; + '.google.ai.generativelanguage.v1beta.TunedModel', + ) as gax.protobuf.Type; const createTunedModelMetadata = protoFilesRoot.lookup( - '.google.ai.generativelanguage.v1beta.CreateTunedModelMetadata') as gax.protobuf.Type; + '.google.ai.generativelanguage.v1beta.CreateTunedModelMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { createTunedModel: new this._gaxModule.LongrunningDescriptor( this.operationsClient, createTunedModelResponse.decode.bind(createTunedModelResponse), - createTunedModelMetadata.decode.bind(createTunedModelMetadata)) + createTunedModelMetadata.decode.bind(createTunedModelMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1beta.ModelService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1beta.ModelService', + 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 @@ -278,28 +338,42 @@ export class ModelServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1beta.ModelService. this.modelServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1beta.ModelService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1beta.ModelService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1beta.ModelService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1beta + .ModelService, + 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 modelServiceStubMethods = - ['getModel', 'listModels', 'getTunedModel', 'listTunedModels', 'createTunedModel', 'updateTunedModel', 'deleteTunedModel']; + const modelServiceStubMethods = [ + 'getModel', + 'listModels', + 'getTunedModel', + 'listTunedModels', + 'createTunedModel', + 'updateTunedModel', + 'deleteTunedModel', + ]; for (const methodName of modelServiceStubMethods) { const callPromise = this.modelServiceStub.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] || @@ -309,7 +383,7 @@ export class ModelServiceClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -324,8 +398,14 @@ export class ModelServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -336,8 +416,14 @@ export class ModelServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -377,8 +463,9 @@ export class ModelServiceClient { * 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; @@ -389,595 +476,874 @@ export class ModelServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets information about a specific `Model` such as its version number, token - * limits, - * [parameters](https://ai.google.dev/gemini-api/docs/models/generative-models#model-parameters) - * and other metadata. Refer to the [Gemini models - * guide](https://ai.google.dev/gemini-api/docs/models/gemini) for detailed - * model information. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the model. - * - * This name should match a model name returned by the `ListModels` method. - * - * Format: `models/{model}` - * @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.ai.generativelanguage.v1beta.Model|Model}. - * 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/v1beta/model_service.get_model.js - * region_tag:generativelanguage_v1beta_generated_ModelService_GetModel_async - */ + /** + * Gets information about a specific `Model` such as its version number, token + * limits, + * [parameters](https://ai.google.dev/gemini-api/docs/models/generative-models#model-parameters) + * and other metadata. Refer to the [Gemini models + * guide](https://ai.google.dev/gemini-api/docs/models/gemini) for detailed + * model information. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the model. + * + * This name should match a model name returned by the `ListModels` method. + * + * Format: `models/{model}` + * @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.ai.generativelanguage.v1beta.Model|Model}. + * 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/v1beta/model_service.get_model.js + * region_tag:generativelanguage_v1beta_generated_ModelService_GetModel_async + */ getModel( - request?: protos.google.ai.generativelanguage.v1beta.IGetModelRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IModel, - protos.google.ai.generativelanguage.v1beta.IGetModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IGetModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IModel, + protos.google.ai.generativelanguage.v1beta.IGetModelRequest | undefined, + {} | undefined, + ] + >; getModel( - request: protos.google.ai.generativelanguage.v1beta.IGetModelRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IModel, - protos.google.ai.generativelanguage.v1beta.IGetModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGetModelRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IModel, + | protos.google.ai.generativelanguage.v1beta.IGetModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getModel( - request: protos.google.ai.generativelanguage.v1beta.IGetModelRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IModel, - protos.google.ai.generativelanguage.v1beta.IGetModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGetModelRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IModel, + | protos.google.ai.generativelanguage.v1beta.IGetModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getModel( - request?: protos.google.ai.generativelanguage.v1beta.IGetModelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.IModel, - protos.google.ai.generativelanguage.v1beta.IGetModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IGetModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IModel, - protos.google.ai.generativelanguage.v1beta.IGetModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IModel, - protos.google.ai.generativelanguage.v1beta.IGetModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IGetModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IModel, + | protos.google.ai.generativelanguage.v1beta.IGetModelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IModel, + protos.google.ai.generativelanguage.v1beta.IGetModelRequest | 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('getModel request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.IModel, - protos.google.ai.generativelanguage.v1beta.IGetModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IModel, + | protos.google.ai.generativelanguage.v1beta.IGetModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getModel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.IModel, - protos.google.ai.generativelanguage.v1beta.IGetModelRequest|undefined, - {}|undefined - ]) => { - this._log.info('getModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IModel, + ( + | protos.google.ai.generativelanguage.v1beta.IGetModelRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets information about a specific TunedModel. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the model. - * - * Format: `tunedModels/my-model-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.ai.generativelanguage.v1beta.TunedModel|TunedModel}. - * 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/v1beta/model_service.get_tuned_model.js - * region_tag:generativelanguage_v1beta_generated_ModelService_GetTunedModel_async - */ + /** + * Gets information about a specific TunedModel. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the model. + * + * Format: `tunedModels/my-model-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.ai.generativelanguage.v1beta.TunedModel|TunedModel}. + * 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/v1beta/model_service.get_tuned_model.js + * region_tag:generativelanguage_v1beta_generated_ModelService_GetTunedModel_async + */ getTunedModel( - request?: protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ITunedModel, - protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ITunedModel, + ( + | protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest + | undefined + ), + {} | undefined, + ] + >; getTunedModel( - request: protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ITunedModel, - protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ITunedModel, + | protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getTunedModel( - request: protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ITunedModel, - protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ITunedModel, + | protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getTunedModel( - request?: protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.ITunedModel, - protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.ITunedModel, - protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ITunedModel, - protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.ITunedModel, + | protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ITunedModel, + ( + | protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest + | 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('getTunedModel request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.ITunedModel, - protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.ITunedModel, + | protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getTunedModel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getTunedModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.ITunedModel, - protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest|undefined, - {}|undefined - ]) => { - this._log.info('getTunedModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getTunedModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.ITunedModel, + ( + | protos.google.ai.generativelanguage.v1beta.IGetTunedModelRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getTunedModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a tuned model. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ai.generativelanguage.v1beta.TunedModel} request.tunedModel - * Required. The tuned model to update. - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. The list of fields to update. - * @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.ai.generativelanguage.v1beta.TunedModel|TunedModel}. - * 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/v1beta/model_service.update_tuned_model.js - * region_tag:generativelanguage_v1beta_generated_ModelService_UpdateTunedModel_async - */ + /** + * Updates a tuned model. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ai.generativelanguage.v1beta.TunedModel} request.tunedModel + * Required. The tuned model to update. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. The list of fields to update. + * @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.ai.generativelanguage.v1beta.TunedModel|TunedModel}. + * 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/v1beta/model_service.update_tuned_model.js + * region_tag:generativelanguage_v1beta_generated_ModelService_UpdateTunedModel_async + */ updateTunedModel( - request?: protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ITunedModel, - protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ITunedModel, + ( + | protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest + | undefined + ), + {} | undefined, + ] + >; updateTunedModel( - request: protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ITunedModel, - protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ITunedModel, + | protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateTunedModel( - request: protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ITunedModel, - protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ITunedModel, + | protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateTunedModel( - request?: protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.ITunedModel, - protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.ITunedModel, - protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ITunedModel, - protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.ITunedModel, + | protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ITunedModel, + ( + | protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest + | 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({ - 'tuned_model.name': request.tunedModel!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'tuned_model.name': request.tunedModel!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateTunedModel request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.ITunedModel, - protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.ITunedModel, + | protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateTunedModel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateTunedModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.ITunedModel, - protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateTunedModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateTunedModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.ITunedModel, + ( + | protos.google.ai.generativelanguage.v1beta.IUpdateTunedModelRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateTunedModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a tuned model. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the model. - * Format: `tunedModels/my-model-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 include:samples/generated/v1beta/model_service.delete_tuned_model.js - * region_tag:generativelanguage_v1beta_generated_ModelService_DeleteTunedModel_async - */ + /** + * Deletes a tuned model. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the model. + * Format: `tunedModels/my-model-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 include:samples/generated/v1beta/model_service.delete_tuned_model.js + * region_tag:generativelanguage_v1beta_generated_ModelService_DeleteTunedModel_async + */ deleteTunedModel( - request?: protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest + | undefined + ), + {} | undefined, + ] + >; deleteTunedModel( - request: protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteTunedModel( - request: protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteTunedModel( - request?: protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest + | 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('deleteTunedModel request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteTunedModel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteTunedModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteTunedModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteTunedModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta.IDeleteTunedModelRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteTunedModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a tuned model. - * Check intermediate tuning progress (if any) through the - * [google.longrunning.Operations] service. - * - * Access status and results through the Operations service. - * Example: - * GET /v1/tunedModels/az2mb0bpw6i/operations/000-111-222 - * - * @param {Object} request - * The request object that will be sent. - * @param {string} [request.tunedModelId] - * Optional. The unique id for the tuned model if specified. - * This value should be up to 40 characters, the first character must be a - * letter, the last could be a letter or a number. The id must match the - * regular expression: `[a-z]([a-z0-9-]{0,38}[a-z0-9])?`. - * @param {google.ai.generativelanguage.v1beta.TunedModel} request.tunedModel - * Required. The tuned model 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 include:samples/generated/v1beta/model_service.create_tuned_model.js - * region_tag:generativelanguage_v1beta_generated_ModelService_CreateTunedModel_async - */ + /** + * Creates a tuned model. + * Check intermediate tuning progress (if any) through the + * [google.longrunning.Operations] service. + * + * Access status and results through the Operations service. + * Example: + * GET /v1/tunedModels/az2mb0bpw6i/operations/000-111-222 + * + * @param {Object} request + * The request object that will be sent. + * @param {string} [request.tunedModelId] + * Optional. The unique id for the tuned model if specified. + * This value should be up to 40 characters, the first character must be a + * letter, the last could be a letter or a number. The id must match the + * regular expression: `[a-z]([a-z0-9-]{0,38}[a-z0-9])?`. + * @param {google.ai.generativelanguage.v1beta.TunedModel} request.tunedModel + * Required. The tuned model 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 include:samples/generated/v1beta/model_service.create_tuned_model.js + * region_tag:generativelanguage_v1beta_generated_ModelService_CreateTunedModel_async + */ createTunedModel( - request?: protos.google.ai.generativelanguage.v1beta.ICreateTunedModelRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.ICreateTunedModelRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.ai.generativelanguage.v1beta.ITunedModel, + protos.google.ai.generativelanguage.v1beta.ICreateTunedModelMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; createTunedModel( - request: protos.google.ai.generativelanguage.v1beta.ICreateTunedModelRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.ICreateTunedModelRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.ai.generativelanguage.v1beta.ITunedModel, + protos.google.ai.generativelanguage.v1beta.ICreateTunedModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createTunedModel( - request: protos.google.ai.generativelanguage.v1beta.ICreateTunedModelRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.ICreateTunedModelRequest, + callback: Callback< + LROperation< + protos.google.ai.generativelanguage.v1beta.ITunedModel, + protos.google.ai.generativelanguage.v1beta.ICreateTunedModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createTunedModel( - request?: protos.google.ai.generativelanguage.v1beta.ICreateTunedModelRequest, - 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.ai.generativelanguage.v1beta.ICreateTunedModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.ai.generativelanguage.v1beta.ITunedModel, + protos.google.ai.generativelanguage.v1beta.ICreateTunedModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.ai.generativelanguage.v1beta.ITunedModel, + protos.google.ai.generativelanguage.v1beta.ICreateTunedModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.ai.generativelanguage.v1beta.ITunedModel, + protos.google.ai.generativelanguage.v1beta.ICreateTunedModelMetadata + >, + 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 || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.ai.generativelanguage.v1beta.ITunedModel, + protos.google.ai.generativelanguage.v1beta.ICreateTunedModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('createTunedModel response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('createTunedModel request %j', request); - return this.innerApiCalls.createTunedModel(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('createTunedModel response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .createTunedModel(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.ai.generativelanguage.v1beta.ITunedModel, + protos.google.ai.generativelanguage.v1beta.ICreateTunedModelMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createTunedModel response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `createTunedModel()`. - * @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/v1beta/model_service.create_tuned_model.js - * region_tag:generativelanguage_v1beta_generated_ModelService_CreateTunedModel_async - */ - async checkCreateTunedModelProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `createTunedModel()`. + * @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/v1beta/model_service.create_tuned_model.js + * region_tag:generativelanguage_v1beta_generated_ModelService_CreateTunedModel_async + */ + async checkCreateTunedModelProgress( + name: string, + ): Promise< + LROperation< + protos.google.ai.generativelanguage.v1beta.TunedModel, + protos.google.ai.generativelanguage.v1beta.CreateTunedModelMetadata + > + > { this._log.info('createTunedModel 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.createTunedModel, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createTunedModel, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.ai.generativelanguage.v1beta.TunedModel, + protos.google.ai.generativelanguage.v1beta.CreateTunedModelMetadata + >; } - /** - * Lists the [`Model`s](https://ai.google.dev/gemini-api/docs/models/gemini) - * available through the Gemini API. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of `Models` to return (per page). - * - * If unspecified, 50 models will be returned per page. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} request.pageToken - * A page token, received from a previous `ListModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListModels` must match - * the call that provided the page token. - * @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.ai.generativelanguage.v1beta.Model|Model}. - * 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 `listModelsAsync()` - * 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 [`Model`s](https://ai.google.dev/gemini-api/docs/models/gemini) + * available through the Gemini API. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of `Models` to return (per page). + * + * If unspecified, 50 models will be returned per page. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} request.pageToken + * A page token, received from a previous `ListModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListModels` must match + * the call that provided the page token. + * @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.ai.generativelanguage.v1beta.Model|Model}. + * 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 `listModelsAsync()` + * 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. + */ listModels( - request?: protos.google.ai.generativelanguage.v1beta.IListModelsRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IModel[], - protos.google.ai.generativelanguage.v1beta.IListModelsRequest|null, - protos.google.ai.generativelanguage.v1beta.IListModelsResponse - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IListModelsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IModel[], + protos.google.ai.generativelanguage.v1beta.IListModelsRequest | null, + protos.google.ai.generativelanguage.v1beta.IListModelsResponse, + ] + >; listModels( - request: protos.google.ai.generativelanguage.v1beta.IListModelsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListModelsRequest, - protos.google.ai.generativelanguage.v1beta.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IModel>): void; + request: protos.google.ai.generativelanguage.v1beta.IListModelsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListModelsRequest, + | protos.google.ai.generativelanguage.v1beta.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IModel + >, + ): void; listModels( - request: protos.google.ai.generativelanguage.v1beta.IListModelsRequest, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListModelsRequest, - protos.google.ai.generativelanguage.v1beta.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IModel>): void; + request: protos.google.ai.generativelanguage.v1beta.IListModelsRequest, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListModelsRequest, + | protos.google.ai.generativelanguage.v1beta.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IModel + >, + ): void; listModels( - request?: protos.google.ai.generativelanguage.v1beta.IListModelsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListModelsRequest, - protos.google.ai.generativelanguage.v1beta.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IModel>, - callback?: PaginationCallback< + request?: protos.google.ai.generativelanguage.v1beta.IListModelsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ai.generativelanguage.v1beta.IListModelsRequest, - protos.google.ai.generativelanguage.v1beta.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IModel>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IModel[], - protos.google.ai.generativelanguage.v1beta.IListModelsRequest|null, - protos.google.ai.generativelanguage.v1beta.IListModelsResponse - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IModel + >, + callback?: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListModelsRequest, + | protos.google.ai.generativelanguage.v1beta.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IModel + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IModel[], + protos.google.ai.generativelanguage.v1beta.IListModelsRequest | null, + protos.google.ai.generativelanguage.v1beta.IListModelsResponse, + ] + > | 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 || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListModelsRequest, - protos.google.ai.generativelanguage.v1beta.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IModel>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListModelsRequest, + | protos.google.ai.generativelanguage.v1beta.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IModel + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listModels values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -986,214 +1352,246 @@ export class ModelServiceClient { this._log.info('listModels request %j', request); return this.innerApiCalls .listModels(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ai.generativelanguage.v1beta.IModel[], - protos.google.ai.generativelanguage.v1beta.IListModelsRequest|null, - protos.google.ai.generativelanguage.v1beta.IListModelsResponse - ]) => { - this._log.info('listModels values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ai.generativelanguage.v1beta.IModel[], + protos.google.ai.generativelanguage.v1beta.IListModelsRequest | null, + protos.google.ai.generativelanguage.v1beta.IListModelsResponse, + ]) => { + this._log.info('listModels values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listModels`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of `Models` to return (per page). - * - * If unspecified, 50 models will be returned per page. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} request.pageToken - * A page token, received from a previous `ListModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListModels` must match - * the call that provided the page token. - * @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.ai.generativelanguage.v1beta.Model|Model} 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 `listModelsAsync()` - * 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 `listModels`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of `Models` to return (per page). + * + * If unspecified, 50 models will be returned per page. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} request.pageToken + * A page token, received from a previous `ListModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListModels` must match + * the call that provided the page token. + * @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.ai.generativelanguage.v1beta.Model|Model} 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 `listModelsAsync()` + * 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. + */ listModelsStream( - request?: protos.google.ai.generativelanguage.v1beta.IListModelsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ai.generativelanguage.v1beta.IListModelsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listModels stream %j', request); return this.descriptors.page.listModels.createStream( this.innerApiCalls.listModels as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listModels`, 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 {number} request.pageSize - * The maximum number of `Models` to return (per page). - * - * If unspecified, 50 models will be returned per page. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} request.pageToken - * A page token, received from a previous `ListModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListModels` must match - * the call that provided the 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 protos.google.ai.generativelanguage.v1beta.Model|Model}. 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 include:samples/generated/v1beta/model_service.list_models.js - * region_tag:generativelanguage_v1beta_generated_ModelService_ListModels_async - */ + /** + * Equivalent to `listModels`, 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 {number} request.pageSize + * The maximum number of `Models` to return (per page). + * + * If unspecified, 50 models will be returned per page. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} request.pageToken + * A page token, received from a previous `ListModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListModels` must match + * the call that provided the 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 protos.google.ai.generativelanguage.v1beta.Model|Model}. 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 include:samples/generated/v1beta/model_service.list_models.js + * region_tag:generativelanguage_v1beta_generated_ModelService_ListModels_async + */ listModelsAsync( - request?: protos.google.ai.generativelanguage.v1beta.IListModelsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ai.generativelanguage.v1beta.IListModelsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listModels iterate %j', request); return this.descriptors.page.listModels.asyncIterate( this.innerApiCalls['listModels'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists created tuned models. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of `TunedModels` to return (per page). - * The service may return fewer tuned models. - * - * If unspecified, at most 10 tuned models will be returned. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListTunedModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListTunedModels` - * must match the call that provided the page token. - * @param {string} [request.filter] - * Optional. A filter is a full text search over the tuned model's description - * and display name. By default, results will not include tuned models shared - * with everyone. - * - * Additional operators: - * - owner:me - * - writers:me - * - readers:me - * - readers:everyone - * - * Examples: - * "owner:me" returns all tuned models to which caller has owner role - * "readers:me" returns all tuned models to which caller has reader role - * "readers:everyone" returns all tuned models that are shared with everyone - * @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.ai.generativelanguage.v1beta.TunedModel|TunedModel}. - * 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 `listTunedModelsAsync()` - * 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 created tuned models. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of `TunedModels` to return (per page). + * The service may return fewer tuned models. + * + * If unspecified, at most 10 tuned models will be returned. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListTunedModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListTunedModels` + * must match the call that provided the page token. + * @param {string} [request.filter] + * Optional. A filter is a full text search over the tuned model's description + * and display name. By default, results will not include tuned models shared + * with everyone. + * + * Additional operators: + * - owner:me + * - writers:me + * - readers:me + * - readers:everyone + * + * Examples: + * "owner:me" returns all tuned models to which caller has owner role + * "readers:me" returns all tuned models to which caller has reader role + * "readers:everyone" returns all tuned models that are shared with everyone + * @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.ai.generativelanguage.v1beta.TunedModel|TunedModel}. + * 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 `listTunedModelsAsync()` + * 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. + */ listTunedModels( - request?: protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ITunedModel[], - protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest|null, - protos.google.ai.generativelanguage.v1beta.IListTunedModelsResponse - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ITunedModel[], + protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest | null, + protos.google.ai.generativelanguage.v1beta.IListTunedModelsResponse, + ] + >; listTunedModels( - request: protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest, - protos.google.ai.generativelanguage.v1beta.IListTunedModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.ITunedModel>): void; + request: protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest, + | protos.google.ai.generativelanguage.v1beta.IListTunedModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.ITunedModel + >, + ): void; listTunedModels( - request: protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest, - protos.google.ai.generativelanguage.v1beta.IListTunedModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.ITunedModel>): void; + request: protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest, + | protos.google.ai.generativelanguage.v1beta.IListTunedModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.ITunedModel + >, + ): void; listTunedModels( - request?: protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest, - protos.google.ai.generativelanguage.v1beta.IListTunedModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.ITunedModel>, - callback?: PaginationCallback< + request?: protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest, - protos.google.ai.generativelanguage.v1beta.IListTunedModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.ITunedModel>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ITunedModel[], - protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest|null, - protos.google.ai.generativelanguage.v1beta.IListTunedModelsResponse - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IListTunedModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.ITunedModel + >, + callback?: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest, + | protos.google.ai.generativelanguage.v1beta.IListTunedModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.ITunedModel + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ITunedModel[], + protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest | null, + protos.google.ai.generativelanguage.v1beta.IListTunedModelsResponse, + ] + > | 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 || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest, - protos.google.ai.generativelanguage.v1beta.IListTunedModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.ITunedModel>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest, + | protos.google.ai.generativelanguage.v1beta.IListTunedModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.ITunedModel + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listTunedModels values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1202,147 +1600,153 @@ export class ModelServiceClient { this._log.info('listTunedModels request %j', request); return this.innerApiCalls .listTunedModels(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ai.generativelanguage.v1beta.ITunedModel[], - protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest|null, - protos.google.ai.generativelanguage.v1beta.IListTunedModelsResponse - ]) => { - this._log.info('listTunedModels values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ai.generativelanguage.v1beta.ITunedModel[], + protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest | null, + protos.google.ai.generativelanguage.v1beta.IListTunedModelsResponse, + ]) => { + this._log.info('listTunedModels values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listTunedModels`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of `TunedModels` to return (per page). - * The service may return fewer tuned models. - * - * If unspecified, at most 10 tuned models will be returned. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListTunedModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListTunedModels` - * must match the call that provided the page token. - * @param {string} [request.filter] - * Optional. A filter is a full text search over the tuned model's description - * and display name. By default, results will not include tuned models shared - * with everyone. - * - * Additional operators: - * - owner:me - * - writers:me - * - readers:me - * - readers:everyone - * - * Examples: - * "owner:me" returns all tuned models to which caller has owner role - * "readers:me" returns all tuned models to which caller has reader role - * "readers:everyone" returns all tuned models that are shared with everyone - * @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.ai.generativelanguage.v1beta.TunedModel|TunedModel} 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 `listTunedModelsAsync()` - * 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 `listTunedModels`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of `TunedModels` to return (per page). + * The service may return fewer tuned models. + * + * If unspecified, at most 10 tuned models will be returned. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListTunedModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListTunedModels` + * must match the call that provided the page token. + * @param {string} [request.filter] + * Optional. A filter is a full text search over the tuned model's description + * and display name. By default, results will not include tuned models shared + * with everyone. + * + * Additional operators: + * - owner:me + * - writers:me + * - readers:me + * - readers:everyone + * + * Examples: + * "owner:me" returns all tuned models to which caller has owner role + * "readers:me" returns all tuned models to which caller has reader role + * "readers:everyone" returns all tuned models that are shared with everyone + * @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.ai.generativelanguage.v1beta.TunedModel|TunedModel} 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 `listTunedModelsAsync()` + * 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. + */ listTunedModelsStream( - request?: protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listTunedModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTunedModels stream %j', request); return this.descriptors.page.listTunedModels.createStream( this.innerApiCalls.listTunedModels as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listTunedModels`, 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 {number} [request.pageSize] - * Optional. The maximum number of `TunedModels` to return (per page). - * The service may return fewer tuned models. - * - * If unspecified, at most 10 tuned models will be returned. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListTunedModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListTunedModels` - * must match the call that provided the page token. - * @param {string} [request.filter] - * Optional. A filter is a full text search over the tuned model's description - * and display name. By default, results will not include tuned models shared - * with everyone. - * - * Additional operators: - * - owner:me - * - writers:me - * - readers:me - * - readers:everyone - * - * Examples: - * "owner:me" returns all tuned models to which caller has owner role - * "readers:me" returns all tuned models to which caller has reader role - * "readers:everyone" returns all tuned models that are shared with everyone - * @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.ai.generativelanguage.v1beta.TunedModel|TunedModel}. 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 include:samples/generated/v1beta/model_service.list_tuned_models.js - * region_tag:generativelanguage_v1beta_generated_ModelService_ListTunedModels_async - */ + /** + * Equivalent to `listTunedModels`, 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 {number} [request.pageSize] + * Optional. The maximum number of `TunedModels` to return (per page). + * The service may return fewer tuned models. + * + * If unspecified, at most 10 tuned models will be returned. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListTunedModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListTunedModels` + * must match the call that provided the page token. + * @param {string} [request.filter] + * Optional. A filter is a full text search over the tuned model's description + * and display name. By default, results will not include tuned models shared + * with everyone. + * + * Additional operators: + * - owner:me + * - writers:me + * - readers:me + * - readers:everyone + * + * Examples: + * "owner:me" returns all tuned models to which caller has owner role + * "readers:me" returns all tuned models to which caller has reader role + * "readers:everyone" returns all tuned models that are shared with everyone + * @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.ai.generativelanguage.v1beta.TunedModel|TunedModel}. 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 include:samples/generated/v1beta/model_service.list_tuned_models.js + * region_tag:generativelanguage_v1beta_generated_ModelService_ListTunedModels_async + */ listTunedModelsAsync( - request?: protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ai.generativelanguage.v1beta.IListTunedModelsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listTunedModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTunedModels iterate %j', request); return this.descriptors.page.listTunedModels.asyncIterate( this.innerApiCalls['listTunedModels'] as GaxCall, request as {}, - callSettings + callSettings, ) as 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. @@ -1385,22 +1789,22 @@ export class ModelServiceClient { protos.google.longrunning.Operation, protos.google.longrunning.GetOperationRequest, {} | 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); } /** @@ -1435,15 +1839,15 @@ export class ModelServiceClient { */ listOperationsAsync( request: protos.google.longrunning.ListOperationsRequest, - options?: gax.CallOptions + 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); } /** @@ -1477,7 +1881,7 @@ export class ModelServiceClient { * await client.cancelOperation({name: ''}); * ``` */ - cancelOperation( + cancelOperation( request: protos.google.longrunning.CancelOperationRequest, optionsOrCallback?: | gax.CallOptions @@ -1490,25 +1894,24 @@ export class ModelServiceClient { protos.google.longrunning.CancelOperationRequest, protos.google.protobuf.Empty, {} | 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); } - /** * Deletes a long-running operation. This method indicates that the client is * no longer interested in the operation result. It does not cancel the @@ -1547,22 +1950,22 @@ export class ModelServiceClient { protos.google.protobuf.Empty, protos.google.longrunning.DeleteOperationRequest, {} | 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); } @@ -1576,7 +1979,7 @@ export class ModelServiceClient { * @param {string} id * @returns {string} Resource name string. */ - cachedContentPath(id:string) { + cachedContentPath(id: string) { return this.pathTemplates.cachedContentPathTemplate.render({ id: id, }); @@ -1590,7 +1993,8 @@ export class ModelServiceClient { * @returns {string} A string representing the id. */ matchIdFromCachedContentName(cachedContentName: string) { - return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName).id; + return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName) + .id; } /** @@ -1601,7 +2005,7 @@ export class ModelServiceClient { * @param {string} chunk * @returns {string} Resource name string. */ - chunkPath(corpus:string,document:string,chunk:string) { + chunkPath(corpus: string, document: string, chunk: string) { return this.pathTemplates.chunkPathTemplate.render({ corpus: corpus, document: document, @@ -1648,7 +2052,7 @@ export class ModelServiceClient { * @param {string} corpus * @returns {string} Resource name string. */ - corpusPath(corpus:string) { + corpusPath(corpus: string) { return this.pathTemplates.corpusPathTemplate.render({ corpus: corpus, }); @@ -1672,7 +2076,7 @@ export class ModelServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - corpusPermissionsPath(corpus:string,permission:string) { + corpusPermissionsPath(corpus: string, permission: string) { return this.pathTemplates.corpusPermissionsPathTemplate.render({ corpus: corpus, permission: permission, @@ -1687,7 +2091,9 @@ export class ModelServiceClient { * @returns {string} A string representing the corpus. */ matchCorpusFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).corpus; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).corpus; } /** @@ -1698,7 +2104,9 @@ export class ModelServiceClient { * @returns {string} A string representing the permission. */ matchPermissionFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).permission; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).permission; } /** @@ -1708,7 +2116,7 @@ export class ModelServiceClient { * @param {string} document * @returns {string} Resource name string. */ - documentPath(corpus:string,document:string) { + documentPath(corpus: string, document: string) { return this.pathTemplates.documentPathTemplate.render({ corpus: corpus, document: document, @@ -1743,7 +2151,7 @@ export class ModelServiceClient { * @param {string} file * @returns {string} Resource name string. */ - filePath(file:string) { + filePath(file: string) { return this.pathTemplates.filePathTemplate.render({ file: file, }); @@ -1766,7 +2174,7 @@ export class ModelServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -1789,7 +2197,7 @@ export class ModelServiceClient { * @param {string} tuned_model * @returns {string} Resource name string. */ - tunedModelPath(tunedModel:string) { + tunedModelPath(tunedModel: string) { return this.pathTemplates.tunedModelPathTemplate.render({ tuned_model: tunedModel, }); @@ -1803,7 +2211,8 @@ export class ModelServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromTunedModelName(tunedModelName: string) { - return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName).tuned_model; + return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName) + .tuned_model; } /** @@ -1813,7 +2222,7 @@ export class ModelServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - tunedModelPermissionsPath(tunedModel:string,permission:string) { + tunedModelPermissionsPath(tunedModel: string, permission: string) { return this.pathTemplates.tunedModelPermissionsPathTemplate.render({ tuned_model: tunedModel, permission: permission, @@ -1827,8 +2236,12 @@ export class ModelServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the tuned_model. */ - matchTunedModelFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).tuned_model; + matchTunedModelFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).tuned_model; } /** @@ -1838,8 +2251,12 @@ export class ModelServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the permission. */ - matchPermissionFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).permission; + matchPermissionFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).permission; } /** @@ -1850,7 +2267,7 @@ export class ModelServiceClient { */ close(): Promise { if (this.modelServiceStub && !this._terminated) { - return this.modelServiceStub.then(stub => { + return this.modelServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1859,4 +2276,4 @@ export class ModelServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1beta/permission_service_client.ts b/packages/google-ai-generativelanguage/src/v1beta/permission_service_client.ts index b17c7295b3ef..f920a37add21 100644 --- a/packages/google-ai-generativelanguage/src/v1beta/permission_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1beta/permission_service_client.ts @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class PermissionServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -57,9 +64,9 @@ export class PermissionServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - permissionServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + permissionServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of PermissionServiceClient. @@ -100,21 +107,42 @@ export class PermissionServiceClient { * const client = new PermissionServiceClient({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 PermissionServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -139,7 +167,7 @@ export class PermissionServiceClient { 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; @@ -153,10 +181,7 @@ export class PermissionServiceClient { } // 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 { @@ -178,31 +203,25 @@ export class PermissionServiceClient { // Create useful helper objects for these. this.pathTemplates = { cachedContentPathTemplate: new this._gaxModule.PathTemplate( - 'cachedContents/{id}' + 'cachedContents/{id}', ), chunkPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}/chunks/{chunk}' - ), - corpusPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}' + 'corpora/{corpus}/documents/{document}/chunks/{chunk}', ), + corpusPathTemplate: new this._gaxModule.PathTemplate('corpora/{corpus}'), corpusPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/permissions/{permission}' + 'corpora/{corpus}/permissions/{permission}', ), documentPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}' - ), - filePathTemplate: new this._gaxModule.PathTemplate( - 'files/{file}' - ), - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' + 'corpora/{corpus}/documents/{document}', ), + filePathTemplate: new this._gaxModule.PathTemplate('files/{file}'), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), tunedModelPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}' + 'tunedModels/{tuned_model}', ), tunedModelPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}/permissions/{permission}' + 'tunedModels/{tuned_model}/permissions/{permission}', ), }; @@ -210,14 +229,20 @@ export class PermissionServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listPermissions: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'permissions') + listPermissions: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'permissions', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1beta.PermissionService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1beta.PermissionService', + 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 @@ -248,37 +273,48 @@ export class PermissionServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1beta.PermissionService. this.permissionServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1beta.PermissionService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1beta.PermissionService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1beta.PermissionService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1beta + .PermissionService, + 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 permissionServiceStubMethods = - ['createPermission', 'getPermission', 'listPermissions', 'updatePermission', 'deletePermission', 'transferOwnership']; + const permissionServiceStubMethods = [ + 'createPermission', + 'getPermission', + 'listPermissions', + 'updatePermission', + 'deletePermission', + 'transferOwnership', + ]; for (const methodName of permissionServiceStubMethods) { const callPromise = this.permissionServiceStub.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] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -293,8 +329,14 @@ export class PermissionServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -305,8 +347,14 @@ export class PermissionServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -346,8 +394,9 @@ export class PermissionServiceClient { * 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; @@ -358,596 +407,866 @@ export class PermissionServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Create a permission to a specific resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource of the `Permission`. - * Formats: - * `tunedModels/{tuned_model}` - * `corpora/{corpus}` - * @param {google.ai.generativelanguage.v1beta.Permission} request.permission - * Required. The permission 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.ai.generativelanguage.v1beta.Permission|Permission}. - * 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/v1beta/permission_service.create_permission.js - * region_tag:generativelanguage_v1beta_generated_PermissionService_CreatePermission_async - */ + /** + * Create a permission to a specific resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource of the `Permission`. + * Formats: + * `tunedModels/{tuned_model}` + * `corpora/{corpus}` + * @param {google.ai.generativelanguage.v1beta.Permission} request.permission + * Required. The permission 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.ai.generativelanguage.v1beta.Permission|Permission}. + * 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/v1beta/permission_service.create_permission.js + * region_tag:generativelanguage_v1beta_generated_PermissionService_CreatePermission_async + */ createPermission( - request?: protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IPermission, + ( + | protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest + | undefined + ), + {} | undefined, + ] + >; createPermission( - request: protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IPermission, + | protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createPermission( - request: protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IPermission, + | protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createPermission( - request?: protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IPermission, + | protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IPermission, + ( + | protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest + | 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('createPermission request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IPermission, + | protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createPermission response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createPermission(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest|undefined, - {}|undefined - ]) => { - this._log.info('createPermission response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createPermission(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IPermission, + ( + | protos.google.ai.generativelanguage.v1beta.ICreatePermissionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createPermission response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets information about a specific Permission. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the permission. - * - * Formats: - * `tunedModels/{tuned_model}/permissions/{permission}` - * `corpora/{corpus}/permissions/{permission}` - * @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.ai.generativelanguage.v1beta.Permission|Permission}. - * 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/v1beta/permission_service.get_permission.js - * region_tag:generativelanguage_v1beta_generated_PermissionService_GetPermission_async - */ + /** + * Gets information about a specific Permission. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the permission. + * + * Formats: + * `tunedModels/{tuned_model}/permissions/{permission}` + * `corpora/{corpus}/permissions/{permission}` + * @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.ai.generativelanguage.v1beta.Permission|Permission}. + * 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/v1beta/permission_service.get_permission.js + * region_tag:generativelanguage_v1beta_generated_PermissionService_GetPermission_async + */ getPermission( - request?: protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IPermission, + ( + | protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest + | undefined + ), + {} | undefined, + ] + >; getPermission( - request: protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IPermission, + | protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getPermission( - request: protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IPermission, + | protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getPermission( - request?: protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IPermission, + | protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IPermission, + ( + | protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest + | 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('getPermission request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IPermission, + | protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getPermission response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getPermission(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest|undefined, - {}|undefined - ]) => { - this._log.info('getPermission response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getPermission(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IPermission, + ( + | protos.google.ai.generativelanguage.v1beta.IGetPermissionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getPermission response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the permission. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ai.generativelanguage.v1beta.Permission} request.permission - * Required. The permission to update. - * - * The permission's `name` field is used to identify the permission to update. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to update. Accepted ones: - * - role (`Permission.role` 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 {@link protos.google.ai.generativelanguage.v1beta.Permission|Permission}. - * 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/v1beta/permission_service.update_permission.js - * region_tag:generativelanguage_v1beta_generated_PermissionService_UpdatePermission_async - */ + /** + * Updates the permission. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ai.generativelanguage.v1beta.Permission} request.permission + * Required. The permission to update. + * + * The permission's `name` field is used to identify the permission to update. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to update. Accepted ones: + * - role (`Permission.role` 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 {@link protos.google.ai.generativelanguage.v1beta.Permission|Permission}. + * 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/v1beta/permission_service.update_permission.js + * region_tag:generativelanguage_v1beta_generated_PermissionService_UpdatePermission_async + */ updatePermission( - request?: protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IPermission, + ( + | protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest + | undefined + ), + {} | undefined, + ] + >; updatePermission( - request: protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IPermission, + | protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updatePermission( - request: protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IPermission, + | protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updatePermission( - request?: protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IPermission, + | protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IPermission, + ( + | protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest + | 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({ - 'permission.name': request.permission!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'permission.name': request.permission!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updatePermission request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IPermission, + | protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updatePermission response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updatePermission(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.IPermission, - protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest|undefined, - {}|undefined - ]) => { - this._log.info('updatePermission response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updatePermission(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IPermission, + ( + | protos.google.ai.generativelanguage.v1beta.IUpdatePermissionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updatePermission response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes the permission. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the permission. - * Formats: - * `tunedModels/{tuned_model}/permissions/{permission}` - * `corpora/{corpus}/permissions/{permission}` - * @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/v1beta/permission_service.delete_permission.js - * region_tag:generativelanguage_v1beta_generated_PermissionService_DeletePermission_async - */ + /** + * Deletes the permission. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the permission. + * Formats: + * `tunedModels/{tuned_model}/permissions/{permission}` + * `corpora/{corpus}/permissions/{permission}` + * @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/v1beta/permission_service.delete_permission.js + * region_tag:generativelanguage_v1beta_generated_PermissionService_DeletePermission_async + */ deletePermission( - request?: protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest + | undefined + ), + {} | undefined, + ] + >; deletePermission( - request: protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deletePermission( - request: protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deletePermission( - request?: protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest + | 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('deletePermission request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deletePermission response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deletePermission(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest|undefined, - {}|undefined - ]) => { - this._log.info('deletePermission response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deletePermission(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta.IDeletePermissionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deletePermission response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Transfers ownership of the tuned model. - * This is the only way to change ownership of the tuned model. - * The current owner will be downgraded to writer role. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the tuned model to transfer ownership. - * - * Format: `tunedModels/my-model-id` - * @param {string} request.emailAddress - * Required. The email address of the user to whom the tuned model is being - * transferred to. - * @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.ai.generativelanguage.v1beta.TransferOwnershipResponse|TransferOwnershipResponse}. - * 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/v1beta/permission_service.transfer_ownership.js - * region_tag:generativelanguage_v1beta_generated_PermissionService_TransferOwnership_async - */ + /** + * Transfers ownership of the tuned model. + * This is the only way to change ownership of the tuned model. + * The current owner will be downgraded to writer role. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the tuned model to transfer ownership. + * + * Format: `tunedModels/my-model-id` + * @param {string} request.emailAddress + * Required. The email address of the user to whom the tuned model is being + * transferred to. + * @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.ai.generativelanguage.v1beta.TransferOwnershipResponse|TransferOwnershipResponse}. + * 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/v1beta/permission_service.transfer_ownership.js + * region_tag:generativelanguage_v1beta_generated_PermissionService_TransferOwnership_async + */ transferOwnership( - request?: protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ITransferOwnershipResponse, + ( + | protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest + | undefined + ), + {} | undefined, + ] + >; transferOwnership( - request: protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ITransferOwnershipResponse, + | protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest + | null + | undefined, + {} | null | undefined + >, + ): void; transferOwnership( - request: protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ITransferOwnershipResponse, + | protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest + | null + | undefined, + {} | null | undefined + >, + ): void; transferOwnership( - request?: protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1beta.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.ITransferOwnershipResponse, + | protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ITransferOwnershipResponse, + ( + | protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest + | 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('transferOwnership request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.ITransferOwnershipResponse, + | protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('transferOwnership response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.transferOwnership(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest|undefined, - {}|undefined - ]) => { - this._log.info('transferOwnership response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .transferOwnership(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.ITransferOwnershipResponse, + ( + | protos.google.ai.generativelanguage.v1beta.ITransferOwnershipRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('transferOwnership response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists permissions for the specific resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource of the permissions. - * Formats: - * `tunedModels/{tuned_model}` - * `corpora/{corpus}` - * @param {number} [request.pageSize] - * Optional. The maximum number of `Permission`s to return (per page). - * The service may return fewer permissions. - * - * If unspecified, at most 10 permissions will be returned. - * This method returns at most 1000 permissions per page, even if you pass - * larger page_size. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListPermissions` call. - * - * Provide the `page_token` returned by one request as an argument to the - * next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListPermissions` - * must match the call that provided the page token. - * @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.ai.generativelanguage.v1beta.Permission|Permission}. - * 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 `listPermissionsAsync()` - * 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 permissions for the specific resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource of the permissions. + * Formats: + * `tunedModels/{tuned_model}` + * `corpora/{corpus}` + * @param {number} [request.pageSize] + * Optional. The maximum number of `Permission`s to return (per page). + * The service may return fewer permissions. + * + * If unspecified, at most 10 permissions will be returned. + * This method returns at most 1000 permissions per page, even if you pass + * larger page_size. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListPermissions` call. + * + * Provide the `page_token` returned by one request as an argument to the + * next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListPermissions` + * must match the call that provided the page token. + * @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.ai.generativelanguage.v1beta.Permission|Permission}. + * 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 `listPermissionsAsync()` + * 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. + */ listPermissions( - request?: protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IPermission[], - protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest|null, - protos.google.ai.generativelanguage.v1beta.IListPermissionsResponse - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IPermission[], + protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest | null, + protos.google.ai.generativelanguage.v1beta.IListPermissionsResponse, + ] + >; listPermissions( - request: protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest, - protos.google.ai.generativelanguage.v1beta.IListPermissionsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IPermission>): void; + request: protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest, + | protos.google.ai.generativelanguage.v1beta.IListPermissionsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IPermission + >, + ): void; listPermissions( - request: protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest, - protos.google.ai.generativelanguage.v1beta.IListPermissionsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IPermission>): void; + request: protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest, + | protos.google.ai.generativelanguage.v1beta.IListPermissionsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IPermission + >, + ): void; listPermissions( - request?: protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest, - protos.google.ai.generativelanguage.v1beta.IListPermissionsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IPermission>, - callback?: PaginationCallback< + request?: protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest, - protos.google.ai.generativelanguage.v1beta.IListPermissionsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IPermission>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IPermission[], - protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest|null, - protos.google.ai.generativelanguage.v1beta.IListPermissionsResponse - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IListPermissionsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IPermission + >, + callback?: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest, + | protos.google.ai.generativelanguage.v1beta.IListPermissionsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IPermission + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IPermission[], + protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest | null, + protos.google.ai.generativelanguage.v1beta.IListPermissionsResponse, + ] + > | 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.ai.generativelanguage.v1beta.IListPermissionsRequest, - protos.google.ai.generativelanguage.v1beta.IListPermissionsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IPermission>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest, + | protos.google.ai.generativelanguage.v1beta.IListPermissionsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IPermission + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listPermissions values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -956,134 +1275,138 @@ export class PermissionServiceClient { this._log.info('listPermissions request %j', request); return this.innerApiCalls .listPermissions(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ai.generativelanguage.v1beta.IPermission[], - protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest|null, - protos.google.ai.generativelanguage.v1beta.IListPermissionsResponse - ]) => { - this._log.info('listPermissions values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ai.generativelanguage.v1beta.IPermission[], + protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest | null, + protos.google.ai.generativelanguage.v1beta.IListPermissionsResponse, + ]) => { + this._log.info('listPermissions values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listPermissions`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource of the permissions. - * Formats: - * `tunedModels/{tuned_model}` - * `corpora/{corpus}` - * @param {number} [request.pageSize] - * Optional. The maximum number of `Permission`s to return (per page). - * The service may return fewer permissions. - * - * If unspecified, at most 10 permissions will be returned. - * This method returns at most 1000 permissions per page, even if you pass - * larger page_size. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListPermissions` call. - * - * Provide the `page_token` returned by one request as an argument to the - * next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListPermissions` - * must match the call that provided the page token. - * @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.ai.generativelanguage.v1beta.Permission|Permission} 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 `listPermissionsAsync()` - * 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 `listPermissions`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource of the permissions. + * Formats: + * `tunedModels/{tuned_model}` + * `corpora/{corpus}` + * @param {number} [request.pageSize] + * Optional. The maximum number of `Permission`s to return (per page). + * The service may return fewer permissions. + * + * If unspecified, at most 10 permissions will be returned. + * This method returns at most 1000 permissions per page, even if you pass + * larger page_size. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListPermissions` call. + * + * Provide the `page_token` returned by one request as an argument to the + * next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListPermissions` + * must match the call that provided the page token. + * @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.ai.generativelanguage.v1beta.Permission|Permission} 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 `listPermissionsAsync()` + * 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. + */ listPermissionsStream( - request?: protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest, + 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['listPermissions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listPermissions stream %j', request); return this.descriptors.page.listPermissions.createStream( this.innerApiCalls.listPermissions as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listPermissions`, 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 of the permissions. - * Formats: - * `tunedModels/{tuned_model}` - * `corpora/{corpus}` - * @param {number} [request.pageSize] - * Optional. The maximum number of `Permission`s to return (per page). - * The service may return fewer permissions. - * - * If unspecified, at most 10 permissions will be returned. - * This method returns at most 1000 permissions per page, even if you pass - * larger page_size. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListPermissions` call. - * - * Provide the `page_token` returned by one request as an argument to the - * next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListPermissions` - * must match the call that provided the 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 protos.google.ai.generativelanguage.v1beta.Permission|Permission}. 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 include:samples/generated/v1beta/permission_service.list_permissions.js - * region_tag:generativelanguage_v1beta_generated_PermissionService_ListPermissions_async - */ + /** + * Equivalent to `listPermissions`, 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 of the permissions. + * Formats: + * `tunedModels/{tuned_model}` + * `corpora/{corpus}` + * @param {number} [request.pageSize] + * Optional. The maximum number of `Permission`s to return (per page). + * The service may return fewer permissions. + * + * If unspecified, at most 10 permissions will be returned. + * This method returns at most 1000 permissions per page, even if you pass + * larger page_size. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListPermissions` call. + * + * Provide the `page_token` returned by one request as an argument to the + * next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListPermissions` + * must match the call that provided the 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 protos.google.ai.generativelanguage.v1beta.Permission|Permission}. 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 include:samples/generated/v1beta/permission_service.list_permissions.js + * region_tag:generativelanguage_v1beta_generated_PermissionService_ListPermissions_async + */ listPermissionsAsync( - request?: protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ai.generativelanguage.v1beta.IListPermissionsRequest, + 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['listPermissions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listPermissions iterate %j', request); return this.descriptors.page.listPermissions.asyncIterate( this.innerApiCalls['listPermissions'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1096,7 +1419,7 @@ export class PermissionServiceClient { * @param {string} id * @returns {string} Resource name string. */ - cachedContentPath(id:string) { + cachedContentPath(id: string) { return this.pathTemplates.cachedContentPathTemplate.render({ id: id, }); @@ -1110,7 +1433,8 @@ export class PermissionServiceClient { * @returns {string} A string representing the id. */ matchIdFromCachedContentName(cachedContentName: string) { - return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName).id; + return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName) + .id; } /** @@ -1121,7 +1445,7 @@ export class PermissionServiceClient { * @param {string} chunk * @returns {string} Resource name string. */ - chunkPath(corpus:string,document:string,chunk:string) { + chunkPath(corpus: string, document: string, chunk: string) { return this.pathTemplates.chunkPathTemplate.render({ corpus: corpus, document: document, @@ -1168,7 +1492,7 @@ export class PermissionServiceClient { * @param {string} corpus * @returns {string} Resource name string. */ - corpusPath(corpus:string) { + corpusPath(corpus: string) { return this.pathTemplates.corpusPathTemplate.render({ corpus: corpus, }); @@ -1192,7 +1516,7 @@ export class PermissionServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - corpusPermissionsPath(corpus:string,permission:string) { + corpusPermissionsPath(corpus: string, permission: string) { return this.pathTemplates.corpusPermissionsPathTemplate.render({ corpus: corpus, permission: permission, @@ -1207,7 +1531,9 @@ export class PermissionServiceClient { * @returns {string} A string representing the corpus. */ matchCorpusFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).corpus; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).corpus; } /** @@ -1218,7 +1544,9 @@ export class PermissionServiceClient { * @returns {string} A string representing the permission. */ matchPermissionFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).permission; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).permission; } /** @@ -1228,7 +1556,7 @@ export class PermissionServiceClient { * @param {string} document * @returns {string} Resource name string. */ - documentPath(corpus:string,document:string) { + documentPath(corpus: string, document: string) { return this.pathTemplates.documentPathTemplate.render({ corpus: corpus, document: document, @@ -1263,7 +1591,7 @@ export class PermissionServiceClient { * @param {string} file * @returns {string} Resource name string. */ - filePath(file:string) { + filePath(file: string) { return this.pathTemplates.filePathTemplate.render({ file: file, }); @@ -1286,7 +1614,7 @@ export class PermissionServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -1309,7 +1637,7 @@ export class PermissionServiceClient { * @param {string} tuned_model * @returns {string} Resource name string. */ - tunedModelPath(tunedModel:string) { + tunedModelPath(tunedModel: string) { return this.pathTemplates.tunedModelPathTemplate.render({ tuned_model: tunedModel, }); @@ -1323,7 +1651,8 @@ export class PermissionServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromTunedModelName(tunedModelName: string) { - return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName).tuned_model; + return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName) + .tuned_model; } /** @@ -1333,7 +1662,7 @@ export class PermissionServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - tunedModelPermissionsPath(tunedModel:string,permission:string) { + tunedModelPermissionsPath(tunedModel: string, permission: string) { return this.pathTemplates.tunedModelPermissionsPathTemplate.render({ tuned_model: tunedModel, permission: permission, @@ -1347,8 +1676,12 @@ export class PermissionServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the tuned_model. */ - matchTunedModelFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).tuned_model; + matchTunedModelFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).tuned_model; } /** @@ -1358,8 +1691,12 @@ export class PermissionServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the permission. */ - matchPermissionFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).permission; + matchPermissionFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).permission; } /** @@ -1370,7 +1707,7 @@ export class PermissionServiceClient { */ close(): Promise { if (this.permissionServiceStub && !this._terminated) { - return this.permissionServiceStub.then(stub => { + return this.permissionServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1378,4 +1715,4 @@ export class PermissionServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1beta/prediction_service_client.ts b/packages/google-ai-generativelanguage/src/v1beta/prediction_service_client.ts index fef6ec0cb7d7..deea88ae8f52 100644 --- a/packages/google-ai-generativelanguage/src/v1beta/prediction_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1beta/prediction_service_client.ts @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class PredictionServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -57,10 +64,10 @@ export class PredictionServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - predictionServiceStub?: Promise<{[name: string]: Function}>; + predictionServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of PredictionServiceClient. @@ -101,21 +108,42 @@ export class PredictionServiceClient { * const client = new PredictionServiceClient({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 PredictionServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -140,7 +168,7 @@ export class PredictionServiceClient { 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; @@ -154,10 +182,7 @@ export class PredictionServiceClient { } // 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 { @@ -179,31 +204,25 @@ export class PredictionServiceClient { // Create useful helper objects for these. this.pathTemplates = { cachedContentPathTemplate: new this._gaxModule.PathTemplate( - 'cachedContents/{id}' + 'cachedContents/{id}', ), chunkPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}/chunks/{chunk}' - ), - corpusPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}' + 'corpora/{corpus}/documents/{document}/chunks/{chunk}', ), + corpusPathTemplate: new this._gaxModule.PathTemplate('corpora/{corpus}'), corpusPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/permissions/{permission}' + 'corpora/{corpus}/permissions/{permission}', ), documentPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}' - ), - filePathTemplate: new this._gaxModule.PathTemplate( - 'files/{file}' - ), - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' + 'corpora/{corpus}/documents/{document}', ), + filePathTemplate: new this._gaxModule.PathTemplate('files/{file}'), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), tunedModelPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}' + 'tunedModels/{tuned_model}', ), tunedModelPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}/permissions/{permission}' + 'tunedModels/{tuned_model}/permissions/{permission}', ), }; @@ -213,31 +232,64 @@ export class PredictionServiceClient { // 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: '/v1beta/{name=batches/*}:cancel',},{selector: 'google.longrunning.Operations.DeleteOperation',delete: '/v1beta/{name=batches/*}',},{selector: 'google.longrunning.Operations.GetOperation',get: '/v1beta/{name=tunedModels/*/operations/*}',additional_bindings: [{get: '/v1beta/{name=generatedFiles/*/operations/*}',},{get: '/v1beta/{name=batches/*}',},{get: '/v1beta/{name=models/*/operations/*}',},{get: '/v1beta/{name=corpora/*/operations/*}',}], - },{selector: 'google.longrunning.Operations.ListOperations',get: '/v1beta/{name=tunedModels/*}/operations',additional_bindings: [{get: '/v1beta/{name=batches}',},{get: '/v1beta/{name=models/*}/operations',}], - }]; + lroOptions.httpRules = [ + { + selector: 'google.longrunning.Operations.CancelOperation', + post: '/v1beta/{name=batches/*}:cancel', + }, + { + selector: 'google.longrunning.Operations.DeleteOperation', + delete: '/v1beta/{name=batches/*}', + }, + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v1beta/{name=tunedModels/*/operations/*}', + additional_bindings: [ + { get: '/v1beta/{name=generatedFiles/*/operations/*}' }, + { get: '/v1beta/{name=batches/*}' }, + { get: '/v1beta/{name=models/*/operations/*}' }, + { get: '/v1beta/{name=corpora/*/operations/*}' }, + ], + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v1beta/{name=tunedModels/*}/operations', + additional_bindings: [ + { get: '/v1beta/{name=batches}' }, + { get: '/v1beta/{name=models/*}/operations' }, + ], + }, + ]; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const predictLongRunningResponse = protoFilesRoot.lookup( - '.google.ai.generativelanguage.v1beta.PredictLongRunningResponse') as gax.protobuf.Type; + '.google.ai.generativelanguage.v1beta.PredictLongRunningResponse', + ) as gax.protobuf.Type; const predictLongRunningMetadata = protoFilesRoot.lookup( - '.google.ai.generativelanguage.v1beta.PredictLongRunningMetadata') as gax.protobuf.Type; + '.google.ai.generativelanguage.v1beta.PredictLongRunningMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { predictLongRunning: new this._gaxModule.LongrunningDescriptor( this.operationsClient, predictLongRunningResponse.decode.bind(predictLongRunningResponse), - predictLongRunningMetadata.decode.bind(predictLongRunningMetadata)) + predictLongRunningMetadata.decode.bind(predictLongRunningMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1beta.PredictionService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1beta.PredictionService', + 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 @@ -268,37 +320,41 @@ export class PredictionServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1beta.PredictionService. this.predictionServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1beta.PredictionService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1beta.PredictionService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1beta.PredictionService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1beta + .PredictionService, + 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 predictionServiceStubMethods = - ['predict', 'predictLongRunning']; + const predictionServiceStubMethods = ['predict', 'predictLongRunning']; for (const methodName of predictionServiceStubMethods) { const callPromise = this.predictionServiceStub.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.longrunning[methodName] || - undefined; + const descriptor = this.descriptors.longrunning[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -313,8 +369,14 @@ export class PredictionServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -325,8 +387,14 @@ export class PredictionServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -366,8 +434,9 @@ export class PredictionServiceClient { * 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; @@ -378,219 +447,324 @@ export class PredictionServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Performs a prediction request. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The name of the model for prediction. - * Format: `name=models/{model}`. - * @param {number[]} request.instances - * Required. The instances that are the input to the prediction call. - * @param {google.protobuf.Value} [request.parameters] - * Optional. The parameters that govern the prediction call. - * @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.ai.generativelanguage.v1beta.PredictResponse|PredictResponse}. - * 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/v1beta/prediction_service.predict.js - * region_tag:generativelanguage_v1beta_generated_PredictionService_Predict_async - */ + /** + * Performs a prediction request. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The name of the model for prediction. + * Format: `name=models/{model}`. + * @param {number[]} request.instances + * Required. The instances that are the input to the prediction call. + * @param {google.protobuf.Value} [request.parameters] + * Optional. The parameters that govern the prediction call. + * @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.ai.generativelanguage.v1beta.PredictResponse|PredictResponse}. + * 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/v1beta/prediction_service.predict.js + * region_tag:generativelanguage_v1beta_generated_PredictionService_Predict_async + */ predict( - request?: protos.google.ai.generativelanguage.v1beta.IPredictRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IPredictResponse, - protos.google.ai.generativelanguage.v1beta.IPredictRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IPredictRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IPredictResponse, + protos.google.ai.generativelanguage.v1beta.IPredictRequest | undefined, + {} | undefined, + ] + >; predict( - request: protos.google.ai.generativelanguage.v1beta.IPredictRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IPredictResponse, - protos.google.ai.generativelanguage.v1beta.IPredictRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IPredictRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IPredictResponse, + | protos.google.ai.generativelanguage.v1beta.IPredictRequest + | null + | undefined, + {} | null | undefined + >, + ): void; predict( - request: protos.google.ai.generativelanguage.v1beta.IPredictRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IPredictResponse, - protos.google.ai.generativelanguage.v1beta.IPredictRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IPredictRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IPredictResponse, + | protos.google.ai.generativelanguage.v1beta.IPredictRequest + | null + | undefined, + {} | null | undefined + >, + ): void; predict( - request?: protos.google.ai.generativelanguage.v1beta.IPredictRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.IPredictResponse, - protos.google.ai.generativelanguage.v1beta.IPredictRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IPredictRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IPredictResponse, - protos.google.ai.generativelanguage.v1beta.IPredictRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IPredictResponse, - protos.google.ai.generativelanguage.v1beta.IPredictRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IPredictRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IPredictResponse, + | protos.google.ai.generativelanguage.v1beta.IPredictRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IPredictResponse, + protos.google.ai.generativelanguage.v1beta.IPredictRequest | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('predict request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.IPredictResponse, - protos.google.ai.generativelanguage.v1beta.IPredictRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IPredictResponse, + | protos.google.ai.generativelanguage.v1beta.IPredictRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('predict response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.predict(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.IPredictResponse, - protos.google.ai.generativelanguage.v1beta.IPredictRequest|undefined, - {}|undefined - ]) => { - this._log.info('predict response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .predict(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IPredictResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IPredictRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('predict response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Same as Predict but returns an LRO. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The name of the model for prediction. - * Format: `name=models/{model}`. - * @param {number[]} request.instances - * Required. The instances that are the input to the prediction call. - * @param {google.protobuf.Value} [request.parameters] - * Optional. The parameters that govern the prediction call. - * @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/v1beta/prediction_service.predict_long_running.js - * region_tag:generativelanguage_v1beta_generated_PredictionService_PredictLongRunning_async - */ + /** + * Same as Predict but returns an LRO. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The name of the model for prediction. + * Format: `name=models/{model}`. + * @param {number[]} request.instances + * Required. The instances that are the input to the prediction call. + * @param {google.protobuf.Value} [request.parameters] + * Optional. The parameters that govern the prediction call. + * @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/v1beta/prediction_service.predict_long_running.js + * region_tag:generativelanguage_v1beta_generated_PredictionService_PredictLongRunning_async + */ predictLongRunning( - request?: protos.google.ai.generativelanguage.v1beta.IPredictLongRunningRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IPredictLongRunningRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.ai.generativelanguage.v1beta.IPredictLongRunningResponse, + protos.google.ai.generativelanguage.v1beta.IPredictLongRunningMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; predictLongRunning( - request: protos.google.ai.generativelanguage.v1beta.IPredictLongRunningRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IPredictLongRunningRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.ai.generativelanguage.v1beta.IPredictLongRunningResponse, + protos.google.ai.generativelanguage.v1beta.IPredictLongRunningMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; predictLongRunning( - request: protos.google.ai.generativelanguage.v1beta.IPredictLongRunningRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IPredictLongRunningRequest, + callback: Callback< + LROperation< + protos.google.ai.generativelanguage.v1beta.IPredictLongRunningResponse, + protos.google.ai.generativelanguage.v1beta.IPredictLongRunningMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; predictLongRunning( - request?: protos.google.ai.generativelanguage.v1beta.IPredictLongRunningRequest, - 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.ai.generativelanguage.v1beta.IPredictLongRunningRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.ai.generativelanguage.v1beta.IPredictLongRunningResponse, + protos.google.ai.generativelanguage.v1beta.IPredictLongRunningMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.ai.generativelanguage.v1beta.IPredictLongRunningResponse, + protos.google.ai.generativelanguage.v1beta.IPredictLongRunningMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.ai.generativelanguage.v1beta.IPredictLongRunningResponse, + protos.google.ai.generativelanguage.v1beta.IPredictLongRunningMetadata + >, + 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + 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.ai.generativelanguage.v1beta.IPredictLongRunningResponse, + protos.google.ai.generativelanguage.v1beta.IPredictLongRunningMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('predictLongRunning response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('predictLongRunning request %j', request); - return this.innerApiCalls.predictLongRunning(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('predictLongRunning response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .predictLongRunning(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.ai.generativelanguage.v1beta.IPredictLongRunningResponse, + protos.google.ai.generativelanguage.v1beta.IPredictLongRunningMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('predictLongRunning response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `predictLongRunning()`. - * @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/v1beta/prediction_service.predict_long_running.js - * region_tag:generativelanguage_v1beta_generated_PredictionService_PredictLongRunning_async - */ - async checkPredictLongRunningProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `predictLongRunning()`. + * @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/v1beta/prediction_service.predict_long_running.js + * region_tag:generativelanguage_v1beta_generated_PredictionService_PredictLongRunning_async + */ + async checkPredictLongRunningProgress( + name: string, + ): Promise< + LROperation< + protos.google.ai.generativelanguage.v1beta.PredictLongRunningResponse, + protos.google.ai.generativelanguage.v1beta.PredictLongRunningMetadata + > + > { this._log.info('predictLongRunning 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.predictLongRunning, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.predictLongRunning, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.ai.generativelanguage.v1beta.PredictLongRunningResponse, + protos.google.ai.generativelanguage.v1beta.PredictLongRunningMetadata + >; } -/** + /** * 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. @@ -633,22 +807,22 @@ export class PredictionServiceClient { protos.google.longrunning.Operation, protos.google.longrunning.GetOperationRequest, {} | 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); } /** @@ -683,15 +857,15 @@ export class PredictionServiceClient { */ listOperationsAsync( request: protos.google.longrunning.ListOperationsRequest, - options?: gax.CallOptions + 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); } /** @@ -725,7 +899,7 @@ export class PredictionServiceClient { * await client.cancelOperation({name: ''}); * ``` */ - cancelOperation( + cancelOperation( request: protos.google.longrunning.CancelOperationRequest, optionsOrCallback?: | gax.CallOptions @@ -738,25 +912,24 @@ export class PredictionServiceClient { protos.google.longrunning.CancelOperationRequest, protos.google.protobuf.Empty, {} | 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); } - /** * Deletes a long-running operation. This method indicates that the client is * no longer interested in the operation result. It does not cancel the @@ -795,22 +968,22 @@ export class PredictionServiceClient { protos.google.protobuf.Empty, protos.google.longrunning.DeleteOperationRequest, {} | 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); } @@ -824,7 +997,7 @@ export class PredictionServiceClient { * @param {string} id * @returns {string} Resource name string. */ - cachedContentPath(id:string) { + cachedContentPath(id: string) { return this.pathTemplates.cachedContentPathTemplate.render({ id: id, }); @@ -838,7 +1011,8 @@ export class PredictionServiceClient { * @returns {string} A string representing the id. */ matchIdFromCachedContentName(cachedContentName: string) { - return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName).id; + return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName) + .id; } /** @@ -849,7 +1023,7 @@ export class PredictionServiceClient { * @param {string} chunk * @returns {string} Resource name string. */ - chunkPath(corpus:string,document:string,chunk:string) { + chunkPath(corpus: string, document: string, chunk: string) { return this.pathTemplates.chunkPathTemplate.render({ corpus: corpus, document: document, @@ -896,7 +1070,7 @@ export class PredictionServiceClient { * @param {string} corpus * @returns {string} Resource name string. */ - corpusPath(corpus:string) { + corpusPath(corpus: string) { return this.pathTemplates.corpusPathTemplate.render({ corpus: corpus, }); @@ -920,7 +1094,7 @@ export class PredictionServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - corpusPermissionsPath(corpus:string,permission:string) { + corpusPermissionsPath(corpus: string, permission: string) { return this.pathTemplates.corpusPermissionsPathTemplate.render({ corpus: corpus, permission: permission, @@ -935,7 +1109,9 @@ export class PredictionServiceClient { * @returns {string} A string representing the corpus. */ matchCorpusFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).corpus; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).corpus; } /** @@ -946,7 +1122,9 @@ export class PredictionServiceClient { * @returns {string} A string representing the permission. */ matchPermissionFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).permission; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).permission; } /** @@ -956,7 +1134,7 @@ export class PredictionServiceClient { * @param {string} document * @returns {string} Resource name string. */ - documentPath(corpus:string,document:string) { + documentPath(corpus: string, document: string) { return this.pathTemplates.documentPathTemplate.render({ corpus: corpus, document: document, @@ -991,7 +1169,7 @@ export class PredictionServiceClient { * @param {string} file * @returns {string} Resource name string. */ - filePath(file:string) { + filePath(file: string) { return this.pathTemplates.filePathTemplate.render({ file: file, }); @@ -1014,7 +1192,7 @@ export class PredictionServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -1037,7 +1215,7 @@ export class PredictionServiceClient { * @param {string} tuned_model * @returns {string} Resource name string. */ - tunedModelPath(tunedModel:string) { + tunedModelPath(tunedModel: string) { return this.pathTemplates.tunedModelPathTemplate.render({ tuned_model: tunedModel, }); @@ -1051,7 +1229,8 @@ export class PredictionServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromTunedModelName(tunedModelName: string) { - return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName).tuned_model; + return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName) + .tuned_model; } /** @@ -1061,7 +1240,7 @@ export class PredictionServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - tunedModelPermissionsPath(tunedModel:string,permission:string) { + tunedModelPermissionsPath(tunedModel: string, permission: string) { return this.pathTemplates.tunedModelPermissionsPathTemplate.render({ tuned_model: tunedModel, permission: permission, @@ -1075,8 +1254,12 @@ export class PredictionServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the tuned_model. */ - matchTunedModelFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).tuned_model; + matchTunedModelFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).tuned_model; } /** @@ -1086,8 +1269,12 @@ export class PredictionServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the permission. */ - matchPermissionFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).permission; + matchPermissionFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).permission; } /** @@ -1098,7 +1285,7 @@ export class PredictionServiceClient { */ close(): Promise { if (this.predictionServiceStub && !this._terminated) { - return this.predictionServiceStub.then(stub => { + return this.predictionServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1107,4 +1294,4 @@ export class PredictionServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1beta/retriever_service_client.ts b/packages/google-ai-generativelanguage/src/v1beta/retriever_service_client.ts index e1048ec89b88..6432c3918951 100644 --- a/packages/google-ai-generativelanguage/src/v1beta/retriever_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1beta/retriever_service_client.ts @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class RetrieverServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -57,9 +64,9 @@ export class RetrieverServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - retrieverServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + retrieverServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of RetrieverServiceClient. @@ -100,21 +107,42 @@ export class RetrieverServiceClient { * const client = new RetrieverServiceClient({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 RetrieverServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -139,7 +167,7 @@ export class RetrieverServiceClient { 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; @@ -153,10 +181,7 @@ export class RetrieverServiceClient { } // 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 { @@ -178,31 +203,25 @@ export class RetrieverServiceClient { // Create useful helper objects for these. this.pathTemplates = { cachedContentPathTemplate: new this._gaxModule.PathTemplate( - 'cachedContents/{id}' + 'cachedContents/{id}', ), chunkPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}/chunks/{chunk}' - ), - corpusPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}' + 'corpora/{corpus}/documents/{document}/chunks/{chunk}', ), + corpusPathTemplate: new this._gaxModule.PathTemplate('corpora/{corpus}'), corpusPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/permissions/{permission}' + 'corpora/{corpus}/permissions/{permission}', ), documentPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}' - ), - filePathTemplate: new this._gaxModule.PathTemplate( - 'files/{file}' - ), - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' + 'corpora/{corpus}/documents/{document}', ), + filePathTemplate: new this._gaxModule.PathTemplate('files/{file}'), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), tunedModelPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}' + 'tunedModels/{tuned_model}', ), tunedModelPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}/permissions/{permission}' + 'tunedModels/{tuned_model}/permissions/{permission}', ), }; @@ -210,18 +229,30 @@ export class RetrieverServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listCorpora: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'corpora'), - listDocuments: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'documents'), - listChunks: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'chunks') + listCorpora: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'corpora', + ), + listDocuments: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'documents', + ), + listChunks: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'chunks', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1beta.RetrieverService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1beta.RetrieverService', + 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 @@ -252,37 +283,62 @@ export class RetrieverServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1beta.RetrieverService. this.retrieverServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1beta.RetrieverService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1beta.RetrieverService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1beta.RetrieverService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1beta + .RetrieverService, + 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 retrieverServiceStubMethods = - ['createCorpus', 'getCorpus', 'updateCorpus', 'deleteCorpus', 'listCorpora', 'queryCorpus', 'createDocument', 'getDocument', 'updateDocument', 'deleteDocument', 'listDocuments', 'queryDocument', 'createChunk', 'batchCreateChunks', 'getChunk', 'updateChunk', 'batchUpdateChunks', 'deleteChunk', 'batchDeleteChunks', 'listChunks']; + const retrieverServiceStubMethods = [ + 'createCorpus', + 'getCorpus', + 'updateCorpus', + 'deleteCorpus', + 'listCorpora', + 'queryCorpus', + 'createDocument', + 'getDocument', + 'updateDocument', + 'deleteDocument', + 'listDocuments', + 'queryDocument', + 'createChunk', + 'batchCreateChunks', + 'getChunk', + 'updateChunk', + 'batchUpdateChunks', + 'deleteChunk', + 'batchDeleteChunks', + 'listChunks', + ]; for (const methodName of retrieverServiceStubMethods) { const callPromise = this.retrieverServiceStub.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] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -297,8 +353,14 @@ export class RetrieverServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -309,8 +371,14 @@ export class RetrieverServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -350,8 +418,9 @@ export class RetrieverServiceClient { * 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; @@ -362,1814 +431,2662 @@ export class RetrieverServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Creates an empty `Corpus`. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ai.generativelanguage.v1beta.Corpus} request.corpus - * Required. The `Corpus` 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.ai.generativelanguage.v1beta.Corpus|Corpus}. - * 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/v1beta/retriever_service.create_corpus.js - * region_tag:generativelanguage_v1beta_generated_RetrieverService_CreateCorpus_async - */ + /** + * Creates an empty `Corpus`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ai.generativelanguage.v1beta.Corpus} request.corpus + * Required. The `Corpus` 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.ai.generativelanguage.v1beta.Corpus|Corpus}. + * 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/v1beta/retriever_service.create_corpus.js + * region_tag:generativelanguage_v1beta_generated_RetrieverService_CreateCorpus_async + */ createCorpus( - request?: protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICorpus, + ( + | protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest + | undefined + ), + {} | undefined, + ] + >; createCorpus( - request: protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ICorpus, + | protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createCorpus( - request: protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ICorpus, + | protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createCorpus( - request?: protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.ICorpus, + | protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICorpus, + ( + | protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest + | 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 || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createCorpus request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.ICorpus, + | protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createCorpus response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createCorpus(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest|undefined, - {}|undefined - ]) => { - this._log.info('createCorpus response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createCorpus(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.ICorpus, + ( + | protos.google.ai.generativelanguage.v1beta.ICreateCorpusRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createCorpus response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets information about a specific `Corpus`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the `Corpus`. - * Example: `corpora/my-corpus-123` - * @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.ai.generativelanguage.v1beta.Corpus|Corpus}. - * 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/v1beta/retriever_service.get_corpus.js - * region_tag:generativelanguage_v1beta_generated_RetrieverService_GetCorpus_async - */ + /** + * Gets information about a specific `Corpus`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the `Corpus`. + * Example: `corpora/my-corpus-123` + * @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.ai.generativelanguage.v1beta.Corpus|Corpus}. + * 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/v1beta/retriever_service.get_corpus.js + * region_tag:generativelanguage_v1beta_generated_RetrieverService_GetCorpus_async + */ getCorpus( - request?: protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICorpus, + protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest | undefined, + {} | undefined, + ] + >; getCorpus( - request: protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ICorpus, + | protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getCorpus( - request: protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ICorpus, + | protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getCorpus( - request?: protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.ICorpus, + | protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICorpus, + protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest | 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('getCorpus request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.ICorpus, + | protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getCorpus response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getCorpus(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest|undefined, - {}|undefined - ]) => { - this._log.info('getCorpus response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getCorpus(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.ICorpus, + ( + | protos.google.ai.generativelanguage.v1beta.IGetCorpusRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getCorpus response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a `Corpus`. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ai.generativelanguage.v1beta.Corpus} request.corpus - * Required. The `Corpus` to update. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to update. - * Currently, this only supports updating `display_name`. - * @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.ai.generativelanguage.v1beta.Corpus|Corpus}. - * 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/v1beta/retriever_service.update_corpus.js - * region_tag:generativelanguage_v1beta_generated_RetrieverService_UpdateCorpus_async - */ + /** + * Updates a `Corpus`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ai.generativelanguage.v1beta.Corpus} request.corpus + * Required. The `Corpus` to update. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to update. + * Currently, this only supports updating `display_name`. + * @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.ai.generativelanguage.v1beta.Corpus|Corpus}. + * 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/v1beta/retriever_service.update_corpus.js + * region_tag:generativelanguage_v1beta_generated_RetrieverService_UpdateCorpus_async + */ updateCorpus( - request?: protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICorpus, + ( + | protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest + | undefined + ), + {} | undefined, + ] + >; updateCorpus( - request: protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ICorpus, + | protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCorpus( - request: protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ICorpus, + | protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCorpus( - request?: protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.ICorpus, + | protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICorpus, + ( + | protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest + | 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({ - 'corpus.name': request.corpus!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'corpus.name': request.corpus!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateCorpus request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.ICorpus, + | protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateCorpus response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateCorpus(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.ICorpus, - protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateCorpus response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateCorpus(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.ICorpus, + ( + | protos.google.ai.generativelanguage.v1beta.IUpdateCorpusRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateCorpus response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a `Corpus`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the `Corpus`. - * Example: `corpora/my-corpus-123` - * @param {boolean} [request.force] - * Optional. If set to true, any `Document`s and objects related to this - * `Corpus` will also be deleted. - * - * If false (the default), a `FAILED_PRECONDITION` error will be returned if - * `Corpus` contains any `Document`s. - * @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/v1beta/retriever_service.delete_corpus.js - * region_tag:generativelanguage_v1beta_generated_RetrieverService_DeleteCorpus_async - */ + /** + * Deletes a `Corpus`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the `Corpus`. + * Example: `corpora/my-corpus-123` + * @param {boolean} [request.force] + * Optional. If set to true, any `Document`s and objects related to this + * `Corpus` will also be deleted. + * + * If false (the default), a `FAILED_PRECONDITION` error will be returned if + * `Corpus` contains any `Document`s. + * @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/v1beta/retriever_service.delete_corpus.js + * region_tag:generativelanguage_v1beta_generated_RetrieverService_DeleteCorpus_async + */ deleteCorpus( - request?: protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest + | undefined + ), + {} | undefined, + ] + >; deleteCorpus( - request: protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteCorpus( - request: protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteCorpus( - request?: protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest + | 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('deleteCorpus request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteCorpus response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteCorpus(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteCorpus response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteCorpus(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta.IDeleteCorpusRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteCorpus response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Performs semantic search over a `Corpus`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the `Corpus` to query. - * Example: `corpora/my-corpus-123` - * @param {string} request.query - * Required. Query string to perform semantic search. - * @param {number[]} [request.metadataFilters] - * Optional. Filter for `Chunk` and `Document` metadata. Each `MetadataFilter` - * object should correspond to a unique key. Multiple `MetadataFilter` objects - * are joined by logical "AND"s. - * - * Example query at document level: - * (year >= 2020 OR year < 2010) AND (genre = drama OR genre = action) - * - * `MetadataFilter` object list: - * metadata_filters = [ - * {key = "document.custom_metadata.year" - * conditions = [{int_value = 2020, operation = GREATER_EQUAL}, - * {int_value = 2010, operation = LESS}]}, - * {key = "document.custom_metadata.year" - * conditions = [{int_value = 2020, operation = GREATER_EQUAL}, - * {int_value = 2010, operation = LESS}]}, - * {key = "document.custom_metadata.genre" - * conditions = [{string_value = "drama", operation = EQUAL}, - * {string_value = "action", operation = EQUAL}]}] - * - * Example query at chunk level for a numeric range of values: - * (year > 2015 AND year <= 2020) - * - * `MetadataFilter` object list: - * metadata_filters = [ - * {key = "chunk.custom_metadata.year" - * conditions = [{int_value = 2015, operation = GREATER}]}, - * {key = "chunk.custom_metadata.year" - * conditions = [{int_value = 2020, operation = LESS_EQUAL}]}] - * - * Note: "AND"s for the same key are only supported for numeric values. String - * values only support "OR"s for the same key. - * @param {number} [request.resultsCount] - * Optional. The maximum number of `Chunk`s to return. - * The service may return fewer `Chunk`s. - * - * If unspecified, at most 10 `Chunk`s will be returned. - * The maximum specified result count is 100. - * @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.ai.generativelanguage.v1beta.QueryCorpusResponse|QueryCorpusResponse}. - * 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/v1beta/retriever_service.query_corpus.js - * region_tag:generativelanguage_v1beta_generated_RetrieverService_QueryCorpus_async - */ + /** + * Performs semantic search over a `Corpus`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the `Corpus` to query. + * Example: `corpora/my-corpus-123` + * @param {string} request.query + * Required. Query string to perform semantic search. + * @param {number[]} [request.metadataFilters] + * Optional. Filter for `Chunk` and `Document` metadata. Each `MetadataFilter` + * object should correspond to a unique key. Multiple `MetadataFilter` objects + * are joined by logical "AND"s. + * + * Example query at document level: + * (year >= 2020 OR year < 2010) AND (genre = drama OR genre = action) + * + * `MetadataFilter` object list: + * metadata_filters = [ + * {key = "document.custom_metadata.year" + * conditions = [{int_value = 2020, operation = GREATER_EQUAL}, + * {int_value = 2010, operation = LESS}]}, + * {key = "document.custom_metadata.year" + * conditions = [{int_value = 2020, operation = GREATER_EQUAL}, + * {int_value = 2010, operation = LESS}]}, + * {key = "document.custom_metadata.genre" + * conditions = [{string_value = "drama", operation = EQUAL}, + * {string_value = "action", operation = EQUAL}]}] + * + * Example query at chunk level for a numeric range of values: + * (year > 2015 AND year <= 2020) + * + * `MetadataFilter` object list: + * metadata_filters = [ + * {key = "chunk.custom_metadata.year" + * conditions = [{int_value = 2015, operation = GREATER}]}, + * {key = "chunk.custom_metadata.year" + * conditions = [{int_value = 2020, operation = LESS_EQUAL}]}] + * + * Note: "AND"s for the same key are only supported for numeric values. String + * values only support "OR"s for the same key. + * @param {number} [request.resultsCount] + * Optional. The maximum number of `Chunk`s to return. + * The service may return fewer `Chunk`s. + * + * If unspecified, at most 10 `Chunk`s will be returned. + * The maximum specified result count is 100. + * @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.ai.generativelanguage.v1beta.QueryCorpusResponse|QueryCorpusResponse}. + * 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/v1beta/retriever_service.query_corpus.js + * region_tag:generativelanguage_v1beta_generated_RetrieverService_QueryCorpus_async + */ queryCorpus( - request?: protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IQueryCorpusResponse, - protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IQueryCorpusResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest + | undefined + ), + {} | undefined, + ] + >; queryCorpus( - request: protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IQueryCorpusResponse, - protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IQueryCorpusResponse, + | protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): void; queryCorpus( - request: protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IQueryCorpusResponse, - protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IQueryCorpusResponse, + | protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): void; queryCorpus( - request?: protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.IQueryCorpusResponse, - protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IQueryCorpusResponse, - protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IQueryCorpusResponse, - protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IQueryCorpusResponse, + | protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IQueryCorpusResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest + | 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('queryCorpus request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.IQueryCorpusResponse, - protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IQueryCorpusResponse, + | protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('queryCorpus response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.queryCorpus(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.IQueryCorpusResponse, - protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest|undefined, - {}|undefined - ]) => { - this._log.info('queryCorpus response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .queryCorpus(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IQueryCorpusResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IQueryCorpusRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('queryCorpus response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates an empty `Document`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the `Corpus` where this `Document` will be created. - * Example: `corpora/my-corpus-123` - * @param {google.ai.generativelanguage.v1beta.Document} request.document - * Required. The `Document` 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.ai.generativelanguage.v1beta.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/v1beta/retriever_service.create_document.js - * region_tag:generativelanguage_v1beta_generated_RetrieverService_CreateDocument_async - */ + /** + * Creates an empty `Document`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the `Corpus` where this `Document` will be created. + * Example: `corpora/my-corpus-123` + * @param {google.ai.generativelanguage.v1beta.Document} request.document + * Required. The `Document` 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.ai.generativelanguage.v1beta.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/v1beta/retriever_service.create_document.js + * region_tag:generativelanguage_v1beta_generated_RetrieverService_CreateDocument_async + */ createDocument( - request?: protos.google.ai.generativelanguage.v1beta.ICreateDocumentRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.ICreateDocumentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.ICreateDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IDocument, + ( + | protos.google.ai.generativelanguage.v1beta.ICreateDocumentRequest + | undefined + ), + {} | undefined, + ] + >; createDocument( - request: protos.google.ai.generativelanguage.v1beta.ICreateDocumentRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.ICreateDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.ICreateDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IDocument, + | protos.google.ai.generativelanguage.v1beta.ICreateDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createDocument( - request: protos.google.ai.generativelanguage.v1beta.ICreateDocumentRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.ICreateDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.ICreateDocumentRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IDocument, + | protos.google.ai.generativelanguage.v1beta.ICreateDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createDocument( - request?: protos.google.ai.generativelanguage.v1beta.ICreateDocumentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.ICreateDocumentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.ICreateDocumentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.ICreateDocumentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.ICreateDocumentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.ICreateDocumentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IDocument, + | protos.google.ai.generativelanguage.v1beta.ICreateDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IDocument, + ( + | protos.google.ai.generativelanguage.v1beta.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 ?? '', + 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('createDocument request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.ICreateDocumentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IDocument, + | protos.google.ai.generativelanguage.v1beta.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.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.ICreateDocumentRequest|undefined, - {}|undefined - ]) => { - this._log.info('createDocument response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createDocument(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IDocument, + ( + | protos.google.ai.generativelanguage.v1beta.ICreateDocumentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createDocument response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets information about a specific `Document`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the `Document` to retrieve. - * Example: `corpora/my-corpus-123/documents/the-doc-abc` - * @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.ai.generativelanguage.v1beta.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/v1beta/retriever_service.get_document.js - * region_tag:generativelanguage_v1beta_generated_RetrieverService_GetDocument_async - */ + /** + * Gets information about a specific `Document`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the `Document` to retrieve. + * Example: `corpora/my-corpus-123/documents/the-doc-abc` + * @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.ai.generativelanguage.v1beta.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/v1beta/retriever_service.get_document.js + * region_tag:generativelanguage_v1beta_generated_RetrieverService_GetDocument_async + */ getDocument( - request?: protos.google.ai.generativelanguage.v1beta.IGetDocumentRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.IGetDocumentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IGetDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IDocument, + ( + | protos.google.ai.generativelanguage.v1beta.IGetDocumentRequest + | undefined + ), + {} | undefined, + ] + >; getDocument( - request: protos.google.ai.generativelanguage.v1beta.IGetDocumentRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.IGetDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGetDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IDocument, + | protos.google.ai.generativelanguage.v1beta.IGetDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDocument( - request: protos.google.ai.generativelanguage.v1beta.IGetDocumentRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.IGetDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGetDocumentRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IDocument, + | protos.google.ai.generativelanguage.v1beta.IGetDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDocument( - request?: protos.google.ai.generativelanguage.v1beta.IGetDocumentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.IGetDocumentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IGetDocumentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.IGetDocumentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.IGetDocumentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IGetDocumentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IDocument, + | protos.google.ai.generativelanguage.v1beta.IGetDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IDocument, + ( + | protos.google.ai.generativelanguage.v1beta.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.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.IGetDocumentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IDocument, + | protos.google.ai.generativelanguage.v1beta.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.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.IGetDocumentRequest|undefined, - {}|undefined - ]) => { - this._log.info('getDocument response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getDocument(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IDocument, + ( + | protos.google.ai.generativelanguage.v1beta.IGetDocumentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getDocument response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a `Document`. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ai.generativelanguage.v1beta.Document} request.document - * Required. The `Document` to update. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to update. - * Currently, this only supports updating `display_name` and - * `custom_metadata`. - * @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.ai.generativelanguage.v1beta.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/v1beta/retriever_service.update_document.js - * region_tag:generativelanguage_v1beta_generated_RetrieverService_UpdateDocument_async - */ + /** + * Updates a `Document`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ai.generativelanguage.v1beta.Document} request.document + * Required. The `Document` to update. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to update. + * Currently, this only supports updating `display_name` and + * `custom_metadata`. + * @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.ai.generativelanguage.v1beta.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/v1beta/retriever_service.update_document.js + * region_tag:generativelanguage_v1beta_generated_RetrieverService_UpdateDocument_async + */ updateDocument( - request?: protos.google.ai.generativelanguage.v1beta.IUpdateDocumentRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.IUpdateDocumentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IUpdateDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IDocument, + ( + | protos.google.ai.generativelanguage.v1beta.IUpdateDocumentRequest + | undefined + ), + {} | undefined, + ] + >; updateDocument( - request: protos.google.ai.generativelanguage.v1beta.IUpdateDocumentRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.IUpdateDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IUpdateDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IDocument, + | protos.google.ai.generativelanguage.v1beta.IUpdateDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDocument( - request: protos.google.ai.generativelanguage.v1beta.IUpdateDocumentRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.IUpdateDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IUpdateDocumentRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IDocument, + | protos.google.ai.generativelanguage.v1beta.IUpdateDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDocument( - request?: protos.google.ai.generativelanguage.v1beta.IUpdateDocumentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.IUpdateDocumentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IUpdateDocumentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.IUpdateDocumentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.IUpdateDocumentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IUpdateDocumentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IDocument, + | protos.google.ai.generativelanguage.v1beta.IUpdateDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IDocument, + ( + | protos.google.ai.generativelanguage.v1beta.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.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.IUpdateDocumentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IDocument, + | protos.google.ai.generativelanguage.v1beta.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.ai.generativelanguage.v1beta.IDocument, - protos.google.ai.generativelanguage.v1beta.IUpdateDocumentRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateDocument response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateDocument(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IDocument, + ( + | protos.google.ai.generativelanguage.v1beta.IUpdateDocumentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateDocument response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * 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. - * Example: `corpora/my-corpus-123/documents/the-doc-abc` - * @param {boolean} [request.force] - * Optional. If set to true, any `Chunk`s and objects related to this - * `Document` will also be deleted. - * - * If false (the default), a `FAILED_PRECONDITION` error will be returned if - * `Document` contains any `Chunk`s. - * @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/v1beta/retriever_service.delete_document.js - * region_tag:generativelanguage_v1beta_generated_RetrieverService_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. + * Example: `corpora/my-corpus-123/documents/the-doc-abc` + * @param {boolean} [request.force] + * Optional. If set to true, any `Chunk`s and objects related to this + * `Document` will also be deleted. + * + * If false (the default), a `FAILED_PRECONDITION` error will be returned if + * `Document` contains any `Chunk`s. + * @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/v1beta/retriever_service.delete_document.js + * region_tag:generativelanguage_v1beta_generated_RetrieverService_DeleteDocument_async + */ deleteDocument( - request?: protos.google.ai.generativelanguage.v1beta.IDeleteDocumentRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteDocumentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IDeleteDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta.IDeleteDocumentRequest + | undefined + ), + {} | undefined, + ] + >; deleteDocument( - request: protos.google.ai.generativelanguage.v1beta.IDeleteDocumentRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IDeleteDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeleteDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteDocument( - request: protos.google.ai.generativelanguage.v1beta.IDeleteDocumentRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IDeleteDocumentRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeleteDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteDocument( - request?: protos.google.ai.generativelanguage.v1beta.IDeleteDocumentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteDocumentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IDeleteDocumentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteDocumentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteDocumentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IDeleteDocumentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeleteDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta.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.ai.generativelanguage.v1beta.IDeleteDocumentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.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.ai.generativelanguage.v1beta.IDeleteDocumentRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteDocument response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteDocument(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta.IDeleteDocumentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteDocument response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Performs semantic search over a `Document`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the `Document` to query. - * Example: `corpora/my-corpus-123/documents/the-doc-abc` - * @param {string} request.query - * Required. Query string to perform semantic search. - * @param {number} [request.resultsCount] - * Optional. The maximum number of `Chunk`s to return. - * The service may return fewer `Chunk`s. - * - * If unspecified, at most 10 `Chunk`s will be returned. - * The maximum specified result count is 100. - * @param {number[]} [request.metadataFilters] - * Optional. Filter for `Chunk` metadata. Each `MetadataFilter` object should - * correspond to a unique key. Multiple `MetadataFilter` objects are joined by - * logical "AND"s. - * - * Note: `Document`-level filtering is not supported for this request because - * a `Document` name is already specified. - * - * Example query: - * (year >= 2020 OR year < 2010) AND (genre = drama OR genre = action) - * - * `MetadataFilter` object list: - * metadata_filters = [ - * {key = "chunk.custom_metadata.year" - * conditions = [{int_value = 2020, operation = GREATER_EQUAL}, - * {int_value = 2010, operation = LESS}}, - * {key = "chunk.custom_metadata.genre" - * conditions = [{string_value = "drama", operation = EQUAL}, - * {string_value = "action", operation = EQUAL}}] - * - * Example query for a numeric range of values: - * (year > 2015 AND year <= 2020) - * - * `MetadataFilter` object list: - * metadata_filters = [ - * {key = "chunk.custom_metadata.year" - * conditions = [{int_value = 2015, operation = GREATER}]}, - * {key = "chunk.custom_metadata.year" - * conditions = [{int_value = 2020, operation = LESS_EQUAL}]}] - * - * Note: "AND"s for the same key are only supported for numeric values. String - * values only support "OR"s for the same key. - * @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.ai.generativelanguage.v1beta.QueryDocumentResponse|QueryDocumentResponse}. - * 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/v1beta/retriever_service.query_document.js - * region_tag:generativelanguage_v1beta_generated_RetrieverService_QueryDocument_async - */ + /** + * Performs semantic search over a `Document`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the `Document` to query. + * Example: `corpora/my-corpus-123/documents/the-doc-abc` + * @param {string} request.query + * Required. Query string to perform semantic search. + * @param {number} [request.resultsCount] + * Optional. The maximum number of `Chunk`s to return. + * The service may return fewer `Chunk`s. + * + * If unspecified, at most 10 `Chunk`s will be returned. + * The maximum specified result count is 100. + * @param {number[]} [request.metadataFilters] + * Optional. Filter for `Chunk` metadata. Each `MetadataFilter` object should + * correspond to a unique key. Multiple `MetadataFilter` objects are joined by + * logical "AND"s. + * + * Note: `Document`-level filtering is not supported for this request because + * a `Document` name is already specified. + * + * Example query: + * (year >= 2020 OR year < 2010) AND (genre = drama OR genre = action) + * + * `MetadataFilter` object list: + * metadata_filters = [ + * {key = "chunk.custom_metadata.year" + * conditions = [{int_value = 2020, operation = GREATER_EQUAL}, + * {int_value = 2010, operation = LESS}}, + * {key = "chunk.custom_metadata.genre" + * conditions = [{string_value = "drama", operation = EQUAL}, + * {string_value = "action", operation = EQUAL}}] + * + * Example query for a numeric range of values: + * (year > 2015 AND year <= 2020) + * + * `MetadataFilter` object list: + * metadata_filters = [ + * {key = "chunk.custom_metadata.year" + * conditions = [{int_value = 2015, operation = GREATER}]}, + * {key = "chunk.custom_metadata.year" + * conditions = [{int_value = 2020, operation = LESS_EQUAL}]}] + * + * Note: "AND"s for the same key are only supported for numeric values. String + * values only support "OR"s for the same key. + * @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.ai.generativelanguage.v1beta.QueryDocumentResponse|QueryDocumentResponse}. + * 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/v1beta/retriever_service.query_document.js + * region_tag:generativelanguage_v1beta_generated_RetrieverService_QueryDocument_async + */ queryDocument( - request?: protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IQueryDocumentResponse, - protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IQueryDocumentResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest + | undefined + ), + {} | undefined, + ] + >; queryDocument( - request: protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IQueryDocumentResponse, - protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IQueryDocumentResponse, + | protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; queryDocument( - request: protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IQueryDocumentResponse, - protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IQueryDocumentResponse, + | protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): void; queryDocument( - request?: protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.IQueryDocumentResponse, - protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IQueryDocumentResponse, - protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IQueryDocumentResponse, - protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IQueryDocumentResponse, + | protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IQueryDocumentResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest + | 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('queryDocument request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.IQueryDocumentResponse, - protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IQueryDocumentResponse, + | protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('queryDocument response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.queryDocument(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.IQueryDocumentResponse, - protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest|undefined, - {}|undefined - ]) => { - this._log.info('queryDocument response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .queryDocument(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IQueryDocumentResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IQueryDocumentRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('queryDocument response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a `Chunk`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the `Document` where this `Chunk` will be created. - * Example: `corpora/my-corpus-123/documents/the-doc-abc` - * @param {google.ai.generativelanguage.v1beta.Chunk} request.chunk - * Required. The `Chunk` 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.ai.generativelanguage.v1beta.Chunk|Chunk}. - * 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/v1beta/retriever_service.create_chunk.js - * region_tag:generativelanguage_v1beta_generated_RetrieverService_CreateChunk_async - */ + /** + * Creates a `Chunk`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the `Document` where this `Chunk` will be created. + * Example: `corpora/my-corpus-123/documents/the-doc-abc` + * @param {google.ai.generativelanguage.v1beta.Chunk} request.chunk + * Required. The `Chunk` 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.ai.generativelanguage.v1beta.Chunk|Chunk}. + * 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/v1beta/retriever_service.create_chunk.js + * region_tag:generativelanguage_v1beta_generated_RetrieverService_CreateChunk_async + */ createChunk( - request?: protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IChunk, + ( + | protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest + | undefined + ), + {} | undefined, + ] + >; createChunk( - request: protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IChunk, + | protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createChunk( - request: protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IChunk, + | protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createChunk( - request?: protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IChunk, + | protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IChunk, + ( + | protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest + | 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('createChunk request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IChunk, + | protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createChunk response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createChunk(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest|undefined, - {}|undefined - ]) => { - this._log.info('createChunk response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createChunk(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IChunk, + ( + | protos.google.ai.generativelanguage.v1beta.ICreateChunkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createChunk response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Batch create `Chunk`s. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} [request.parent] - * Optional. The name of the `Document` where this batch of `Chunk`s will be - * created. The parent field in every `CreateChunkRequest` must match this - * value. Example: `corpora/my-corpus-123/documents/the-doc-abc` - * @param {number[]} request.requests - * Required. The request messages specifying the `Chunk`s to create. - * A maximum of 100 `Chunk`s can be created in a batch. - * @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.ai.generativelanguage.v1beta.BatchCreateChunksResponse|BatchCreateChunksResponse}. - * 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/v1beta/retriever_service.batch_create_chunks.js - * region_tag:generativelanguage_v1beta_generated_RetrieverService_BatchCreateChunks_async - */ + /** + * Batch create `Chunk`s. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} [request.parent] + * Optional. The name of the `Document` where this batch of `Chunk`s will be + * created. The parent field in every `CreateChunkRequest` must match this + * value. Example: `corpora/my-corpus-123/documents/the-doc-abc` + * @param {number[]} request.requests + * Required. The request messages specifying the `Chunk`s to create. + * A maximum of 100 `Chunk`s can be created in a batch. + * @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.ai.generativelanguage.v1beta.BatchCreateChunksResponse|BatchCreateChunksResponse}. + * 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/v1beta/retriever_service.batch_create_chunks.js + * region_tag:generativelanguage_v1beta_generated_RetrieverService_BatchCreateChunks_async + */ batchCreateChunks( - request?: protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksResponse, - protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest + | undefined + ), + {} | undefined, + ] + >; batchCreateChunks( - request: protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksResponse, - protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksResponse, + | protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchCreateChunks( - request: protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksResponse, - protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksResponse, + | protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchCreateChunks( - request?: protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksResponse, - protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksResponse, - protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksResponse, - protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksResponse, + | protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest + | 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('batchCreateChunks request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksResponse, - protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksResponse, + | protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchCreateChunks response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.batchCreateChunks(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksResponse, - protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest|undefined, - {}|undefined - ]) => { - this._log.info('batchCreateChunks response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchCreateChunks(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchCreateChunks response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets information about a specific `Chunk`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the `Chunk` to retrieve. - * Example: `corpora/my-corpus-123/documents/the-doc-abc/chunks/some-chunk` - * @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.ai.generativelanguage.v1beta.Chunk|Chunk}. - * 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/v1beta/retriever_service.get_chunk.js - * region_tag:generativelanguage_v1beta_generated_RetrieverService_GetChunk_async - */ + /** + * Gets information about a specific `Chunk`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the `Chunk` to retrieve. + * Example: `corpora/my-corpus-123/documents/the-doc-abc/chunks/some-chunk` + * @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.ai.generativelanguage.v1beta.Chunk|Chunk}. + * 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/v1beta/retriever_service.get_chunk.js + * region_tag:generativelanguage_v1beta_generated_RetrieverService_GetChunk_async + */ getChunk( - request?: protos.google.ai.generativelanguage.v1beta.IGetChunkRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.IGetChunkRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IGetChunkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IChunk, + protos.google.ai.generativelanguage.v1beta.IGetChunkRequest | undefined, + {} | undefined, + ] + >; getChunk( - request: protos.google.ai.generativelanguage.v1beta.IGetChunkRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.IGetChunkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGetChunkRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IChunk, + | protos.google.ai.generativelanguage.v1beta.IGetChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getChunk( - request: protos.google.ai.generativelanguage.v1beta.IGetChunkRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.IGetChunkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGetChunkRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IChunk, + | protos.google.ai.generativelanguage.v1beta.IGetChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getChunk( - request?: protos.google.ai.generativelanguage.v1beta.IGetChunkRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta.IGetChunkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.IGetChunkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.IGetChunkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.IGetChunkRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IGetChunkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IChunk, + | protos.google.ai.generativelanguage.v1beta.IGetChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IChunk, + protos.google.ai.generativelanguage.v1beta.IGetChunkRequest | 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('getChunk request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.IGetChunkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IChunk, + | protos.google.ai.generativelanguage.v1beta.IGetChunkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getChunk response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getChunk(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.IGetChunkRequest|undefined, - {}|undefined - ]) => { - this._log.info('getChunk response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getChunk(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IChunk, + ( + | protos.google.ai.generativelanguage.v1beta.IGetChunkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getChunk response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a `Chunk`. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ai.generativelanguage.v1beta.Chunk} request.chunk - * Required. The `Chunk` to update. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to update. - * Currently, this only supports updating `custom_metadata` and `data`. - * @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.ai.generativelanguage.v1beta.Chunk|Chunk}. - * 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/v1beta/retriever_service.update_chunk.js - * region_tag:generativelanguage_v1beta_generated_RetrieverService_UpdateChunk_async - */ + /** + * Updates a `Chunk`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ai.generativelanguage.v1beta.Chunk} request.chunk + * Required. The `Chunk` to update. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to update. + * Currently, this only supports updating `custom_metadata` and `data`. + * @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.ai.generativelanguage.v1beta.Chunk|Chunk}. + * 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/v1beta/retriever_service.update_chunk.js + * region_tag:generativelanguage_v1beta_generated_RetrieverService_UpdateChunk_async + */ updateChunk( - request?: protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IChunk, + ( + | protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest + | undefined + ), + {} | undefined, + ] + >; updateChunk( - request: protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IChunk, + | protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateChunk( - request: protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IChunk, + | protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateChunk( - request?: protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IChunk, + | protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IChunk, + ( + | protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest + | 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({ - 'chunk.name': request.chunk!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'chunk.name': request.chunk!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateChunk request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IChunk, + | protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateChunk response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateChunk(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.IChunk, - protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateChunk response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateChunk(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IChunk, + ( + | protos.google.ai.generativelanguage.v1beta.IUpdateChunkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateChunk response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Batch update `Chunk`s. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} [request.parent] - * Optional. The name of the `Document` containing the `Chunk`s to update. - * The parent field in every `UpdateChunkRequest` must match this value. - * Example: `corpora/my-corpus-123/documents/the-doc-abc` - * @param {number[]} request.requests - * Required. The request messages specifying the `Chunk`s to update. - * A maximum of 100 `Chunk`s can be updated in a batch. - * @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.ai.generativelanguage.v1beta.BatchUpdateChunksResponse|BatchUpdateChunksResponse}. - * 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/v1beta/retriever_service.batch_update_chunks.js - * region_tag:generativelanguage_v1beta_generated_RetrieverService_BatchUpdateChunks_async - */ + /** + * Batch update `Chunk`s. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} [request.parent] + * Optional. The name of the `Document` containing the `Chunk`s to update. + * The parent field in every `UpdateChunkRequest` must match this value. + * Example: `corpora/my-corpus-123/documents/the-doc-abc` + * @param {number[]} request.requests + * Required. The request messages specifying the `Chunk`s to update. + * A maximum of 100 `Chunk`s can be updated in a batch. + * @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.ai.generativelanguage.v1beta.BatchUpdateChunksResponse|BatchUpdateChunksResponse}. + * 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/v1beta/retriever_service.batch_update_chunks.js + * region_tag:generativelanguage_v1beta_generated_RetrieverService_BatchUpdateChunks_async + */ batchUpdateChunks( - request?: protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksResponse, - protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest + | undefined + ), + {} | undefined, + ] + >; batchUpdateChunks( - request: protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksResponse, - protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksResponse, + | protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchUpdateChunks( - request: protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksResponse, - protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksResponse, + | protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchUpdateChunks( - request?: protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksResponse, - protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksResponse, - protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksResponse, - protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksResponse, + | protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest + | 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('batchUpdateChunks request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksResponse, - protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksResponse, + | protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchUpdateChunks response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.batchUpdateChunks(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksResponse, - protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest|undefined, - {}|undefined - ]) => { - this._log.info('batchUpdateChunks response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchUpdateChunks(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchUpdateChunks response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a `Chunk`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the `Chunk` to delete. - * Example: `corpora/my-corpus-123/documents/the-doc-abc/chunks/some-chunk` - * @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/v1beta/retriever_service.delete_chunk.js - * region_tag:generativelanguage_v1beta_generated_RetrieverService_DeleteChunk_async - */ + /** + * Deletes a `Chunk`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the `Chunk` to delete. + * Example: `corpora/my-corpus-123/documents/the-doc-abc/chunks/some-chunk` + * @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/v1beta/retriever_service.delete_chunk.js + * region_tag:generativelanguage_v1beta_generated_RetrieverService_DeleteChunk_async + */ deleteChunk( - request?: protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest + | undefined + ), + {} | undefined, + ] + >; deleteChunk( - request: protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteChunk( - request: protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteChunk( - request?: protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest + | 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('deleteChunk request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteChunk response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteChunk(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteChunk response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteChunk(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta.IDeleteChunkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteChunk response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Batch delete `Chunk`s. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} [request.parent] - * Optional. The name of the `Document` containing the `Chunk`s to delete. - * The parent field in every `DeleteChunkRequest` must match this value. - * Example: `corpora/my-corpus-123/documents/the-doc-abc` - * @param {number[]} request.requests - * Required. The request messages specifying the `Chunk`s to delete. - * @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/v1beta/retriever_service.batch_delete_chunks.js - * region_tag:generativelanguage_v1beta_generated_RetrieverService_BatchDeleteChunks_async - */ + /** + * Batch delete `Chunk`s. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} [request.parent] + * Optional. The name of the `Document` containing the `Chunk`s to delete. + * The parent field in every `DeleteChunkRequest` must match this value. + * Example: `corpora/my-corpus-123/documents/the-doc-abc` + * @param {number[]} request.requests + * Required. The request messages specifying the `Chunk`s to delete. + * @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/v1beta/retriever_service.batch_delete_chunks.js + * region_tag:generativelanguage_v1beta_generated_RetrieverService_BatchDeleteChunks_async + */ batchDeleteChunks( - request?: protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest + | undefined + ), + {} | undefined, + ] + >; batchDeleteChunks( - request: protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchDeleteChunks( - request: protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchDeleteChunks( - request?: protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest + | 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('batchDeleteChunks request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchDeleteChunks response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.batchDeleteChunks(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest|undefined, - {}|undefined - ]) => { - this._log.info('batchDeleteChunks response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchDeleteChunks(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta.IBatchDeleteChunksRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchDeleteChunks response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists all `Corpora` owned by the user. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of `Corpora` to return (per page). - * The service may return fewer `Corpora`. - * - * If unspecified, at most 10 `Corpora` will be returned. - * The maximum size limit is 20 `Corpora` per page. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListCorpora` call. - * - * Provide the `next_page_token` returned in the response as an argument to - * the next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListCorpora` - * must match the call that provided the page token. - * @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.ai.generativelanguage.v1beta.Corpus|Corpus}. - * 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 `listCorporaAsync()` - * 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 `Corpora` owned by the user. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of `Corpora` to return (per page). + * The service may return fewer `Corpora`. + * + * If unspecified, at most 10 `Corpora` will be returned. + * The maximum size limit is 20 `Corpora` per page. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListCorpora` call. + * + * Provide the `next_page_token` returned in the response as an argument to + * the next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListCorpora` + * must match the call that provided the page token. + * @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.ai.generativelanguage.v1beta.Corpus|Corpus}. + * 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 `listCorporaAsync()` + * 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. + */ listCorpora( - request?: protos.google.ai.generativelanguage.v1beta.IListCorporaRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICorpus[], - protos.google.ai.generativelanguage.v1beta.IListCorporaRequest|null, - protos.google.ai.generativelanguage.v1beta.IListCorporaResponse - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IListCorporaRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICorpus[], + protos.google.ai.generativelanguage.v1beta.IListCorporaRequest | null, + protos.google.ai.generativelanguage.v1beta.IListCorporaResponse, + ] + >; listCorpora( - request: protos.google.ai.generativelanguage.v1beta.IListCorporaRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListCorporaRequest, - protos.google.ai.generativelanguage.v1beta.IListCorporaResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.ICorpus>): void; + request: protos.google.ai.generativelanguage.v1beta.IListCorporaRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListCorporaRequest, + | protos.google.ai.generativelanguage.v1beta.IListCorporaResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.ICorpus + >, + ): void; listCorpora( - request: protos.google.ai.generativelanguage.v1beta.IListCorporaRequest, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListCorporaRequest, - protos.google.ai.generativelanguage.v1beta.IListCorporaResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.ICorpus>): void; + request: protos.google.ai.generativelanguage.v1beta.IListCorporaRequest, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListCorporaRequest, + | protos.google.ai.generativelanguage.v1beta.IListCorporaResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.ICorpus + >, + ): void; listCorpora( - request?: protos.google.ai.generativelanguage.v1beta.IListCorporaRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.ai.generativelanguage.v1beta.IListCorporaRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ai.generativelanguage.v1beta.IListCorporaRequest, - protos.google.ai.generativelanguage.v1beta.IListCorporaResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.ICorpus>, - callback?: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListCorporaRequest, - protos.google.ai.generativelanguage.v1beta.IListCorporaResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.ICorpus>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICorpus[], - protos.google.ai.generativelanguage.v1beta.IListCorporaRequest|null, - protos.google.ai.generativelanguage.v1beta.IListCorporaResponse - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IListCorporaResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.ICorpus + >, + callback?: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListCorporaRequest, + | protos.google.ai.generativelanguage.v1beta.IListCorporaResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.ICorpus + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICorpus[], + protos.google.ai.generativelanguage.v1beta.IListCorporaRequest | null, + protos.google.ai.generativelanguage.v1beta.IListCorporaResponse, + ] + > | 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 || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListCorporaRequest, - protos.google.ai.generativelanguage.v1beta.IListCorporaResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.ICorpus>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListCorporaRequest, + | protos.google.ai.generativelanguage.v1beta.IListCorporaResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.ICorpus + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listCorpora values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -2178,206 +3095,237 @@ export class RetrieverServiceClient { this._log.info('listCorpora request %j', request); return this.innerApiCalls .listCorpora(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ai.generativelanguage.v1beta.ICorpus[], - protos.google.ai.generativelanguage.v1beta.IListCorporaRequest|null, - protos.google.ai.generativelanguage.v1beta.IListCorporaResponse - ]) => { - this._log.info('listCorpora values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ai.generativelanguage.v1beta.ICorpus[], + protos.google.ai.generativelanguage.v1beta.IListCorporaRequest | null, + protos.google.ai.generativelanguage.v1beta.IListCorporaResponse, + ]) => { + this._log.info('listCorpora values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listCorpora`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of `Corpora` to return (per page). - * The service may return fewer `Corpora`. - * - * If unspecified, at most 10 `Corpora` will be returned. - * The maximum size limit is 20 `Corpora` per page. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListCorpora` call. - * - * Provide the `next_page_token` returned in the response as an argument to - * the next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListCorpora` - * must match the call that provided the page token. - * @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.ai.generativelanguage.v1beta.Corpus|Corpus} 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 `listCorporaAsync()` - * 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 `listCorpora`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of `Corpora` to return (per page). + * The service may return fewer `Corpora`. + * + * If unspecified, at most 10 `Corpora` will be returned. + * The maximum size limit is 20 `Corpora` per page. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListCorpora` call. + * + * Provide the `next_page_token` returned in the response as an argument to + * the next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListCorpora` + * must match the call that provided the page token. + * @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.ai.generativelanguage.v1beta.Corpus|Corpus} 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 `listCorporaAsync()` + * 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. + */ listCorporaStream( - request?: protos.google.ai.generativelanguage.v1beta.IListCorporaRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ai.generativelanguage.v1beta.IListCorporaRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listCorpora']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCorpora stream %j', request); return this.descriptors.page.listCorpora.createStream( this.innerApiCalls.listCorpora as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listCorpora`, 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 {number} [request.pageSize] - * Optional. The maximum number of `Corpora` to return (per page). - * The service may return fewer `Corpora`. - * - * If unspecified, at most 10 `Corpora` will be returned. - * The maximum size limit is 20 `Corpora` per page. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListCorpora` call. - * - * Provide the `next_page_token` returned in the response as an argument to - * the next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListCorpora` - * must match the call that provided the 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 protos.google.ai.generativelanguage.v1beta.Corpus|Corpus}. 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 include:samples/generated/v1beta/retriever_service.list_corpora.js - * region_tag:generativelanguage_v1beta_generated_RetrieverService_ListCorpora_async - */ + /** + * Equivalent to `listCorpora`, 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 {number} [request.pageSize] + * Optional. The maximum number of `Corpora` to return (per page). + * The service may return fewer `Corpora`. + * + * If unspecified, at most 10 `Corpora` will be returned. + * The maximum size limit is 20 `Corpora` per page. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListCorpora` call. + * + * Provide the `next_page_token` returned in the response as an argument to + * the next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListCorpora` + * must match the call that provided the 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 protos.google.ai.generativelanguage.v1beta.Corpus|Corpus}. 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 include:samples/generated/v1beta/retriever_service.list_corpora.js + * region_tag:generativelanguage_v1beta_generated_RetrieverService_ListCorpora_async + */ listCorporaAsync( - request?: protos.google.ai.generativelanguage.v1beta.IListCorporaRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ai.generativelanguage.v1beta.IListCorporaRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listCorpora']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCorpora iterate %j', request); return this.descriptors.page.listCorpora.asyncIterate( this.innerApiCalls['listCorpora'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists all `Document`s in a `Corpus`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the `Corpus` containing `Document`s. - * Example: `corpora/my-corpus-123` - * @param {number} [request.pageSize] - * Optional. The maximum number of `Document`s to return (per page). - * The service may return fewer `Document`s. - * - * If unspecified, at most 10 `Document`s will be returned. - * The maximum size limit is 20 `Document`s per page. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListDocuments` call. - * - * Provide the `next_page_token` returned in the response as an argument to - * the next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListDocuments` - * must match the call that provided the page token. - * @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.ai.generativelanguage.v1beta.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 all `Document`s in a `Corpus`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the `Corpus` containing `Document`s. + * Example: `corpora/my-corpus-123` + * @param {number} [request.pageSize] + * Optional. The maximum number of `Document`s to return (per page). + * The service may return fewer `Document`s. + * + * If unspecified, at most 10 `Document`s will be returned. + * The maximum size limit is 20 `Document`s per page. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListDocuments` call. + * + * Provide the `next_page_token` returned in the response as an argument to + * the next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListDocuments` + * must match the call that provided the page token. + * @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.ai.generativelanguage.v1beta.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.ai.generativelanguage.v1beta.IListDocumentsRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IDocument[], - protos.google.ai.generativelanguage.v1beta.IListDocumentsRequest|null, - protos.google.ai.generativelanguage.v1beta.IListDocumentsResponse - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IListDocumentsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IDocument[], + protos.google.ai.generativelanguage.v1beta.IListDocumentsRequest | null, + protos.google.ai.generativelanguage.v1beta.IListDocumentsResponse, + ] + >; listDocuments( - request: protos.google.ai.generativelanguage.v1beta.IListDocumentsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListDocumentsRequest, - protos.google.ai.generativelanguage.v1beta.IListDocumentsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IDocument>): void; + request: protos.google.ai.generativelanguage.v1beta.IListDocumentsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListDocumentsRequest, + | protos.google.ai.generativelanguage.v1beta.IListDocumentsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IDocument + >, + ): void; listDocuments( - request: protos.google.ai.generativelanguage.v1beta.IListDocumentsRequest, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListDocumentsRequest, - protos.google.ai.generativelanguage.v1beta.IListDocumentsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IDocument>): void; + request: protos.google.ai.generativelanguage.v1beta.IListDocumentsRequest, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListDocumentsRequest, + | protos.google.ai.generativelanguage.v1beta.IListDocumentsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IDocument + >, + ): void; listDocuments( - request?: protos.google.ai.generativelanguage.v1beta.IListDocumentsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.ai.generativelanguage.v1beta.IListDocumentsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ai.generativelanguage.v1beta.IListDocumentsRequest, - protos.google.ai.generativelanguage.v1beta.IListDocumentsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IDocument>, - callback?: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListDocumentsRequest, - protos.google.ai.generativelanguage.v1beta.IListDocumentsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IDocument>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IDocument[], - protos.google.ai.generativelanguage.v1beta.IListDocumentsRequest|null, - protos.google.ai.generativelanguage.v1beta.IListDocumentsResponse - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IListDocumentsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IDocument + >, + callback?: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListDocumentsRequest, + | protos.google.ai.generativelanguage.v1beta.IListDocumentsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IDocument + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IDocument[], + protos.google.ai.generativelanguage.v1beta.IListDocumentsRequest | null, + protos.google.ai.generativelanguage.v1beta.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 ?? '', + 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.ai.generativelanguage.v1beta.IListDocumentsRequest, - protos.google.ai.generativelanguage.v1beta.IListDocumentsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IDocument>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListDocumentsRequest, + | protos.google.ai.generativelanguage.v1beta.IListDocumentsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IDocument + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listDocuments values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -2386,222 +3334,251 @@ export class RetrieverServiceClient { this._log.info('listDocuments request %j', request); return this.innerApiCalls .listDocuments(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ai.generativelanguage.v1beta.IDocument[], - protos.google.ai.generativelanguage.v1beta.IListDocumentsRequest|null, - protos.google.ai.generativelanguage.v1beta.IListDocumentsResponse - ]) => { - this._log.info('listDocuments values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ai.generativelanguage.v1beta.IDocument[], + protos.google.ai.generativelanguage.v1beta.IListDocumentsRequest | null, + protos.google.ai.generativelanguage.v1beta.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 name of the `Corpus` containing `Document`s. - * Example: `corpora/my-corpus-123` - * @param {number} [request.pageSize] - * Optional. The maximum number of `Document`s to return (per page). - * The service may return fewer `Document`s. - * - * If unspecified, at most 10 `Document`s will be returned. - * The maximum size limit is 20 `Document`s per page. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListDocuments` call. - * - * Provide the `next_page_token` returned in the response as an argument to - * the next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListDocuments` - * must match the call that provided the page token. - * @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.ai.generativelanguage.v1beta.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 name of the `Corpus` containing `Document`s. + * Example: `corpora/my-corpus-123` + * @param {number} [request.pageSize] + * Optional. The maximum number of `Document`s to return (per page). + * The service may return fewer `Document`s. + * + * If unspecified, at most 10 `Document`s will be returned. + * The maximum size limit is 20 `Document`s per page. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListDocuments` call. + * + * Provide the `next_page_token` returned in the response as an argument to + * the next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListDocuments` + * must match the call that provided the page token. + * @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.ai.generativelanguage.v1beta.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.ai.generativelanguage.v1beta.IListDocumentsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ai.generativelanguage.v1beta.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 ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); 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, request, - callSettings + callSettings, ); } -/** - * 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 name of the `Corpus` containing `Document`s. - * Example: `corpora/my-corpus-123` - * @param {number} [request.pageSize] - * Optional. The maximum number of `Document`s to return (per page). - * The service may return fewer `Document`s. - * - * If unspecified, at most 10 `Document`s will be returned. - * The maximum size limit is 20 `Document`s per page. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListDocuments` call. - * - * Provide the `next_page_token` returned in the response as an argument to - * the next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListDocuments` - * must match the call that provided the 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 protos.google.ai.generativelanguage.v1beta.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 include:samples/generated/v1beta/retriever_service.list_documents.js - * region_tag:generativelanguage_v1beta_generated_RetrieverService_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 name of the `Corpus` containing `Document`s. + * Example: `corpora/my-corpus-123` + * @param {number} [request.pageSize] + * Optional. The maximum number of `Document`s to return (per page). + * The service may return fewer `Document`s. + * + * If unspecified, at most 10 `Document`s will be returned. + * The maximum size limit is 20 `Document`s per page. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListDocuments` call. + * + * Provide the `next_page_token` returned in the response as an argument to + * the next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListDocuments` + * must match the call that provided the 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 protos.google.ai.generativelanguage.v1beta.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 include:samples/generated/v1beta/retriever_service.list_documents.js + * region_tag:generativelanguage_v1beta_generated_RetrieverService_ListDocuments_async + */ listDocumentsAsync( - request?: protos.google.ai.generativelanguage.v1beta.IListDocumentsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ai.generativelanguage.v1beta.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 ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); 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, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists all `Chunk`s in a `Document`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the `Document` containing `Chunk`s. - * Example: `corpora/my-corpus-123/documents/the-doc-abc` - * @param {number} [request.pageSize] - * Optional. The maximum number of `Chunk`s to return (per page). - * The service may return fewer `Chunk`s. - * - * If unspecified, at most 10 `Chunk`s will be returned. - * The maximum size limit is 100 `Chunk`s per page. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListChunks` call. - * - * Provide the `next_page_token` returned in the response as an argument to - * the next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListChunks` - * must match the call that provided the page token. - * @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.ai.generativelanguage.v1beta.Chunk|Chunk}. - * 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 `listChunksAsync()` - * 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 `Chunk`s in a `Document`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the `Document` containing `Chunk`s. + * Example: `corpora/my-corpus-123/documents/the-doc-abc` + * @param {number} [request.pageSize] + * Optional. The maximum number of `Chunk`s to return (per page). + * The service may return fewer `Chunk`s. + * + * If unspecified, at most 10 `Chunk`s will be returned. + * The maximum size limit is 100 `Chunk`s per page. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListChunks` call. + * + * Provide the `next_page_token` returned in the response as an argument to + * the next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListChunks` + * must match the call that provided the page token. + * @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.ai.generativelanguage.v1beta.Chunk|Chunk}. + * 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 `listChunksAsync()` + * 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. + */ listChunks( - request?: protos.google.ai.generativelanguage.v1beta.IListChunksRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IChunk[], - protos.google.ai.generativelanguage.v1beta.IListChunksRequest|null, - protos.google.ai.generativelanguage.v1beta.IListChunksResponse - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IListChunksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IChunk[], + protos.google.ai.generativelanguage.v1beta.IListChunksRequest | null, + protos.google.ai.generativelanguage.v1beta.IListChunksResponse, + ] + >; listChunks( - request: protos.google.ai.generativelanguage.v1beta.IListChunksRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListChunksRequest, - protos.google.ai.generativelanguage.v1beta.IListChunksResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IChunk>): void; + request: protos.google.ai.generativelanguage.v1beta.IListChunksRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListChunksRequest, + | protos.google.ai.generativelanguage.v1beta.IListChunksResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IChunk + >, + ): void; listChunks( - request: protos.google.ai.generativelanguage.v1beta.IListChunksRequest, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListChunksRequest, - protos.google.ai.generativelanguage.v1beta.IListChunksResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IChunk>): void; + request: protos.google.ai.generativelanguage.v1beta.IListChunksRequest, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListChunksRequest, + | protos.google.ai.generativelanguage.v1beta.IListChunksResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IChunk + >, + ): void; listChunks( - request?: protos.google.ai.generativelanguage.v1beta.IListChunksRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.ai.generativelanguage.v1beta.IListChunksRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ai.generativelanguage.v1beta.IListChunksRequest, - protos.google.ai.generativelanguage.v1beta.IListChunksResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IChunk>, - callback?: PaginationCallback< - protos.google.ai.generativelanguage.v1beta.IListChunksRequest, - protos.google.ai.generativelanguage.v1beta.IListChunksResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IChunk>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IChunk[], - protos.google.ai.generativelanguage.v1beta.IListChunksRequest|null, - protos.google.ai.generativelanguage.v1beta.IListChunksResponse - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IListChunksResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IChunk + >, + callback?: PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListChunksRequest, + | protos.google.ai.generativelanguage.v1beta.IListChunksResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IChunk + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IChunk[], + protos.google.ai.generativelanguage.v1beta.IListChunksRequest | null, + protos.google.ai.generativelanguage.v1beta.IListChunksResponse, + ] + > | 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.ai.generativelanguage.v1beta.IListChunksRequest, - protos.google.ai.generativelanguage.v1beta.IListChunksResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta.IChunk>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.ai.generativelanguage.v1beta.IListChunksRequest, + | protos.google.ai.generativelanguage.v1beta.IListChunksResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta.IChunk + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listChunks values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -2610,128 +3587,132 @@ export class RetrieverServiceClient { this._log.info('listChunks request %j', request); return this.innerApiCalls .listChunks(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ai.generativelanguage.v1beta.IChunk[], - protos.google.ai.generativelanguage.v1beta.IListChunksRequest|null, - protos.google.ai.generativelanguage.v1beta.IListChunksResponse - ]) => { - this._log.info('listChunks values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ai.generativelanguage.v1beta.IChunk[], + protos.google.ai.generativelanguage.v1beta.IListChunksRequest | null, + protos.google.ai.generativelanguage.v1beta.IListChunksResponse, + ]) => { + this._log.info('listChunks values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listChunks`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the `Document` containing `Chunk`s. - * Example: `corpora/my-corpus-123/documents/the-doc-abc` - * @param {number} [request.pageSize] - * Optional. The maximum number of `Chunk`s to return (per page). - * The service may return fewer `Chunk`s. - * - * If unspecified, at most 10 `Chunk`s will be returned. - * The maximum size limit is 100 `Chunk`s per page. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListChunks` call. - * - * Provide the `next_page_token` returned in the response as an argument to - * the next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListChunks` - * must match the call that provided the page token. - * @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.ai.generativelanguage.v1beta.Chunk|Chunk} 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 `listChunksAsync()` - * 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 `listChunks`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the `Document` containing `Chunk`s. + * Example: `corpora/my-corpus-123/documents/the-doc-abc` + * @param {number} [request.pageSize] + * Optional. The maximum number of `Chunk`s to return (per page). + * The service may return fewer `Chunk`s. + * + * If unspecified, at most 10 `Chunk`s will be returned. + * The maximum size limit is 100 `Chunk`s per page. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListChunks` call. + * + * Provide the `next_page_token` returned in the response as an argument to + * the next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListChunks` + * must match the call that provided the page token. + * @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.ai.generativelanguage.v1beta.Chunk|Chunk} 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 `listChunksAsync()` + * 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. + */ listChunksStream( - request?: protos.google.ai.generativelanguage.v1beta.IListChunksRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ai.generativelanguage.v1beta.IListChunksRequest, + 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['listChunks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listChunks stream %j', request); return this.descriptors.page.listChunks.createStream( this.innerApiCalls.listChunks as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listChunks`, 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 name of the `Document` containing `Chunk`s. - * Example: `corpora/my-corpus-123/documents/the-doc-abc` - * @param {number} [request.pageSize] - * Optional. The maximum number of `Chunk`s to return (per page). - * The service may return fewer `Chunk`s. - * - * If unspecified, at most 10 `Chunk`s will be returned. - * The maximum size limit is 100 `Chunk`s per page. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListChunks` call. - * - * Provide the `next_page_token` returned in the response as an argument to - * the next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListChunks` - * must match the call that provided the 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 protos.google.ai.generativelanguage.v1beta.Chunk|Chunk}. 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 include:samples/generated/v1beta/retriever_service.list_chunks.js - * region_tag:generativelanguage_v1beta_generated_RetrieverService_ListChunks_async - */ + /** + * Equivalent to `listChunks`, 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 name of the `Document` containing `Chunk`s. + * Example: `corpora/my-corpus-123/documents/the-doc-abc` + * @param {number} [request.pageSize] + * Optional. The maximum number of `Chunk`s to return (per page). + * The service may return fewer `Chunk`s. + * + * If unspecified, at most 10 `Chunk`s will be returned. + * The maximum size limit is 100 `Chunk`s per page. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListChunks` call. + * + * Provide the `next_page_token` returned in the response as an argument to + * the next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListChunks` + * must match the call that provided the 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 protos.google.ai.generativelanguage.v1beta.Chunk|Chunk}. 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 include:samples/generated/v1beta/retriever_service.list_chunks.js + * region_tag:generativelanguage_v1beta_generated_RetrieverService_ListChunks_async + */ listChunksAsync( - request?: protos.google.ai.generativelanguage.v1beta.IListChunksRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ai.generativelanguage.v1beta.IListChunksRequest, + 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['listChunks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listChunks iterate %j', request); return this.descriptors.page.listChunks.asyncIterate( this.innerApiCalls['listChunks'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -2744,7 +3725,7 @@ export class RetrieverServiceClient { * @param {string} id * @returns {string} Resource name string. */ - cachedContentPath(id:string) { + cachedContentPath(id: string) { return this.pathTemplates.cachedContentPathTemplate.render({ id: id, }); @@ -2758,7 +3739,8 @@ export class RetrieverServiceClient { * @returns {string} A string representing the id. */ matchIdFromCachedContentName(cachedContentName: string) { - return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName).id; + return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName) + .id; } /** @@ -2769,7 +3751,7 @@ export class RetrieverServiceClient { * @param {string} chunk * @returns {string} Resource name string. */ - chunkPath(corpus:string,document:string,chunk:string) { + chunkPath(corpus: string, document: string, chunk: string) { return this.pathTemplates.chunkPathTemplate.render({ corpus: corpus, document: document, @@ -2816,7 +3798,7 @@ export class RetrieverServiceClient { * @param {string} corpus * @returns {string} Resource name string. */ - corpusPath(corpus:string) { + corpusPath(corpus: string) { return this.pathTemplates.corpusPathTemplate.render({ corpus: corpus, }); @@ -2840,7 +3822,7 @@ export class RetrieverServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - corpusPermissionsPath(corpus:string,permission:string) { + corpusPermissionsPath(corpus: string, permission: string) { return this.pathTemplates.corpusPermissionsPathTemplate.render({ corpus: corpus, permission: permission, @@ -2855,7 +3837,9 @@ export class RetrieverServiceClient { * @returns {string} A string representing the corpus. */ matchCorpusFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).corpus; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).corpus; } /** @@ -2866,7 +3850,9 @@ export class RetrieverServiceClient { * @returns {string} A string representing the permission. */ matchPermissionFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).permission; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).permission; } /** @@ -2876,7 +3862,7 @@ export class RetrieverServiceClient { * @param {string} document * @returns {string} Resource name string. */ - documentPath(corpus:string,document:string) { + documentPath(corpus: string, document: string) { return this.pathTemplates.documentPathTemplate.render({ corpus: corpus, document: document, @@ -2911,7 +3897,7 @@ export class RetrieverServiceClient { * @param {string} file * @returns {string} Resource name string. */ - filePath(file:string) { + filePath(file: string) { return this.pathTemplates.filePathTemplate.render({ file: file, }); @@ -2934,7 +3920,7 @@ export class RetrieverServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -2957,7 +3943,7 @@ export class RetrieverServiceClient { * @param {string} tuned_model * @returns {string} Resource name string. */ - tunedModelPath(tunedModel:string) { + tunedModelPath(tunedModel: string) { return this.pathTemplates.tunedModelPathTemplate.render({ tuned_model: tunedModel, }); @@ -2971,7 +3957,8 @@ export class RetrieverServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromTunedModelName(tunedModelName: string) { - return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName).tuned_model; + return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName) + .tuned_model; } /** @@ -2981,7 +3968,7 @@ export class RetrieverServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - tunedModelPermissionsPath(tunedModel:string,permission:string) { + tunedModelPermissionsPath(tunedModel: string, permission: string) { return this.pathTemplates.tunedModelPermissionsPathTemplate.render({ tuned_model: tunedModel, permission: permission, @@ -2995,8 +3982,12 @@ export class RetrieverServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the tuned_model. */ - matchTunedModelFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).tuned_model; + matchTunedModelFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).tuned_model; } /** @@ -3006,8 +3997,12 @@ export class RetrieverServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the permission. */ - matchPermissionFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).permission; + matchPermissionFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).permission; } /** @@ -3018,7 +4013,7 @@ export class RetrieverServiceClient { */ close(): Promise { if (this.retrieverServiceStub && !this._terminated) { - return this.retrieverServiceStub.then(stub => { + return this.retrieverServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -3026,4 +4021,4 @@ export class RetrieverServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1beta/text_service_client.ts b/packages/google-ai-generativelanguage/src/v1beta/text_service_client.ts index 7b613222a1a9..6ef6a54cfa9c 100644 --- a/packages/google-ai-generativelanguage/src/v1beta/text_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1beta/text_service_client.ts @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +52,7 @@ export class TextServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -60,9 +65,9 @@ export class TextServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - textServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + textServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of TextServiceClient. @@ -103,21 +108,42 @@ export class TextServiceClient { * const client = new TextServiceClient({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 TextServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -142,7 +168,7 @@ export class TextServiceClient { 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; @@ -156,10 +182,7 @@ export class TextServiceClient { } // 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 { @@ -181,38 +204,35 @@ export class TextServiceClient { // Create useful helper objects for these. this.pathTemplates = { cachedContentPathTemplate: new this._gaxModule.PathTemplate( - 'cachedContents/{id}' + 'cachedContents/{id}', ), chunkPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}/chunks/{chunk}' - ), - corpusPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}' + 'corpora/{corpus}/documents/{document}/chunks/{chunk}', ), + corpusPathTemplate: new this._gaxModule.PathTemplate('corpora/{corpus}'), corpusPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/permissions/{permission}' + 'corpora/{corpus}/permissions/{permission}', ), documentPathTemplate: new this._gaxModule.PathTemplate( - 'corpora/{corpus}/documents/{document}' - ), - filePathTemplate: new this._gaxModule.PathTemplate( - 'files/{file}' - ), - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' + 'corpora/{corpus}/documents/{document}', ), + filePathTemplate: new this._gaxModule.PathTemplate('files/{file}'), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), tunedModelPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}' + 'tunedModels/{tuned_model}', ), tunedModelPermissionsPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}/permissions/{permission}' + 'tunedModels/{tuned_model}/permissions/{permission}', ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1beta.TextService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1beta.TextService', + 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 @@ -243,36 +263,45 @@ export class TextServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1beta.TextService. this.textServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1beta.TextService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1beta.TextService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.ai.generativelanguage.v1beta.TextService, - 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 textServiceStubMethods = - ['generateText', 'embedText', 'batchEmbedText', 'countTextTokens']; + const textServiceStubMethods = [ + 'generateText', + 'embedText', + 'batchEmbedText', + 'countTextTokens', + ]; for (const methodName of textServiceStubMethods) { const callPromise = this.textServiceStub.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 = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -287,8 +316,14 @@ export class TextServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -299,8 +334,14 @@ export class TextServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -340,8 +381,9 @@ export class TextServiceClient { * 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; @@ -352,468 +394,658 @@ export class TextServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Generates a response from the model given an input message. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The name of the `Model` or `TunedModel` to use for generating the - * completion. - * Examples: - * models/text-bison-001 - * tunedModels/sentence-translator-u3b7m - * @param {google.ai.generativelanguage.v1beta.TextPrompt} request.prompt - * Required. The free-form input text given to the model as a prompt. - * - * Given a prompt, the model will generate a TextCompletion response it - * predicts as the completion of the input text. - * @param {number} [request.temperature] - * Optional. Controls the randomness of the output. - * Note: The default value varies by model, see the `Model.temperature` - * attribute of the `Model` returned the `getModel` function. - * - * Values can range from [0.0,1.0], - * inclusive. A value closer to 1.0 will produce responses that are more - * varied and creative, while a value closer to 0.0 will typically result in - * more straightforward responses from the model. - * @param {number} [request.candidateCount] - * Optional. Number of generated responses to return. - * - * This value must be between [1, 8], inclusive. If unset, this will default - * to 1. - * @param {number} [request.maxOutputTokens] - * Optional. The maximum number of tokens to include in a candidate. - * - * If unset, this will default to output_token_limit specified in the `Model` - * specification. - * @param {number} [request.topP] - * Optional. The maximum cumulative probability of tokens to consider when - * sampling. - * - * The model uses combined Top-k and nucleus sampling. - * - * Tokens are sorted based on their assigned probabilities so that only the - * most likely tokens are considered. Top-k sampling directly limits the - * maximum number of tokens to consider, while Nucleus sampling limits number - * of tokens based on the cumulative probability. - * - * Note: The default value varies by model, see the `Model.top_p` - * attribute of the `Model` returned the `getModel` function. - * @param {number} [request.topK] - * Optional. The maximum number of tokens to consider when sampling. - * - * The model uses combined Top-k and nucleus sampling. - * - * Top-k sampling considers the set of `top_k` most probable tokens. - * Defaults to 40. - * - * Note: The default value varies by model, see the `Model.top_k` - * attribute of the `Model` returned the `getModel` function. - * @param {number[]} [request.safetySettings] - * Optional. A list of unique `SafetySetting` instances for blocking unsafe - * content. - * - * that will be enforced on the `GenerateTextRequest.prompt` and - * `GenerateTextResponse.candidates`. There should not be more than one - * setting for each `SafetyCategory` type. The API will block any prompts and - * responses that fail to meet the thresholds set by these settings. This list - * overrides the default settings for each `SafetyCategory` specified in the - * safety_settings. If there is no `SafetySetting` for a given - * `SafetyCategory` provided in the list, the API will use the default safety - * setting for that category. Harm categories HARM_CATEGORY_DEROGATORY, - * HARM_CATEGORY_TOXICITY, HARM_CATEGORY_VIOLENCE, HARM_CATEGORY_SEXUAL, - * HARM_CATEGORY_MEDICAL, HARM_CATEGORY_DANGEROUS are supported in text - * service. - * @param {string[]} request.stopSequences - * The set of character sequences (up to 5) that will stop output generation. - * If specified, the API will stop at the first appearance of a stop - * sequence. The stop sequence will not be included as part of 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.ai.generativelanguage.v1beta.GenerateTextResponse|GenerateTextResponse}. - * 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/v1beta/text_service.generate_text.js - * region_tag:generativelanguage_v1beta_generated_TextService_GenerateText_async - */ + /** + * Generates a response from the model given an input message. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The name of the `Model` or `TunedModel` to use for generating the + * completion. + * Examples: + * models/text-bison-001 + * tunedModels/sentence-translator-u3b7m + * @param {google.ai.generativelanguage.v1beta.TextPrompt} request.prompt + * Required. The free-form input text given to the model as a prompt. + * + * Given a prompt, the model will generate a TextCompletion response it + * predicts as the completion of the input text. + * @param {number} [request.temperature] + * Optional. Controls the randomness of the output. + * Note: The default value varies by model, see the `Model.temperature` + * attribute of the `Model` returned the `getModel` function. + * + * Values can range from [0.0,1.0], + * inclusive. A value closer to 1.0 will produce responses that are more + * varied and creative, while a value closer to 0.0 will typically result in + * more straightforward responses from the model. + * @param {number} [request.candidateCount] + * Optional. Number of generated responses to return. + * + * This value must be between [1, 8], inclusive. If unset, this will default + * to 1. + * @param {number} [request.maxOutputTokens] + * Optional. The maximum number of tokens to include in a candidate. + * + * If unset, this will default to output_token_limit specified in the `Model` + * specification. + * @param {number} [request.topP] + * Optional. The maximum cumulative probability of tokens to consider when + * sampling. + * + * The model uses combined Top-k and nucleus sampling. + * + * Tokens are sorted based on their assigned probabilities so that only the + * most likely tokens are considered. Top-k sampling directly limits the + * maximum number of tokens to consider, while Nucleus sampling limits number + * of tokens based on the cumulative probability. + * + * Note: The default value varies by model, see the `Model.top_p` + * attribute of the `Model` returned the `getModel` function. + * @param {number} [request.topK] + * Optional. The maximum number of tokens to consider when sampling. + * + * The model uses combined Top-k and nucleus sampling. + * + * Top-k sampling considers the set of `top_k` most probable tokens. + * Defaults to 40. + * + * Note: The default value varies by model, see the `Model.top_k` + * attribute of the `Model` returned the `getModel` function. + * @param {number[]} [request.safetySettings] + * Optional. A list of unique `SafetySetting` instances for blocking unsafe + * content. + * + * that will be enforced on the `GenerateTextRequest.prompt` and + * `GenerateTextResponse.candidates`. There should not be more than one + * setting for each `SafetyCategory` type. The API will block any prompts and + * responses that fail to meet the thresholds set by these settings. This list + * overrides the default settings for each `SafetyCategory` specified in the + * safety_settings. If there is no `SafetySetting` for a given + * `SafetyCategory` provided in the list, the API will use the default safety + * setting for that category. Harm categories HARM_CATEGORY_DEROGATORY, + * HARM_CATEGORY_TOXICITY, HARM_CATEGORY_VIOLENCE, HARM_CATEGORY_SEXUAL, + * HARM_CATEGORY_MEDICAL, HARM_CATEGORY_DANGEROUS are supported in text + * service. + * @param {string[]} request.stopSequences + * The set of character sequences (up to 5) that will stop output generation. + * If specified, the API will stop at the first appearance of a stop + * sequence. The stop sequence will not be included as part of 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.ai.generativelanguage.v1beta.GenerateTextResponse|GenerateTextResponse}. + * 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/v1beta/text_service.generate_text.js + * region_tag:generativelanguage_v1beta_generated_TextService_GenerateText_async + */ generateText( - request?: protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IGenerateTextResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest + | undefined + ), + {} | undefined, + ] + >; generateText( - request: protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IGenerateTextResponse, + | protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateText( - request: protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IGenerateTextResponse, + | protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateText( - request?: protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IGenerateTextResponse, + | protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IGenerateTextResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('generateText request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IGenerateTextResponse, + | protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('generateText response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.generateText(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest|undefined, - {}|undefined - ]) => { - this._log.info('generateText response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .generateText(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IGenerateTextResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IGenerateTextRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('generateText response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Generates an embedding from the model given an input message. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The model name to use with the format model=models/{model}. - * @param {string} [request.text] - * Optional. The free-form input text that the model will turn into an - * embedding. - * @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.ai.generativelanguage.v1beta.EmbedTextResponse|EmbedTextResponse}. - * 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/v1beta/text_service.embed_text.js - * region_tag:generativelanguage_v1beta_generated_TextService_EmbedText_async - */ + /** + * Generates an embedding from the model given an input message. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The model name to use with the format model=models/{model}. + * @param {string} [request.text] + * Optional. The free-form input text that the model will turn into an + * embedding. + * @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.ai.generativelanguage.v1beta.EmbedTextResponse|EmbedTextResponse}. + * 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/v1beta/text_service.embed_text.js + * region_tag:generativelanguage_v1beta_generated_TextService_EmbedText_async + */ embedText( - request?: protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IEmbedTextResponse, + protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest | undefined, + {} | undefined, + ] + >; embedText( - request: protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IEmbedTextResponse, + | protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; embedText( - request: protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IEmbedTextResponse, + | protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; embedText( - request?: protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IEmbedTextResponse, + | protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IEmbedTextResponse, + protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('embedText request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IEmbedTextResponse, + | protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('embedText response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.embedText(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest|undefined, - {}|undefined - ]) => { - this._log.info('embedText response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .embedText(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IEmbedTextResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IEmbedTextRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('embedText response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Generates multiple embeddings from the model given input text in a - * synchronous call. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The name of the `Model` to use for generating the embedding. - * Examples: - * models/embedding-gecko-001 - * @param {string[]} [request.texts] - * Optional. The free-form input texts that the model will turn into an - * embedding. The current limit is 100 texts, over which an error will be - * thrown. - * @param {number[]} [request.requests] - * Optional. Embed requests for the batch. Only one of `texts` or `requests` - * can be set. - * @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.ai.generativelanguage.v1beta.BatchEmbedTextResponse|BatchEmbedTextResponse}. - * 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/v1beta/text_service.batch_embed_text.js - * region_tag:generativelanguage_v1beta_generated_TextService_BatchEmbedText_async - */ + /** + * Generates multiple embeddings from the model given input text in a + * synchronous call. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The name of the `Model` to use for generating the embedding. + * Examples: + * models/embedding-gecko-001 + * @param {string[]} [request.texts] + * Optional. The free-form input texts that the model will turn into an + * embedding. The current limit is 100 texts, over which an error will be + * thrown. + * @param {number[]} [request.requests] + * Optional. Embed requests for the batch. Only one of `texts` or `requests` + * can be set. + * @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.ai.generativelanguage.v1beta.BatchEmbedTextResponse|BatchEmbedTextResponse}. + * 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/v1beta/text_service.batch_embed_text.js + * region_tag:generativelanguage_v1beta_generated_TextService_BatchEmbedText_async + */ batchEmbedText( - request?: protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest + | undefined + ), + {} | undefined, + ] + >; batchEmbedText( - request: protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextResponse, + | protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchEmbedText( - request: protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextResponse, + | protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchEmbedText( - request?: protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextResponse, + | protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('batchEmbedText request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextResponse, + | protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchEmbedText response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.batchEmbedText(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest|undefined, - {}|undefined - ]) => { - this._log.info('batchEmbedText response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchEmbedText(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextResponse, + ( + | protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchEmbedText response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Runs a model's tokenizer on a text and returns the token count. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The model's resource name. This serves as an ID for the Model to - * use. - * - * This name should match a model name returned by the `ListModels` method. - * - * Format: `models/{model}` - * @param {google.ai.generativelanguage.v1beta.TextPrompt} request.prompt - * Required. The free-form input text given to the model as a prompt. - * @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.ai.generativelanguage.v1beta.CountTextTokensResponse|CountTextTokensResponse}. - * 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/v1beta/text_service.count_text_tokens.js - * region_tag:generativelanguage_v1beta_generated_TextService_CountTextTokens_async - */ + /** + * Runs a model's tokenizer on a text and returns the token count. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The model's resource name. This serves as an ID for the Model to + * use. + * + * This name should match a model name returned by the `ListModels` method. + * + * Format: `models/{model}` + * @param {google.ai.generativelanguage.v1beta.TextPrompt} request.prompt + * Required. The free-form input text given to the model as a prompt. + * @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.ai.generativelanguage.v1beta.CountTextTokensResponse|CountTextTokensResponse}. + * 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/v1beta/text_service.count_text_tokens.js + * region_tag:generativelanguage_v1beta_generated_TextService_CountTextTokens_async + */ countTextTokens( - request?: protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICountTextTokensResponse, + ( + | protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest + | undefined + ), + {} | undefined, + ] + >; countTextTokens( - request: protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ICountTextTokensResponse, + | protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): void; countTextTokens( - request: protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta.ICountTextTokensResponse, + | protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): void; countTextTokens( - request?: protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1beta.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta.ICountTextTokensResponse, + | protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta.ICountTextTokensResponse, + ( + | protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('countTextTokens request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta.ICountTextTokensResponse, + | protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('countTextTokens response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.countTextTokens(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest|undefined, - {}|undefined - ]) => { - this._log.info('countTextTokens response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .countTextTokens(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta.ICountTextTokensResponse, + ( + | protos.google.ai.generativelanguage.v1beta.ICountTextTokensRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('countTextTokens response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -829,7 +1061,7 @@ export class TextServiceClient { * @param {string} id * @returns {string} Resource name string. */ - cachedContentPath(id:string) { + cachedContentPath(id: string) { return this.pathTemplates.cachedContentPathTemplate.render({ id: id, }); @@ -843,7 +1075,8 @@ export class TextServiceClient { * @returns {string} A string representing the id. */ matchIdFromCachedContentName(cachedContentName: string) { - return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName).id; + return this.pathTemplates.cachedContentPathTemplate.match(cachedContentName) + .id; } /** @@ -854,7 +1087,7 @@ export class TextServiceClient { * @param {string} chunk * @returns {string} Resource name string. */ - chunkPath(corpus:string,document:string,chunk:string) { + chunkPath(corpus: string, document: string, chunk: string) { return this.pathTemplates.chunkPathTemplate.render({ corpus: corpus, document: document, @@ -901,7 +1134,7 @@ export class TextServiceClient { * @param {string} corpus * @returns {string} Resource name string. */ - corpusPath(corpus:string) { + corpusPath(corpus: string) { return this.pathTemplates.corpusPathTemplate.render({ corpus: corpus, }); @@ -925,7 +1158,7 @@ export class TextServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - corpusPermissionsPath(corpus:string,permission:string) { + corpusPermissionsPath(corpus: string, permission: string) { return this.pathTemplates.corpusPermissionsPathTemplate.render({ corpus: corpus, permission: permission, @@ -940,7 +1173,9 @@ export class TextServiceClient { * @returns {string} A string representing the corpus. */ matchCorpusFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).corpus; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).corpus; } /** @@ -951,7 +1186,9 @@ export class TextServiceClient { * @returns {string} A string representing the permission. */ matchPermissionFromCorpusPermissionsName(corpusPermissionsName: string) { - return this.pathTemplates.corpusPermissionsPathTemplate.match(corpusPermissionsName).permission; + return this.pathTemplates.corpusPermissionsPathTemplate.match( + corpusPermissionsName, + ).permission; } /** @@ -961,7 +1198,7 @@ export class TextServiceClient { * @param {string} document * @returns {string} Resource name string. */ - documentPath(corpus:string,document:string) { + documentPath(corpus: string, document: string) { return this.pathTemplates.documentPathTemplate.render({ corpus: corpus, document: document, @@ -996,7 +1233,7 @@ export class TextServiceClient { * @param {string} file * @returns {string} Resource name string. */ - filePath(file:string) { + filePath(file: string) { return this.pathTemplates.filePathTemplate.render({ file: file, }); @@ -1019,7 +1256,7 @@ export class TextServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -1042,7 +1279,7 @@ export class TextServiceClient { * @param {string} tuned_model * @returns {string} Resource name string. */ - tunedModelPath(tunedModel:string) { + tunedModelPath(tunedModel: string) { return this.pathTemplates.tunedModelPathTemplate.render({ tuned_model: tunedModel, }); @@ -1056,7 +1293,8 @@ export class TextServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromTunedModelName(tunedModelName: string) { - return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName).tuned_model; + return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName) + .tuned_model; } /** @@ -1066,7 +1304,7 @@ export class TextServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - tunedModelPermissionsPath(tunedModel:string,permission:string) { + tunedModelPermissionsPath(tunedModel: string, permission: string) { return this.pathTemplates.tunedModelPermissionsPathTemplate.render({ tuned_model: tunedModel, permission: permission, @@ -1080,8 +1318,12 @@ export class TextServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the tuned_model. */ - matchTunedModelFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).tuned_model; + matchTunedModelFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).tuned_model; } /** @@ -1091,8 +1333,12 @@ export class TextServiceClient { * A fully-qualified path representing tuned_model_permissions resource. * @returns {string} A string representing the permission. */ - matchPermissionFromTunedModelPermissionsName(tunedModelPermissionsName: string) { - return this.pathTemplates.tunedModelPermissionsPathTemplate.match(tunedModelPermissionsName).permission; + matchPermissionFromTunedModelPermissionsName( + tunedModelPermissionsName: string, + ) { + return this.pathTemplates.tunedModelPermissionsPathTemplate.match( + tunedModelPermissionsName, + ).permission; } /** @@ -1103,7 +1349,7 @@ export class TextServiceClient { */ close(): Promise { if (this.textServiceStub && !this._terminated) { - return this.textServiceStub.then(stub => { + return this.textServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1111,4 +1357,4 @@ export class TextServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1beta2/discuss_service_client.ts b/packages/google-ai-generativelanguage/src/v1beta2/discuss_service_client.ts index 28765ba65b66..08c226007119 100644 --- a/packages/google-ai-generativelanguage/src/v1beta2/discuss_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1beta2/discuss_service_client.ts @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +52,7 @@ export class DiscussServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -60,9 +65,9 @@ export class DiscussServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - discussServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + discussServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of DiscussServiceClient. @@ -103,21 +108,42 @@ export class DiscussServiceClient { * const client = new DiscussServiceClient({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 DiscussServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -142,7 +168,7 @@ export class DiscussServiceClient { 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; @@ -156,10 +182,7 @@ export class DiscussServiceClient { } // 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 { @@ -180,15 +203,16 @@ export class DiscussServiceClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' - ), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1beta2.DiscussService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1beta2.DiscussService', + 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 @@ -219,36 +243,41 @@ export class DiscussServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1beta2.DiscussService. this.discussServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1beta2.DiscussService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1beta2.DiscussService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1beta2.DiscussService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1beta2 + .DiscussService, + 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 discussServiceStubMethods = - ['generateMessage', 'countMessageTokens']; + const discussServiceStubMethods = ['generateMessage', 'countMessageTokens']; for (const methodName of discussServiceStubMethods) { const callPromise = this.discussServiceStub.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 = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -263,8 +292,14 @@ export class DiscussServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -275,8 +310,14 @@ export class DiscussServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -316,8 +357,9 @@ export class DiscussServiceClient { * 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; @@ -328,231 +370,329 @@ export class DiscussServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Generates a response from the model given an input `MessagePrompt`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The name of the model to use. - * - * Format: `name=models/{model}`. - * @param {google.ai.generativelanguage.v1beta2.MessagePrompt} request.prompt - * Required. The structured textual input given to the model as a prompt. - * - * Given a - * prompt, the model will return what it predicts is the next message in the - * discussion. - * @param {number} [request.temperature] - * Optional. Controls the randomness of the output. - * - * Values can range over `[0.0,1.0]`, - * inclusive. A value closer to `1.0` will produce responses that are more - * varied, while a value closer to `0.0` will typically result in - * less surprising responses from the model. - * @param {number} [request.candidateCount] - * Optional. The number of generated response messages to return. - * - * This value must be between - * `[1, 8]`, inclusive. If unset, this will default to `1`. - * @param {number} [request.topP] - * Optional. The maximum cumulative probability of tokens to consider when - * sampling. - * - * The model uses combined Top-k and nucleus sampling. - * - * Nucleus sampling considers the smallest set of tokens whose probability - * sum is at least `top_p`. - * @param {number} [request.topK] - * Optional. The maximum number of tokens to consider when sampling. - * - * The model uses combined Top-k and nucleus sampling. - * - * Top-k sampling considers the set of `top_k` most probable tokens. - * @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.ai.generativelanguage.v1beta2.GenerateMessageResponse|GenerateMessageResponse}. - * 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/v1beta2/discuss_service.generate_message.js - * region_tag:generativelanguage_v1beta2_generated_DiscussService_GenerateMessage_async - */ + /** + * Generates a response from the model given an input `MessagePrompt`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The name of the model to use. + * + * Format: `name=models/{model}`. + * @param {google.ai.generativelanguage.v1beta2.MessagePrompt} request.prompt + * Required. The structured textual input given to the model as a prompt. + * + * Given a + * prompt, the model will return what it predicts is the next message in the + * discussion. + * @param {number} [request.temperature] + * Optional. Controls the randomness of the output. + * + * Values can range over `[0.0,1.0]`, + * inclusive. A value closer to `1.0` will produce responses that are more + * varied, while a value closer to `0.0` will typically result in + * less surprising responses from the model. + * @param {number} [request.candidateCount] + * Optional. The number of generated response messages to return. + * + * This value must be between + * `[1, 8]`, inclusive. If unset, this will default to `1`. + * @param {number} [request.topP] + * Optional. The maximum cumulative probability of tokens to consider when + * sampling. + * + * The model uses combined Top-k and nucleus sampling. + * + * Nucleus sampling considers the smallest set of tokens whose probability + * sum is at least `top_p`. + * @param {number} [request.topK] + * Optional. The maximum number of tokens to consider when sampling. + * + * The model uses combined Top-k and nucleus sampling. + * + * Top-k sampling considers the set of `top_k` most probable tokens. + * @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.ai.generativelanguage.v1beta2.GenerateMessageResponse|GenerateMessageResponse}. + * 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/v1beta2/discuss_service.generate_message.js + * region_tag:generativelanguage_v1beta2_generated_DiscussService_GenerateMessage_async + */ generateMessage( - request?: protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta2.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta2.IGenerateMessageResponse, + ( + | protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest + | undefined + ), + {} | undefined, + ] + >; generateMessage( - request: protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta2.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta2.IGenerateMessageResponse, + | protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateMessage( - request: protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta2.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta2.IGenerateMessageResponse, + | protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateMessage( - request?: protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta2.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1beta2.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta2.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta2.IGenerateMessageResponse, + | protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta2.IGenerateMessageResponse, + ( + | protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('generateMessage request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta2.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta2.IGenerateMessageResponse, + | protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('generateMessage response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.generateMessage(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta2.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest|undefined, - {}|undefined - ]) => { - this._log.info('generateMessage response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .generateMessage(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta2.IGenerateMessageResponse, + ( + | protos.google.ai.generativelanguage.v1beta2.IGenerateMessageRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('generateMessage response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Runs a model's tokenizer on a string and returns the token count. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The model's resource name. This serves as an ID for the Model to - * use. - * - * This name should match a model name returned by the `ListModels` method. - * - * Format: `models/{model}` - * @param {google.ai.generativelanguage.v1beta2.MessagePrompt} request.prompt - * Required. The prompt, whose token count is to 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 {@link protos.google.ai.generativelanguage.v1beta2.CountMessageTokensResponse|CountMessageTokensResponse}. - * 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/v1beta2/discuss_service.count_message_tokens.js - * region_tag:generativelanguage_v1beta2_generated_DiscussService_CountMessageTokens_async - */ + /** + * Runs a model's tokenizer on a string and returns the token count. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The model's resource name. This serves as an ID for the Model to + * use. + * + * This name should match a model name returned by the `ListModels` method. + * + * Format: `models/{model}` + * @param {google.ai.generativelanguage.v1beta2.MessagePrompt} request.prompt + * Required. The prompt, whose token count is to 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 {@link protos.google.ai.generativelanguage.v1beta2.CountMessageTokensResponse|CountMessageTokensResponse}. + * 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/v1beta2/discuss_service.count_message_tokens.js + * region_tag:generativelanguage_v1beta2_generated_DiscussService_CountMessageTokens_async + */ countMessageTokens( - request?: protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensResponse, + ( + | protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest + | undefined + ), + {} | undefined, + ] + >; countMessageTokens( - request: protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensResponse, + | protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): void; countMessageTokens( - request: protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensResponse, + | protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): void; countMessageTokens( - request?: protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensResponse, + | protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensResponse, + ( + | protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('countMessageTokens request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensResponse, + | protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('countMessageTokens response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.countMessageTokens(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest|undefined, - {}|undefined - ]) => { - this._log.info('countMessageTokens response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .countMessageTokens(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensResponse, + ( + | protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('countMessageTokens response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -568,7 +708,7 @@ export class DiscussServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -593,7 +733,7 @@ export class DiscussServiceClient { */ close(): Promise { if (this.discussServiceStub && !this._terminated) { - return this.discussServiceStub.then(stub => { + return this.discussServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -601,4 +741,4 @@ export class DiscussServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1beta2/index.ts b/packages/google-ai-generativelanguage/src/v1beta2/index.ts index 5ca4d25c9c2b..6843433cd51b 100644 --- a/packages/google-ai-generativelanguage/src/v1beta2/index.ts +++ b/packages/google-ai-generativelanguage/src/v1beta2/index.ts @@ -16,6 +16,6 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {DiscussServiceClient} from './discuss_service_client'; -export {ModelServiceClient} from './model_service_client'; -export {TextServiceClient} from './text_service_client'; +export { DiscussServiceClient } from './discuss_service_client'; +export { ModelServiceClient } from './model_service_client'; +export { TextServiceClient } from './text_service_client'; diff --git a/packages/google-ai-generativelanguage/src/v1beta2/model_service_client.ts b/packages/google-ai-generativelanguage/src/v1beta2/model_service_client.ts index 628505ec4564..45f78f09f5cd 100644 --- a/packages/google-ai-generativelanguage/src/v1beta2/model_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1beta2/model_service_client.ts @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class ModelServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -57,9 +64,9 @@ export class ModelServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - modelServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + modelServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ModelServiceClient. @@ -100,21 +107,42 @@ export class ModelServiceClient { * const client = new ModelServiceClient({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 ModelServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -139,7 +167,7 @@ export class ModelServiceClient { 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; @@ -153,10 +181,7 @@ export class ModelServiceClient { } // 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 { @@ -177,23 +202,27 @@ export class ModelServiceClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' - ), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), }; // 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 = { - listModels: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'models') + listModels: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'models', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1beta2.ModelService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1beta2.ModelService', + 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 @@ -224,37 +253,41 @@ export class ModelServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1beta2.ModelService. this.modelServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1beta2.ModelService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1beta2.ModelService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1beta2.ModelService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1beta2 + .ModelService, + 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 modelServiceStubMethods = - ['getModel', 'listModels']; + const modelServiceStubMethods = ['getModel', 'listModels']; for (const methodName of modelServiceStubMethods) { const callPromise = this.modelServiceStub.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] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -269,8 +302,14 @@ export class ModelServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -281,8 +320,14 @@ export class ModelServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -322,8 +367,9 @@ export class ModelServiceClient { * 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; @@ -334,190 +380,259 @@ export class ModelServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets information about a specific Model. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the model. - * - * This name should match a model name returned by the `ListModels` method. - * - * Format: `models/{model}` - * @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.ai.generativelanguage.v1beta2.Model|Model}. - * 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/v1beta2/model_service.get_model.js - * region_tag:generativelanguage_v1beta2_generated_ModelService_GetModel_async - */ + /** + * Gets information about a specific Model. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the model. + * + * This name should match a model name returned by the `ListModels` method. + * + * Format: `models/{model}` + * @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.ai.generativelanguage.v1beta2.Model|Model}. + * 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/v1beta2/model_service.get_model.js + * region_tag:generativelanguage_v1beta2_generated_ModelService_GetModel_async + */ getModel( - request?: protos.google.ai.generativelanguage.v1beta2.IGetModelRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta2.IModel, - protos.google.ai.generativelanguage.v1beta2.IGetModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta2.IGetModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta2.IModel, + protos.google.ai.generativelanguage.v1beta2.IGetModelRequest | undefined, + {} | undefined, + ] + >; getModel( - request: protos.google.ai.generativelanguage.v1beta2.IGetModelRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta2.IModel, - protos.google.ai.generativelanguage.v1beta2.IGetModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta2.IGetModelRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta2.IModel, + | protos.google.ai.generativelanguage.v1beta2.IGetModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getModel( - request: protos.google.ai.generativelanguage.v1beta2.IGetModelRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta2.IModel, - protos.google.ai.generativelanguage.v1beta2.IGetModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta2.IGetModelRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta2.IModel, + | protos.google.ai.generativelanguage.v1beta2.IGetModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getModel( - request?: protos.google.ai.generativelanguage.v1beta2.IGetModelRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta2.IGetModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta2.IModel, - protos.google.ai.generativelanguage.v1beta2.IGetModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1beta2.IModel, - protos.google.ai.generativelanguage.v1beta2.IGetModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta2.IModel, - protos.google.ai.generativelanguage.v1beta2.IGetModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta2.IGetModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta2.IModel, + | protos.google.ai.generativelanguage.v1beta2.IGetModelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta2.IModel, + protos.google.ai.generativelanguage.v1beta2.IGetModelRequest | 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('getModel request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta2.IModel, - protos.google.ai.generativelanguage.v1beta2.IGetModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta2.IModel, + | protos.google.ai.generativelanguage.v1beta2.IGetModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getModel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta2.IModel, - protos.google.ai.generativelanguage.v1beta2.IGetModelRequest|undefined, - {}|undefined - ]) => { - this._log.info('getModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta2.IModel, + ( + | protos.google.ai.generativelanguage.v1beta2.IGetModelRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists models available through the API. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of `Models` to return (per page). - * - * The service may return fewer models. - * If unspecified, at most 50 models will be returned per page. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} request.pageToken - * A page token, received from a previous `ListModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListModels` must match - * the call that provided the page token. - * @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.ai.generativelanguage.v1beta2.Model|Model}. - * 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 `listModelsAsync()` - * 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 models available through the API. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of `Models` to return (per page). + * + * The service may return fewer models. + * If unspecified, at most 50 models will be returned per page. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} request.pageToken + * A page token, received from a previous `ListModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListModels` must match + * the call that provided the page token. + * @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.ai.generativelanguage.v1beta2.Model|Model}. + * 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 `listModelsAsync()` + * 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. + */ listModels( - request?: protos.google.ai.generativelanguage.v1beta2.IListModelsRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta2.IModel[], - protos.google.ai.generativelanguage.v1beta2.IListModelsRequest|null, - protos.google.ai.generativelanguage.v1beta2.IListModelsResponse - ]>; + request?: protos.google.ai.generativelanguage.v1beta2.IListModelsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta2.IModel[], + protos.google.ai.generativelanguage.v1beta2.IListModelsRequest | null, + protos.google.ai.generativelanguage.v1beta2.IListModelsResponse, + ] + >; listModels( - request: protos.google.ai.generativelanguage.v1beta2.IListModelsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta2.IListModelsRequest, - protos.google.ai.generativelanguage.v1beta2.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta2.IModel>): void; + request: protos.google.ai.generativelanguage.v1beta2.IListModelsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta2.IListModelsRequest, + | protos.google.ai.generativelanguage.v1beta2.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta2.IModel + >, + ): void; listModels( - request: protos.google.ai.generativelanguage.v1beta2.IListModelsRequest, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta2.IListModelsRequest, - protos.google.ai.generativelanguage.v1beta2.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta2.IModel>): void; + request: protos.google.ai.generativelanguage.v1beta2.IListModelsRequest, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta2.IListModelsRequest, + | protos.google.ai.generativelanguage.v1beta2.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta2.IModel + >, + ): void; listModels( - request?: protos.google.ai.generativelanguage.v1beta2.IListModelsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.ai.generativelanguage.v1beta2.IListModelsRequest, - protos.google.ai.generativelanguage.v1beta2.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta2.IModel>, - callback?: PaginationCallback< + request?: protos.google.ai.generativelanguage.v1beta2.IListModelsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ai.generativelanguage.v1beta2.IListModelsRequest, - protos.google.ai.generativelanguage.v1beta2.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta2.IModel>): - Promise<[ - protos.google.ai.generativelanguage.v1beta2.IModel[], - protos.google.ai.generativelanguage.v1beta2.IListModelsRequest|null, - protos.google.ai.generativelanguage.v1beta2.IListModelsResponse - ]>|void { + | protos.google.ai.generativelanguage.v1beta2.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta2.IModel + >, + callback?: PaginationCallback< + protos.google.ai.generativelanguage.v1beta2.IListModelsRequest, + | protos.google.ai.generativelanguage.v1beta2.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta2.IModel + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta2.IModel[], + protos.google.ai.generativelanguage.v1beta2.IListModelsRequest | null, + protos.google.ai.generativelanguage.v1beta2.IListModelsResponse, + ] + > | 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 || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta2.IListModelsRequest, - protos.google.ai.generativelanguage.v1beta2.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta2.IModel>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.ai.generativelanguage.v1beta2.IListModelsRequest, + | protos.google.ai.generativelanguage.v1beta2.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta2.IModel + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listModels values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -526,114 +641,120 @@ export class ModelServiceClient { this._log.info('listModels request %j', request); return this.innerApiCalls .listModels(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ai.generativelanguage.v1beta2.IModel[], - protos.google.ai.generativelanguage.v1beta2.IListModelsRequest|null, - protos.google.ai.generativelanguage.v1beta2.IListModelsResponse - ]) => { - this._log.info('listModels values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ai.generativelanguage.v1beta2.IModel[], + protos.google.ai.generativelanguage.v1beta2.IListModelsRequest | null, + protos.google.ai.generativelanguage.v1beta2.IListModelsResponse, + ]) => { + this._log.info('listModels values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listModels`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of `Models` to return (per page). - * - * The service may return fewer models. - * If unspecified, at most 50 models will be returned per page. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} request.pageToken - * A page token, received from a previous `ListModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListModels` must match - * the call that provided the page token. - * @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.ai.generativelanguage.v1beta2.Model|Model} 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 `listModelsAsync()` - * 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 `listModels`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of `Models` to return (per page). + * + * The service may return fewer models. + * If unspecified, at most 50 models will be returned per page. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} request.pageToken + * A page token, received from a previous `ListModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListModels` must match + * the call that provided the page token. + * @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.ai.generativelanguage.v1beta2.Model|Model} 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 `listModelsAsync()` + * 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. + */ listModelsStream( - request?: protos.google.ai.generativelanguage.v1beta2.IListModelsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ai.generativelanguage.v1beta2.IListModelsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listModels stream %j', request); return this.descriptors.page.listModels.createStream( this.innerApiCalls.listModels as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listModels`, 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 {number} request.pageSize - * The maximum number of `Models` to return (per page). - * - * The service may return fewer models. - * If unspecified, at most 50 models will be returned per page. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} request.pageToken - * A page token, received from a previous `ListModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListModels` must match - * the call that provided the 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 protos.google.ai.generativelanguage.v1beta2.Model|Model}. 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 include:samples/generated/v1beta2/model_service.list_models.js - * region_tag:generativelanguage_v1beta2_generated_ModelService_ListModels_async - */ + /** + * Equivalent to `listModels`, 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 {number} request.pageSize + * The maximum number of `Models` to return (per page). + * + * The service may return fewer models. + * If unspecified, at most 50 models will be returned per page. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} request.pageToken + * A page token, received from a previous `ListModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListModels` must match + * the call that provided the 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 protos.google.ai.generativelanguage.v1beta2.Model|Model}. 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 include:samples/generated/v1beta2/model_service.list_models.js + * region_tag:generativelanguage_v1beta2_generated_ModelService_ListModels_async + */ listModelsAsync( - request?: protos.google.ai.generativelanguage.v1beta2.IListModelsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ai.generativelanguage.v1beta2.IListModelsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listModels iterate %j', request); return this.descriptors.page.listModels.asyncIterate( this.innerApiCalls['listModels'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -646,7 +767,7 @@ export class ModelServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -671,7 +792,7 @@ export class ModelServiceClient { */ close(): Promise { if (this.modelServiceStub && !this._terminated) { - return this.modelServiceStub.then(stub => { + return this.modelServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -679,4 +800,4 @@ export class ModelServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1beta2/text_service_client.ts b/packages/google-ai-generativelanguage/src/v1beta2/text_service_client.ts index efacaaab2646..113019a0b201 100644 --- a/packages/google-ai-generativelanguage/src/v1beta2/text_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1beta2/text_service_client.ts @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +52,7 @@ export class TextServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -60,9 +65,9 @@ export class TextServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - textServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + textServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of TextServiceClient. @@ -103,21 +108,42 @@ export class TextServiceClient { * const client = new TextServiceClient({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 TextServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -142,7 +168,7 @@ export class TextServiceClient { 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; @@ -156,10 +182,7 @@ export class TextServiceClient { } // 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 { @@ -180,15 +203,16 @@ export class TextServiceClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' - ), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1beta2.TextService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1beta2.TextService', + 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 @@ -219,36 +243,41 @@ export class TextServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1beta2.TextService. this.textServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1beta2.TextService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1beta2.TextService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1beta2.TextService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1beta2 + .TextService, + 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 textServiceStubMethods = - ['generateText', 'embedText']; + const textServiceStubMethods = ['generateText', 'embedText']; for (const methodName of textServiceStubMethods) { const callPromise = this.textServiceStub.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 = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -263,8 +292,14 @@ export class TextServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -275,8 +310,14 @@ export class TextServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -316,8 +357,9 @@ export class TextServiceClient { * 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; @@ -328,253 +370,345 @@ export class TextServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Generates a response from the model given an input message. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The model name to use with the format name=models/{model}. - * @param {google.ai.generativelanguage.v1beta2.TextPrompt} request.prompt - * Required. The free-form input text given to the model as a prompt. - * - * Given a prompt, the model will generate a TextCompletion response it - * predicts as the completion of the input text. - * @param {number} request.temperature - * Controls the randomness of the output. - * Note: The default value varies by model, see the `Model.temperature` - * attribute of the `Model` returned the `getModel` function. - * - * Values can range from [0.0,1.0], - * inclusive. A value closer to 1.0 will produce responses that are more - * varied and creative, while a value closer to 0.0 will typically result in - * more straightforward responses from the model. - * @param {number} request.candidateCount - * Number of generated responses to return. - * - * This value must be between [1, 8], inclusive. If unset, this will default - * to 1. - * @param {number} request.maxOutputTokens - * The maximum number of tokens to include in a candidate. - * - * If unset, this will default to 64. - * @param {number} request.topP - * The maximum cumulative probability of tokens to consider when sampling. - * - * The model uses combined Top-k and nucleus sampling. - * - * Tokens are sorted based on their assigned probabilities so that only the - * most liekly tokens are considered. Top-k sampling directly limits the - * maximum number of tokens to consider, while Nucleus sampling limits number - * of tokens based on the cumulative probability. - * - * Note: The default value varies by model, see the `Model.top_p` - * attribute of the `Model` returned the `getModel` function. - * @param {number} request.topK - * The maximum number of tokens to consider when sampling. - * - * The model uses combined Top-k and nucleus sampling. - * - * Top-k sampling considers the set of `top_k` most probable tokens. - * Defaults to 40. - * - * Note: The default value varies by model, see the `Model.top_k` - * attribute of the `Model` returned the `getModel` function. - * @param {number[]} request.safetySettings - * A list of unique `SafetySetting` instances for blocking unsafe content. - * - * that will be enforced on the `GenerateTextRequest.prompt` and - * `GenerateTextResponse.candidates`. There should not be more than one - * setting for each `SafetyCategory` type. The API will block any prompts and - * responses that fail to meet the thresholds set by these settings. This list - * overrides the default settings for each `SafetyCategory` specified in the - * safety_settings. If there is no `SafetySetting` for a given - * `SafetyCategory` provided in the list, the API will use the default safety - * setting for that category. - * @param {string[]} request.stopSequences - * The set of character sequences (up to 5) that will stop output generation. - * If specified, the API will stop at the first appearance of a stop - * sequence. The stop sequence will not be included as part of 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.ai.generativelanguage.v1beta2.GenerateTextResponse|GenerateTextResponse}. - * 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/v1beta2/text_service.generate_text.js - * region_tag:generativelanguage_v1beta2_generated_TextService_GenerateText_async - */ + /** + * Generates a response from the model given an input message. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The model name to use with the format name=models/{model}. + * @param {google.ai.generativelanguage.v1beta2.TextPrompt} request.prompt + * Required. The free-form input text given to the model as a prompt. + * + * Given a prompt, the model will generate a TextCompletion response it + * predicts as the completion of the input text. + * @param {number} request.temperature + * Controls the randomness of the output. + * Note: The default value varies by model, see the `Model.temperature` + * attribute of the `Model` returned the `getModel` function. + * + * Values can range from [0.0,1.0], + * inclusive. A value closer to 1.0 will produce responses that are more + * varied and creative, while a value closer to 0.0 will typically result in + * more straightforward responses from the model. + * @param {number} request.candidateCount + * Number of generated responses to return. + * + * This value must be between [1, 8], inclusive. If unset, this will default + * to 1. + * @param {number} request.maxOutputTokens + * The maximum number of tokens to include in a candidate. + * + * If unset, this will default to 64. + * @param {number} request.topP + * The maximum cumulative probability of tokens to consider when sampling. + * + * The model uses combined Top-k and nucleus sampling. + * + * Tokens are sorted based on their assigned probabilities so that only the + * most liekly tokens are considered. Top-k sampling directly limits the + * maximum number of tokens to consider, while Nucleus sampling limits number + * of tokens based on the cumulative probability. + * + * Note: The default value varies by model, see the `Model.top_p` + * attribute of the `Model` returned the `getModel` function. + * @param {number} request.topK + * The maximum number of tokens to consider when sampling. + * + * The model uses combined Top-k and nucleus sampling. + * + * Top-k sampling considers the set of `top_k` most probable tokens. + * Defaults to 40. + * + * Note: The default value varies by model, see the `Model.top_k` + * attribute of the `Model` returned the `getModel` function. + * @param {number[]} request.safetySettings + * A list of unique `SafetySetting` instances for blocking unsafe content. + * + * that will be enforced on the `GenerateTextRequest.prompt` and + * `GenerateTextResponse.candidates`. There should not be more than one + * setting for each `SafetyCategory` type. The API will block any prompts and + * responses that fail to meet the thresholds set by these settings. This list + * overrides the default settings for each `SafetyCategory` specified in the + * safety_settings. If there is no `SafetySetting` for a given + * `SafetyCategory` provided in the list, the API will use the default safety + * setting for that category. + * @param {string[]} request.stopSequences + * The set of character sequences (up to 5) that will stop output generation. + * If specified, the API will stop at the first appearance of a stop + * sequence. The stop sequence will not be included as part of 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.ai.generativelanguage.v1beta2.GenerateTextResponse|GenerateTextResponse}. + * 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/v1beta2/text_service.generate_text.js + * region_tag:generativelanguage_v1beta2_generated_TextService_GenerateText_async + */ generateText( - request?: protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta2.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta2.IGenerateTextResponse, + ( + | protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest + | undefined + ), + {} | undefined, + ] + >; generateText( - request: protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta2.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta2.IGenerateTextResponse, + | protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateText( - request: protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta2.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta2.IGenerateTextResponse, + | protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateText( - request?: protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta2.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1beta2.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta2.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta2.IGenerateTextResponse, + | protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta2.IGenerateTextResponse, + ( + | protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('generateText request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta2.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta2.IGenerateTextResponse, + | protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('generateText response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.generateText(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta2.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest|undefined, - {}|undefined - ]) => { - this._log.info('generateText response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .generateText(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta2.IGenerateTextResponse, + ( + | protos.google.ai.generativelanguage.v1beta2.IGenerateTextRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('generateText response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Generates an embedding from the model given an input message. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The model name to use with the format model=models/{model}. - * @param {string} request.text - * Required. The free-form input text that the model will turn into an - * embedding. - * @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.ai.generativelanguage.v1beta2.EmbedTextResponse|EmbedTextResponse}. - * 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/v1beta2/text_service.embed_text.js - * region_tag:generativelanguage_v1beta2_generated_TextService_EmbedText_async - */ + /** + * Generates an embedding from the model given an input message. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The model name to use with the format model=models/{model}. + * @param {string} request.text + * Required. The free-form input text that the model will turn into an + * embedding. + * @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.ai.generativelanguage.v1beta2.EmbedTextResponse|EmbedTextResponse}. + * 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/v1beta2/text_service.embed_text.js + * region_tag:generativelanguage_v1beta2_generated_TextService_EmbedText_async + */ embedText( - request?: protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta2.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta2.IEmbedTextResponse, + protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest | undefined, + {} | undefined, + ] + >; embedText( - request: protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta2.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta2.IEmbedTextResponse, + | protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; embedText( - request: protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta2.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta2.IEmbedTextResponse, + | protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; embedText( - request?: protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta2.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta2.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta2.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta2.IEmbedTextResponse, + | protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta2.IEmbedTextResponse, + protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('embedText request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta2.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta2.IEmbedTextResponse, + | protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('embedText response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.embedText(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta2.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest|undefined, - {}|undefined - ]) => { - this._log.info('embedText response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .embedText(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta2.IEmbedTextResponse, + ( + | protos.google.ai.generativelanguage.v1beta2.IEmbedTextRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('embedText response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -590,7 +724,7 @@ export class TextServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -615,7 +749,7 @@ export class TextServiceClient { */ close(): Promise { if (this.textServiceStub && !this._terminated) { - return this.textServiceStub.then(stub => { + return this.textServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -623,4 +757,4 @@ export class TextServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1beta3/discuss_service_client.ts b/packages/google-ai-generativelanguage/src/v1beta3/discuss_service_client.ts index 5774b60b1808..d0349f4cc31a 100644 --- a/packages/google-ai-generativelanguage/src/v1beta3/discuss_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1beta3/discuss_service_client.ts @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +52,7 @@ export class DiscussServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -60,9 +65,9 @@ export class DiscussServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - discussServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + discussServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of DiscussServiceClient. @@ -103,21 +108,42 @@ export class DiscussServiceClient { * const client = new DiscussServiceClient({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 DiscussServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -142,7 +168,7 @@ export class DiscussServiceClient { 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; @@ -156,10 +182,7 @@ export class DiscussServiceClient { } // 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 { @@ -180,21 +203,22 @@ export class DiscussServiceClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' - ), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), permissionPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}/permissions/{permission}' + 'tunedModels/{tuned_model}/permissions/{permission}', ), tunedModelPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}' + 'tunedModels/{tuned_model}', ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1beta3.DiscussService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1beta3.DiscussService', + 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 @@ -225,36 +249,41 @@ export class DiscussServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1beta3.DiscussService. this.discussServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1beta3.DiscussService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1beta3.DiscussService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1beta3.DiscussService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1beta3 + .DiscussService, + 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 discussServiceStubMethods = - ['generateMessage', 'countMessageTokens']; + const discussServiceStubMethods = ['generateMessage', 'countMessageTokens']; for (const methodName of discussServiceStubMethods) { const callPromise = this.discussServiceStub.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 = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -269,8 +298,14 @@ export class DiscussServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -281,8 +316,14 @@ export class DiscussServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -322,8 +363,9 @@ export class DiscussServiceClient { * 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; @@ -334,231 +376,329 @@ export class DiscussServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Generates a response from the model given an input `MessagePrompt`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The name of the model to use. - * - * Format: `name=models/{model}`. - * @param {google.ai.generativelanguage.v1beta3.MessagePrompt} request.prompt - * Required. The structured textual input given to the model as a prompt. - * - * Given a - * prompt, the model will return what it predicts is the next message in the - * discussion. - * @param {number} [request.temperature] - * Optional. Controls the randomness of the output. - * - * Values can range over `[0.0,1.0]`, - * inclusive. A value closer to `1.0` will produce responses that are more - * varied, while a value closer to `0.0` will typically result in - * less surprising responses from the model. - * @param {number} [request.candidateCount] - * Optional. The number of generated response messages to return. - * - * This value must be between - * `[1, 8]`, inclusive. If unset, this will default to `1`. - * @param {number} [request.topP] - * Optional. The maximum cumulative probability of tokens to consider when - * sampling. - * - * The model uses combined Top-k and nucleus sampling. - * - * Nucleus sampling considers the smallest set of tokens whose probability - * sum is at least `top_p`. - * @param {number} [request.topK] - * Optional. The maximum number of tokens to consider when sampling. - * - * The model uses combined Top-k and nucleus sampling. - * - * Top-k sampling considers the set of `top_k` most probable tokens. - * @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.ai.generativelanguage.v1beta3.GenerateMessageResponse|GenerateMessageResponse}. - * 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/v1beta3/discuss_service.generate_message.js - * region_tag:generativelanguage_v1beta3_generated_DiscussService_GenerateMessage_async - */ + /** + * Generates a response from the model given an input `MessagePrompt`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The name of the model to use. + * + * Format: `name=models/{model}`. + * @param {google.ai.generativelanguage.v1beta3.MessagePrompt} request.prompt + * Required. The structured textual input given to the model as a prompt. + * + * Given a + * prompt, the model will return what it predicts is the next message in the + * discussion. + * @param {number} [request.temperature] + * Optional. Controls the randomness of the output. + * + * Values can range over `[0.0,1.0]`, + * inclusive. A value closer to `1.0` will produce responses that are more + * varied, while a value closer to `0.0` will typically result in + * less surprising responses from the model. + * @param {number} [request.candidateCount] + * Optional. The number of generated response messages to return. + * + * This value must be between + * `[1, 8]`, inclusive. If unset, this will default to `1`. + * @param {number} [request.topP] + * Optional. The maximum cumulative probability of tokens to consider when + * sampling. + * + * The model uses combined Top-k and nucleus sampling. + * + * Nucleus sampling considers the smallest set of tokens whose probability + * sum is at least `top_p`. + * @param {number} [request.topK] + * Optional. The maximum number of tokens to consider when sampling. + * + * The model uses combined Top-k and nucleus sampling. + * + * Top-k sampling considers the set of `top_k` most probable tokens. + * @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.ai.generativelanguage.v1beta3.GenerateMessageResponse|GenerateMessageResponse}. + * 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/v1beta3/discuss_service.generate_message.js + * region_tag:generativelanguage_v1beta3_generated_DiscussService_GenerateMessage_async + */ generateMessage( - request?: protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.IGenerateMessageResponse, + ( + | protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest + | undefined + ), + {} | undefined, + ] + >; generateMessage( - request: protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.IGenerateMessageResponse, + | protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateMessage( - request: protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.IGenerateMessageResponse, + | protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateMessage( - request?: protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta3.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1beta3.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta3.IGenerateMessageResponse, + | protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.IGenerateMessageResponse, + ( + | protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('generateMessage request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta3.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta3.IGenerateMessageResponse, + | protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('generateMessage response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.generateMessage(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta3.IGenerateMessageResponse, - protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest|undefined, - {}|undefined - ]) => { - this._log.info('generateMessage response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .generateMessage(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta3.IGenerateMessageResponse, + ( + | protos.google.ai.generativelanguage.v1beta3.IGenerateMessageRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('generateMessage response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Runs a model's tokenizer on a string and returns the token count. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The model's resource name. This serves as an ID for the Model to - * use. - * - * This name should match a model name returned by the `ListModels` method. - * - * Format: `models/{model}` - * @param {google.ai.generativelanguage.v1beta3.MessagePrompt} request.prompt - * Required. The prompt, whose token count is to 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 {@link protos.google.ai.generativelanguage.v1beta3.CountMessageTokensResponse|CountMessageTokensResponse}. - * 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/v1beta3/discuss_service.count_message_tokens.js - * region_tag:generativelanguage_v1beta3_generated_DiscussService_CountMessageTokens_async - */ + /** + * Runs a model's tokenizer on a string and returns the token count. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The model's resource name. This serves as an ID for the Model to + * use. + * + * This name should match a model name returned by the `ListModels` method. + * + * Format: `models/{model}` + * @param {google.ai.generativelanguage.v1beta3.MessagePrompt} request.prompt + * Required. The prompt, whose token count is to 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 {@link protos.google.ai.generativelanguage.v1beta3.CountMessageTokensResponse|CountMessageTokensResponse}. + * 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/v1beta3/discuss_service.count_message_tokens.js + * region_tag:generativelanguage_v1beta3_generated_DiscussService_CountMessageTokens_async + */ countMessageTokens( - request?: protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensResponse, + ( + | protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest + | undefined + ), + {} | undefined, + ] + >; countMessageTokens( - request: protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensResponse, + | protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): void; countMessageTokens( - request: protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensResponse, + | protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): void; countMessageTokens( - request?: protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensResponse, + | protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensResponse, + ( + | protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('countMessageTokens request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensResponse, + | protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('countMessageTokens response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.countMessageTokens(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensResponse, - protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest|undefined, - {}|undefined - ]) => { - this._log.info('countMessageTokens response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .countMessageTokens(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensResponse, + ( + | protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('countMessageTokens response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -574,7 +714,7 @@ export class DiscussServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -598,7 +738,7 @@ export class DiscussServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - permissionPath(tunedModel:string,permission:string) { + permissionPath(tunedModel: string, permission: string) { return this.pathTemplates.permissionPathTemplate.render({ tuned_model: tunedModel, permission: permission, @@ -613,7 +753,8 @@ export class DiscussServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromPermissionName(permissionName: string) { - return this.pathTemplates.permissionPathTemplate.match(permissionName).tuned_model; + return this.pathTemplates.permissionPathTemplate.match(permissionName) + .tuned_model; } /** @@ -624,7 +765,8 @@ export class DiscussServiceClient { * @returns {string} A string representing the permission. */ matchPermissionFromPermissionName(permissionName: string) { - return this.pathTemplates.permissionPathTemplate.match(permissionName).permission; + return this.pathTemplates.permissionPathTemplate.match(permissionName) + .permission; } /** @@ -633,7 +775,7 @@ export class DiscussServiceClient { * @param {string} tuned_model * @returns {string} Resource name string. */ - tunedModelPath(tunedModel:string) { + tunedModelPath(tunedModel: string) { return this.pathTemplates.tunedModelPathTemplate.render({ tuned_model: tunedModel, }); @@ -647,7 +789,8 @@ export class DiscussServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromTunedModelName(tunedModelName: string) { - return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName).tuned_model; + return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName) + .tuned_model; } /** @@ -658,7 +801,7 @@ export class DiscussServiceClient { */ close(): Promise { if (this.discussServiceStub && !this._terminated) { - return this.discussServiceStub.then(stub => { + return this.discussServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -666,4 +809,4 @@ export class DiscussServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1beta3/index.ts b/packages/google-ai-generativelanguage/src/v1beta3/index.ts index d22135e1cb0c..3f7447807fc2 100644 --- a/packages/google-ai-generativelanguage/src/v1beta3/index.ts +++ b/packages/google-ai-generativelanguage/src/v1beta3/index.ts @@ -16,7 +16,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {DiscussServiceClient} from './discuss_service_client'; -export {ModelServiceClient} from './model_service_client'; -export {PermissionServiceClient} from './permission_service_client'; -export {TextServiceClient} from './text_service_client'; +export { DiscussServiceClient } from './discuss_service_client'; +export { ModelServiceClient } from './model_service_client'; +export { PermissionServiceClient } from './permission_service_client'; +export { TextServiceClient } from './text_service_client'; diff --git a/packages/google-ai-generativelanguage/src/v1beta3/model_service_client.ts b/packages/google-ai-generativelanguage/src/v1beta3/model_service_client.ts index 11f80b60b958..7e54b86bbe33 100644 --- a/packages/google-ai-generativelanguage/src/v1beta3/model_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1beta3/model_service_client.ts @@ -18,11 +18,20 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +53,7 @@ export class ModelServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -57,10 +66,10 @@ export class ModelServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - modelServiceStub?: Promise<{[name: string]: Function}>; + modelServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ModelServiceClient. @@ -101,21 +110,42 @@ export class ModelServiceClient { * const client = new ModelServiceClient({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 ModelServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -140,7 +170,7 @@ export class ModelServiceClient { 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; @@ -154,10 +184,7 @@ export class ModelServiceClient { } // 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 { @@ -178,14 +205,12 @@ export class ModelServiceClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' - ), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), permissionPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}/permissions/{permission}' + 'tunedModels/{tuned_model}/permissions/{permission}', ), tunedModelPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}' + 'tunedModels/{tuned_model}', ), }; @@ -193,10 +218,16 @@ export class ModelServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listModels: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'models'), - listTunedModels: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'tunedModels') + listModels: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'models', + ), + listTunedModels: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'tunedModels', + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -205,29 +236,37 @@ export class ModelServiceClient { // 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 = []; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const createTunedModelResponse = protoFilesRoot.lookup( - '.google.ai.generativelanguage.v1beta3.TunedModel') as gax.protobuf.Type; + '.google.ai.generativelanguage.v1beta3.TunedModel', + ) as gax.protobuf.Type; const createTunedModelMetadata = protoFilesRoot.lookup( - '.google.ai.generativelanguage.v1beta3.CreateTunedModelMetadata') as gax.protobuf.Type; + '.google.ai.generativelanguage.v1beta3.CreateTunedModelMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { createTunedModel: new this._gaxModule.LongrunningDescriptor( this.operationsClient, createTunedModelResponse.decode.bind(createTunedModelResponse), - createTunedModelMetadata.decode.bind(createTunedModelMetadata)) + createTunedModelMetadata.decode.bind(createTunedModelMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1beta3.ModelService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1beta3.ModelService', + 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 @@ -258,28 +297,42 @@ export class ModelServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1beta3.ModelService. this.modelServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1beta3.ModelService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1beta3.ModelService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1beta3.ModelService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1beta3 + .ModelService, + 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 modelServiceStubMethods = - ['getModel', 'listModels', 'getTunedModel', 'listTunedModels', 'createTunedModel', 'updateTunedModel', 'deleteTunedModel']; + const modelServiceStubMethods = [ + 'getModel', + 'listModels', + 'getTunedModel', + 'listTunedModels', + 'createTunedModel', + 'updateTunedModel', + 'deleteTunedModel', + ]; for (const methodName of modelServiceStubMethods) { const callPromise = this.modelServiceStub.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] || @@ -289,7 +342,7 @@ export class ModelServiceClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -304,8 +357,14 @@ export class ModelServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -316,8 +375,14 @@ export class ModelServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -357,8 +422,9 @@ export class ModelServiceClient { * 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; @@ -369,590 +435,869 @@ export class ModelServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets information about a specific Model. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the model. - * - * This name should match a model name returned by the `ListModels` method. - * - * Format: `models/{model}` - * @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.ai.generativelanguage.v1beta3.Model|Model}. - * 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/v1beta3/model_service.get_model.js - * region_tag:generativelanguage_v1beta3_generated_ModelService_GetModel_async - */ + /** + * Gets information about a specific Model. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the model. + * + * This name should match a model name returned by the `ListModels` method. + * + * Format: `models/{model}` + * @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.ai.generativelanguage.v1beta3.Model|Model}. + * 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/v1beta3/model_service.get_model.js + * region_tag:generativelanguage_v1beta3_generated_ModelService_GetModel_async + */ getModel( - request?: protos.google.ai.generativelanguage.v1beta3.IGetModelRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.IModel, - protos.google.ai.generativelanguage.v1beta3.IGetModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta3.IGetModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.IModel, + protos.google.ai.generativelanguage.v1beta3.IGetModelRequest | undefined, + {} | undefined, + ] + >; getModel( - request: protos.google.ai.generativelanguage.v1beta3.IGetModelRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.IModel, - protos.google.ai.generativelanguage.v1beta3.IGetModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.IGetModelRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.IModel, + | protos.google.ai.generativelanguage.v1beta3.IGetModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getModel( - request: protos.google.ai.generativelanguage.v1beta3.IGetModelRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.IModel, - protos.google.ai.generativelanguage.v1beta3.IGetModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.IGetModelRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.IModel, + | protos.google.ai.generativelanguage.v1beta3.IGetModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getModel( - request?: protos.google.ai.generativelanguage.v1beta3.IGetModelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta3.IModel, - protos.google.ai.generativelanguage.v1beta3.IGetModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta3.IGetModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta3.IModel, - protos.google.ai.generativelanguage.v1beta3.IGetModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.IModel, - protos.google.ai.generativelanguage.v1beta3.IGetModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta3.IGetModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta3.IModel, + | protos.google.ai.generativelanguage.v1beta3.IGetModelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.IModel, + protos.google.ai.generativelanguage.v1beta3.IGetModelRequest | 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('getModel request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta3.IModel, - protos.google.ai.generativelanguage.v1beta3.IGetModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta3.IModel, + | protos.google.ai.generativelanguage.v1beta3.IGetModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getModel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta3.IModel, - protos.google.ai.generativelanguage.v1beta3.IGetModelRequest|undefined, - {}|undefined - ]) => { - this._log.info('getModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta3.IModel, + ( + | protos.google.ai.generativelanguage.v1beta3.IGetModelRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets information about a specific TunedModel. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the model. - * - * Format: `tunedModels/my-model-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.ai.generativelanguage.v1beta3.TunedModel|TunedModel}. - * 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/v1beta3/model_service.get_tuned_model.js - * region_tag:generativelanguage_v1beta3_generated_ModelService_GetTunedModel_async - */ + /** + * Gets information about a specific TunedModel. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the model. + * + * Format: `tunedModels/my-model-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.ai.generativelanguage.v1beta3.TunedModel|TunedModel}. + * 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/v1beta3/model_service.get_tuned_model.js + * region_tag:generativelanguage_v1beta3_generated_ModelService_GetTunedModel_async + */ getTunedModel( - request?: protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.ITunedModel, - protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + ( + | protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest + | undefined + ), + {} | undefined, + ] + >; getTunedModel( - request: protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.ITunedModel, - protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + | protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getTunedModel( - request: protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.ITunedModel, - protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + | protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getTunedModel( - request?: protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta3.ITunedModel, - protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta3.ITunedModel, - protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.ITunedModel, - protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + | protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + ( + | protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest + | 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('getTunedModel request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta3.ITunedModel, - protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + | protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getTunedModel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getTunedModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta3.ITunedModel, - protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest|undefined, - {}|undefined - ]) => { - this._log.info('getTunedModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getTunedModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + ( + | protos.google.ai.generativelanguage.v1beta3.IGetTunedModelRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getTunedModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a tuned model. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ai.generativelanguage.v1beta3.TunedModel} request.tunedModel - * Required. The tuned model to update. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to update. - * @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.ai.generativelanguage.v1beta3.TunedModel|TunedModel}. - * 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/v1beta3/model_service.update_tuned_model.js - * region_tag:generativelanguage_v1beta3_generated_ModelService_UpdateTunedModel_async - */ + /** + * Updates a tuned model. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ai.generativelanguage.v1beta3.TunedModel} request.tunedModel + * Required. The tuned model to update. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to update. + * @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.ai.generativelanguage.v1beta3.TunedModel|TunedModel}. + * 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/v1beta3/model_service.update_tuned_model.js + * region_tag:generativelanguage_v1beta3_generated_ModelService_UpdateTunedModel_async + */ updateTunedModel( - request?: protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.ITunedModel, - protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + ( + | protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest + | undefined + ), + {} | undefined, + ] + >; updateTunedModel( - request: protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.ITunedModel, - protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + | protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateTunedModel( - request: protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.ITunedModel, - protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + | protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateTunedModel( - request?: protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta3.ITunedModel, - protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta3.ITunedModel, - protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.ITunedModel, - protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + | protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + ( + | protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest + | 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({ - 'tuned_model.name': request.tunedModel!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'tuned_model.name': request.tunedModel!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateTunedModel request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta3.ITunedModel, - protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + | protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateTunedModel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateTunedModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta3.ITunedModel, - protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateTunedModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateTunedModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + ( + | protos.google.ai.generativelanguage.v1beta3.IUpdateTunedModelRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateTunedModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a tuned model. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the model. - * Format: `tunedModels/my-model-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 include:samples/generated/v1beta3/model_service.delete_tuned_model.js - * region_tag:generativelanguage_v1beta3_generated_ModelService_DeleteTunedModel_async - */ + /** + * Deletes a tuned model. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the model. + * Format: `tunedModels/my-model-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 include:samples/generated/v1beta3/model_service.delete_tuned_model.js + * region_tag:generativelanguage_v1beta3_generated_ModelService_DeleteTunedModel_async + */ deleteTunedModel( - request?: protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest + | undefined + ), + {} | undefined, + ] + >; deleteTunedModel( - request: protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteTunedModel( - request: protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteTunedModel( - request?: protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest + | 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('deleteTunedModel request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteTunedModel response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteTunedModel(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteTunedModel response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteTunedModel(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta3.IDeleteTunedModelRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteTunedModel response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a tuned model. - * Intermediate tuning progress (if any) is accessed through the - * [google.longrunning.Operations] service. - * - * Status and results can be accessed through the Operations service. - * Example: - * GET /v1/tunedModels/az2mb0bpw6i/operations/000-111-222 - * - * @param {Object} request - * The request object that will be sent. - * @param {string} [request.tunedModelId] - * Optional. The unique id for the tuned model if specified. - * This value should be up to 40 characters, the first character must be a - * letter, the last could be a letter or a number. The id must match the - * regular expression: [a-z]([a-z0-9-]{0,38}[a-z0-9])?. - * @param {google.ai.generativelanguage.v1beta3.TunedModel} request.tunedModel - * Required. The tuned model 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 include:samples/generated/v1beta3/model_service.create_tuned_model.js - * region_tag:generativelanguage_v1beta3_generated_ModelService_CreateTunedModel_async - */ + /** + * Creates a tuned model. + * Intermediate tuning progress (if any) is accessed through the + * [google.longrunning.Operations] service. + * + * Status and results can be accessed through the Operations service. + * Example: + * GET /v1/tunedModels/az2mb0bpw6i/operations/000-111-222 + * + * @param {Object} request + * The request object that will be sent. + * @param {string} [request.tunedModelId] + * Optional. The unique id for the tuned model if specified. + * This value should be up to 40 characters, the first character must be a + * letter, the last could be a letter or a number. The id must match the + * regular expression: [a-z]([a-z0-9-]{0,38}[a-z0-9])?. + * @param {google.ai.generativelanguage.v1beta3.TunedModel} request.tunedModel + * Required. The tuned model 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 include:samples/generated/v1beta3/model_service.create_tuned_model.js + * region_tag:generativelanguage_v1beta3_generated_ModelService_CreateTunedModel_async + */ createTunedModel( - request?: protos.google.ai.generativelanguage.v1beta3.ICreateTunedModelRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta3.ICreateTunedModelRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + protos.google.ai.generativelanguage.v1beta3.ICreateTunedModelMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; createTunedModel( - request: protos.google.ai.generativelanguage.v1beta3.ICreateTunedModelRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.ICreateTunedModelRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + protos.google.ai.generativelanguage.v1beta3.ICreateTunedModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createTunedModel( - request: protos.google.ai.generativelanguage.v1beta3.ICreateTunedModelRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.ICreateTunedModelRequest, + callback: Callback< + LROperation< + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + protos.google.ai.generativelanguage.v1beta3.ICreateTunedModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createTunedModel( - request?: protos.google.ai.generativelanguage.v1beta3.ICreateTunedModelRequest, - 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.ai.generativelanguage.v1beta3.ICreateTunedModelRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + protos.google.ai.generativelanguage.v1beta3.ICreateTunedModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + protos.google.ai.generativelanguage.v1beta3.ICreateTunedModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + protos.google.ai.generativelanguage.v1beta3.ICreateTunedModelMetadata + >, + 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 || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | Callback< + LROperation< + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + protos.google.ai.generativelanguage.v1beta3.ICreateTunedModelMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('createTunedModel response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('createTunedModel request %j', request); - return this.innerApiCalls.createTunedModel(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('createTunedModel response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .createTunedModel(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + protos.google.ai.generativelanguage.v1beta3.ICreateTunedModelMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createTunedModel response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `createTunedModel()`. - * @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/v1beta3/model_service.create_tuned_model.js - * region_tag:generativelanguage_v1beta3_generated_ModelService_CreateTunedModel_async - */ - async checkCreateTunedModelProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `createTunedModel()`. + * @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/v1beta3/model_service.create_tuned_model.js + * region_tag:generativelanguage_v1beta3_generated_ModelService_CreateTunedModel_async + */ + async checkCreateTunedModelProgress( + name: string, + ): Promise< + LROperation< + protos.google.ai.generativelanguage.v1beta3.TunedModel, + protos.google.ai.generativelanguage.v1beta3.CreateTunedModelMetadata + > + > { this._log.info('createTunedModel 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.createTunedModel, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createTunedModel, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.ai.generativelanguage.v1beta3.TunedModel, + protos.google.ai.generativelanguage.v1beta3.CreateTunedModelMetadata + >; } - /** - * Lists models available through the API. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of `Models` to return (per page). - * - * The service may return fewer models. - * If unspecified, at most 50 models will be returned per page. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} request.pageToken - * A page token, received from a previous `ListModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListModels` must match - * the call that provided the page token. - * @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.ai.generativelanguage.v1beta3.Model|Model}. - * 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 `listModelsAsync()` - * 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 models available through the API. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of `Models` to return (per page). + * + * The service may return fewer models. + * If unspecified, at most 50 models will be returned per page. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} request.pageToken + * A page token, received from a previous `ListModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListModels` must match + * the call that provided the page token. + * @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.ai.generativelanguage.v1beta3.Model|Model}. + * 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 `listModelsAsync()` + * 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. + */ listModels( - request?: protos.google.ai.generativelanguage.v1beta3.IListModelsRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.IModel[], - protos.google.ai.generativelanguage.v1beta3.IListModelsRequest|null, - protos.google.ai.generativelanguage.v1beta3.IListModelsResponse - ]>; + request?: protos.google.ai.generativelanguage.v1beta3.IListModelsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.IModel[], + protos.google.ai.generativelanguage.v1beta3.IListModelsRequest | null, + protos.google.ai.generativelanguage.v1beta3.IListModelsResponse, + ] + >; listModels( - request: protos.google.ai.generativelanguage.v1beta3.IListModelsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta3.IListModelsRequest, - protos.google.ai.generativelanguage.v1beta3.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta3.IModel>): void; + request: protos.google.ai.generativelanguage.v1beta3.IListModelsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta3.IListModelsRequest, + | protos.google.ai.generativelanguage.v1beta3.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta3.IModel + >, + ): void; listModels( - request: protos.google.ai.generativelanguage.v1beta3.IListModelsRequest, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta3.IListModelsRequest, - protos.google.ai.generativelanguage.v1beta3.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta3.IModel>): void; + request: protos.google.ai.generativelanguage.v1beta3.IListModelsRequest, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta3.IListModelsRequest, + | protos.google.ai.generativelanguage.v1beta3.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta3.IModel + >, + ): void; listModels( - request?: protos.google.ai.generativelanguage.v1beta3.IListModelsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.ai.generativelanguage.v1beta3.IListModelsRequest, - protos.google.ai.generativelanguage.v1beta3.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta3.IModel>, - callback?: PaginationCallback< + request?: protos.google.ai.generativelanguage.v1beta3.IListModelsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ai.generativelanguage.v1beta3.IListModelsRequest, - protos.google.ai.generativelanguage.v1beta3.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta3.IModel>): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.IModel[], - protos.google.ai.generativelanguage.v1beta3.IListModelsRequest|null, - protos.google.ai.generativelanguage.v1beta3.IListModelsResponse - ]>|void { + | protos.google.ai.generativelanguage.v1beta3.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta3.IModel + >, + callback?: PaginationCallback< + protos.google.ai.generativelanguage.v1beta3.IListModelsRequest, + | protos.google.ai.generativelanguage.v1beta3.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta3.IModel + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.IModel[], + protos.google.ai.generativelanguage.v1beta3.IListModelsRequest | null, + protos.google.ai.generativelanguage.v1beta3.IListModelsResponse, + ] + > | 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 || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta3.IListModelsRequest, - protos.google.ai.generativelanguage.v1beta3.IListModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta3.IModel>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.ai.generativelanguage.v1beta3.IListModelsRequest, + | protos.google.ai.generativelanguage.v1beta3.IListModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta3.IModel + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listModels values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -961,201 +1306,233 @@ export class ModelServiceClient { this._log.info('listModels request %j', request); return this.innerApiCalls .listModels(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ai.generativelanguage.v1beta3.IModel[], - protos.google.ai.generativelanguage.v1beta3.IListModelsRequest|null, - protos.google.ai.generativelanguage.v1beta3.IListModelsResponse - ]) => { - this._log.info('listModels values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ai.generativelanguage.v1beta3.IModel[], + protos.google.ai.generativelanguage.v1beta3.IListModelsRequest | null, + protos.google.ai.generativelanguage.v1beta3.IListModelsResponse, + ]) => { + this._log.info('listModels values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listModels`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of `Models` to return (per page). - * - * The service may return fewer models. - * If unspecified, at most 50 models will be returned per page. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} request.pageToken - * A page token, received from a previous `ListModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListModels` must match - * the call that provided the page token. - * @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.ai.generativelanguage.v1beta3.Model|Model} 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 `listModelsAsync()` - * 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 `listModels`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of `Models` to return (per page). + * + * The service may return fewer models. + * If unspecified, at most 50 models will be returned per page. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} request.pageToken + * A page token, received from a previous `ListModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListModels` must match + * the call that provided the page token. + * @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.ai.generativelanguage.v1beta3.Model|Model} 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 `listModelsAsync()` + * 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. + */ listModelsStream( - request?: protos.google.ai.generativelanguage.v1beta3.IListModelsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ai.generativelanguage.v1beta3.IListModelsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listModels stream %j', request); return this.descriptors.page.listModels.createStream( this.innerApiCalls.listModels as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listModels`, 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 {number} request.pageSize - * The maximum number of `Models` to return (per page). - * - * The service may return fewer models. - * If unspecified, at most 50 models will be returned per page. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} request.pageToken - * A page token, received from a previous `ListModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListModels` must match - * the call that provided the 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 protos.google.ai.generativelanguage.v1beta3.Model|Model}. 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 include:samples/generated/v1beta3/model_service.list_models.js - * region_tag:generativelanguage_v1beta3_generated_ModelService_ListModels_async - */ + /** + * Equivalent to `listModels`, 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 {number} request.pageSize + * The maximum number of `Models` to return (per page). + * + * The service may return fewer models. + * If unspecified, at most 50 models will be returned per page. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} request.pageToken + * A page token, received from a previous `ListModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListModels` must match + * the call that provided the 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 protos.google.ai.generativelanguage.v1beta3.Model|Model}. 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 include:samples/generated/v1beta3/model_service.list_models.js + * region_tag:generativelanguage_v1beta3_generated_ModelService_ListModels_async + */ listModelsAsync( - request?: protos.google.ai.generativelanguage.v1beta3.IListModelsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ai.generativelanguage.v1beta3.IListModelsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listModels iterate %j', request); return this.descriptors.page.listModels.asyncIterate( this.innerApiCalls['listModels'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists tuned models owned by the user. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of `TunedModels` to return (per page). - * The service may return fewer tuned models. - * - * If unspecified, at most 10 tuned models will be returned. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListTunedModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListTunedModels` - * must match the call that provided the page token. - * @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.ai.generativelanguage.v1beta3.TunedModel|TunedModel}. - * 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 `listTunedModelsAsync()` - * 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 tuned models owned by the user. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of `TunedModels` to return (per page). + * The service may return fewer tuned models. + * + * If unspecified, at most 10 tuned models will be returned. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListTunedModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListTunedModels` + * must match the call that provided the page token. + * @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.ai.generativelanguage.v1beta3.TunedModel|TunedModel}. + * 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 `listTunedModelsAsync()` + * 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. + */ listTunedModels( - request?: protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.ITunedModel[], - protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest|null, - protos.google.ai.generativelanguage.v1beta3.IListTunedModelsResponse - ]>; + request?: protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.ITunedModel[], + protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest | null, + protos.google.ai.generativelanguage.v1beta3.IListTunedModelsResponse, + ] + >; listTunedModels( - request: protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest, - protos.google.ai.generativelanguage.v1beta3.IListTunedModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta3.ITunedModel>): void; + request: protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest, + | protos.google.ai.generativelanguage.v1beta3.IListTunedModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta3.ITunedModel + >, + ): void; listTunedModels( - request: protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest, - protos.google.ai.generativelanguage.v1beta3.IListTunedModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta3.ITunedModel>): void; + request: protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest, + | protos.google.ai.generativelanguage.v1beta3.IListTunedModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta3.ITunedModel + >, + ): void; listTunedModels( - request?: protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest, - protos.google.ai.generativelanguage.v1beta3.IListTunedModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta3.ITunedModel>, - callback?: PaginationCallback< + request?: protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest, - protos.google.ai.generativelanguage.v1beta3.IListTunedModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta3.ITunedModel>): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.ITunedModel[], - protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest|null, - protos.google.ai.generativelanguage.v1beta3.IListTunedModelsResponse - ]>|void { + | protos.google.ai.generativelanguage.v1beta3.IListTunedModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta3.ITunedModel + >, + callback?: PaginationCallback< + protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest, + | protos.google.ai.generativelanguage.v1beta3.IListTunedModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta3.ITunedModel + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.ITunedModel[], + protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest | null, + protos.google.ai.generativelanguage.v1beta3.IListTunedModelsResponse, + ] + > | 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 || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest, - protos.google.ai.generativelanguage.v1beta3.IListTunedModelsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta3.ITunedModel>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest, + | protos.google.ai.generativelanguage.v1beta3.IListTunedModelsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta3.ITunedModel + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listTunedModels values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1164,117 +1541,123 @@ export class ModelServiceClient { this._log.info('listTunedModels request %j', request); return this.innerApiCalls .listTunedModels(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ai.generativelanguage.v1beta3.ITunedModel[], - protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest|null, - protos.google.ai.generativelanguage.v1beta3.IListTunedModelsResponse - ]) => { - this._log.info('listTunedModels values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ai.generativelanguage.v1beta3.ITunedModel[], + protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest | null, + protos.google.ai.generativelanguage.v1beta3.IListTunedModelsResponse, + ]) => { + this._log.info('listTunedModels values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listTunedModels`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of `TunedModels` to return (per page). - * The service may return fewer tuned models. - * - * If unspecified, at most 10 tuned models will be returned. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListTunedModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListTunedModels` - * must match the call that provided the page token. - * @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.ai.generativelanguage.v1beta3.TunedModel|TunedModel} 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 `listTunedModelsAsync()` - * 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 `listTunedModels`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of `TunedModels` to return (per page). + * The service may return fewer tuned models. + * + * If unspecified, at most 10 tuned models will be returned. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListTunedModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListTunedModels` + * must match the call that provided the page token. + * @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.ai.generativelanguage.v1beta3.TunedModel|TunedModel} 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 `listTunedModelsAsync()` + * 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. + */ listTunedModelsStream( - request?: protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listTunedModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTunedModels stream %j', request); return this.descriptors.page.listTunedModels.createStream( this.innerApiCalls.listTunedModels as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listTunedModels`, 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 {number} [request.pageSize] - * Optional. The maximum number of `TunedModels` to return (per page). - * The service may return fewer tuned models. - * - * If unspecified, at most 10 tuned models will be returned. - * This method returns at most 1000 models per page, even if you pass a larger - * page_size. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListTunedModels` call. - * - * Provide the `page_token` returned by one request as an argument to the next - * request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListTunedModels` - * must match the call that provided the 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 protos.google.ai.generativelanguage.v1beta3.TunedModel|TunedModel}. 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 include:samples/generated/v1beta3/model_service.list_tuned_models.js - * region_tag:generativelanguage_v1beta3_generated_ModelService_ListTunedModels_async - */ + /** + * Equivalent to `listTunedModels`, 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 {number} [request.pageSize] + * Optional. The maximum number of `TunedModels` to return (per page). + * The service may return fewer tuned models. + * + * If unspecified, at most 10 tuned models will be returned. + * This method returns at most 1000 models per page, even if you pass a larger + * page_size. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListTunedModels` call. + * + * Provide the `page_token` returned by one request as an argument to the next + * request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListTunedModels` + * must match the call that provided the 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 protos.google.ai.generativelanguage.v1beta3.TunedModel|TunedModel}. 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 include:samples/generated/v1beta3/model_service.list_tuned_models.js + * region_tag:generativelanguage_v1beta3_generated_ModelService_ListTunedModels_async + */ listTunedModelsAsync( - request?: protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ai.generativelanguage.v1beta3.IListTunedModelsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listTunedModels']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listTunedModels iterate %j', request); return this.descriptors.page.listTunedModels.asyncIterate( this.innerApiCalls['listTunedModels'] as GaxCall, request as {}, - callSettings + callSettings, ) as 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. @@ -1317,22 +1700,22 @@ export class ModelServiceClient { protos.google.longrunning.Operation, protos.google.longrunning.GetOperationRequest, {} | 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); } /** @@ -1367,15 +1750,15 @@ export class ModelServiceClient { */ listOperationsAsync( request: protos.google.longrunning.ListOperationsRequest, - options?: gax.CallOptions + 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); } /** @@ -1409,7 +1792,7 @@ export class ModelServiceClient { * await client.cancelOperation({name: ''}); * ``` */ - cancelOperation( + cancelOperation( request: protos.google.longrunning.CancelOperationRequest, optionsOrCallback?: | gax.CallOptions @@ -1422,25 +1805,24 @@ export class ModelServiceClient { protos.google.longrunning.CancelOperationRequest, protos.google.protobuf.Empty, {} | 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); } - /** * Deletes a long-running operation. This method indicates that the client is * no longer interested in the operation result. It does not cancel the @@ -1479,22 +1861,22 @@ export class ModelServiceClient { protos.google.protobuf.Empty, protos.google.longrunning.DeleteOperationRequest, {} | 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); } @@ -1508,7 +1890,7 @@ export class ModelServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -1532,7 +1914,7 @@ export class ModelServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - permissionPath(tunedModel:string,permission:string) { + permissionPath(tunedModel: string, permission: string) { return this.pathTemplates.permissionPathTemplate.render({ tuned_model: tunedModel, permission: permission, @@ -1547,7 +1929,8 @@ export class ModelServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromPermissionName(permissionName: string) { - return this.pathTemplates.permissionPathTemplate.match(permissionName).tuned_model; + return this.pathTemplates.permissionPathTemplate.match(permissionName) + .tuned_model; } /** @@ -1558,7 +1941,8 @@ export class ModelServiceClient { * @returns {string} A string representing the permission. */ matchPermissionFromPermissionName(permissionName: string) { - return this.pathTemplates.permissionPathTemplate.match(permissionName).permission; + return this.pathTemplates.permissionPathTemplate.match(permissionName) + .permission; } /** @@ -1567,7 +1951,7 @@ export class ModelServiceClient { * @param {string} tuned_model * @returns {string} Resource name string. */ - tunedModelPath(tunedModel:string) { + tunedModelPath(tunedModel: string) { return this.pathTemplates.tunedModelPathTemplate.render({ tuned_model: tunedModel, }); @@ -1581,7 +1965,8 @@ export class ModelServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromTunedModelName(tunedModelName: string) { - return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName).tuned_model; + return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName) + .tuned_model; } /** @@ -1592,7 +1977,7 @@ export class ModelServiceClient { */ close(): Promise { if (this.modelServiceStub && !this._terminated) { - return this.modelServiceStub.then(stub => { + return this.modelServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1601,4 +1986,4 @@ export class ModelServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1beta3/permission_service_client.ts b/packages/google-ai-generativelanguage/src/v1beta3/permission_service_client.ts index 9d26b3cc3b15..4842237c8f1e 100644 --- a/packages/google-ai-generativelanguage/src/v1beta3/permission_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1beta3/permission_service_client.ts @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class PermissionServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -57,9 +64,9 @@ export class PermissionServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - permissionServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + permissionServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of PermissionServiceClient. @@ -100,21 +107,42 @@ export class PermissionServiceClient { * const client = new PermissionServiceClient({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 PermissionServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -139,7 +167,7 @@ export class PermissionServiceClient { 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; @@ -153,10 +181,7 @@ export class PermissionServiceClient { } // 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 { @@ -177,14 +202,12 @@ export class PermissionServiceClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' - ), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), permissionPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}/permissions/{permission}' + 'tunedModels/{tuned_model}/permissions/{permission}', ), tunedModelPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}' + 'tunedModels/{tuned_model}', ), }; @@ -192,14 +215,20 @@ export class PermissionServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listPermissions: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'permissions') + listPermissions: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'permissions', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1beta3.PermissionService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1beta3.PermissionService', + 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 @@ -230,37 +259,48 @@ export class PermissionServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1beta3.PermissionService. this.permissionServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1beta3.PermissionService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1beta3.PermissionService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1beta3.PermissionService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1beta3 + .PermissionService, + 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 permissionServiceStubMethods = - ['createPermission', 'getPermission', 'listPermissions', 'updatePermission', 'deletePermission', 'transferOwnership']; + const permissionServiceStubMethods = [ + 'createPermission', + 'getPermission', + 'listPermissions', + 'updatePermission', + 'deletePermission', + 'transferOwnership', + ]; for (const methodName of permissionServiceStubMethods) { const callPromise = this.permissionServiceStub.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] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -275,8 +315,14 @@ export class PermissionServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -287,8 +333,14 @@ export class PermissionServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -328,8 +380,9 @@ export class PermissionServiceClient { * 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; @@ -340,588 +393,858 @@ export class PermissionServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Create a permission to a specific resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource of the `Permission`. - * Format: tunedModels/{tuned_model} - * @param {google.ai.generativelanguage.v1beta3.Permission} request.permission - * Required. The permission 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.ai.generativelanguage.v1beta3.Permission|Permission}. - * 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/v1beta3/permission_service.create_permission.js - * region_tag:generativelanguage_v1beta3_generated_PermissionService_CreatePermission_async - */ + /** + * Create a permission to a specific resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource of the `Permission`. + * Format: tunedModels/{tuned_model} + * @param {google.ai.generativelanguage.v1beta3.Permission} request.permission + * Required. The permission 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.ai.generativelanguage.v1beta3.Permission|Permission}. + * 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/v1beta3/permission_service.create_permission.js + * region_tag:generativelanguage_v1beta3_generated_PermissionService_CreatePermission_async + */ createPermission( - request?: protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.IPermission, + ( + | protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest + | undefined + ), + {} | undefined, + ] + >; createPermission( - request: protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.IPermission, + | protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createPermission( - request: protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.IPermission, + | protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createPermission( - request?: protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta3.IPermission, + | protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.IPermission, + ( + | protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest + | 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('createPermission request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta3.IPermission, + | protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createPermission response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createPermission(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest|undefined, - {}|undefined - ]) => { - this._log.info('createPermission response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createPermission(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta3.IPermission, + ( + | protos.google.ai.generativelanguage.v1beta3.ICreatePermissionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createPermission response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets information about a specific Permission. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the permission. - * - * Format: `tunedModels/{tuned_model}permissions/{permission}` - * @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.ai.generativelanguage.v1beta3.Permission|Permission}. - * 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/v1beta3/permission_service.get_permission.js - * region_tag:generativelanguage_v1beta3_generated_PermissionService_GetPermission_async - */ + /** + * Gets information about a specific Permission. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the permission. + * + * Format: `tunedModels/{tuned_model}permissions/{permission}` + * @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.ai.generativelanguage.v1beta3.Permission|Permission}. + * 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/v1beta3/permission_service.get_permission.js + * region_tag:generativelanguage_v1beta3_generated_PermissionService_GetPermission_async + */ getPermission( - request?: protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.IPermission, + ( + | protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest + | undefined + ), + {} | undefined, + ] + >; getPermission( - request: protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.IPermission, + | protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getPermission( - request: protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.IPermission, + | protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getPermission( - request?: protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta3.IPermission, + | protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.IPermission, + ( + | protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest + | 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('getPermission request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta3.IPermission, + | protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getPermission response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getPermission(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest|undefined, - {}|undefined - ]) => { - this._log.info('getPermission response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getPermission(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta3.IPermission, + ( + | protos.google.ai.generativelanguage.v1beta3.IGetPermissionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getPermission response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the permission. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.ai.generativelanguage.v1beta3.Permission} request.permission - * Required. The permission to update. - * - * The permission's `name` field is used to identify the permission to update. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to update. Accepted ones: - * - role (`Permission.role` 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 {@link protos.google.ai.generativelanguage.v1beta3.Permission|Permission}. - * 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/v1beta3/permission_service.update_permission.js - * region_tag:generativelanguage_v1beta3_generated_PermissionService_UpdatePermission_async - */ + /** + * Updates the permission. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.ai.generativelanguage.v1beta3.Permission} request.permission + * Required. The permission to update. + * + * The permission's `name` field is used to identify the permission to update. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to update. Accepted ones: + * - role (`Permission.role` 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 {@link protos.google.ai.generativelanguage.v1beta3.Permission|Permission}. + * 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/v1beta3/permission_service.update_permission.js + * region_tag:generativelanguage_v1beta3_generated_PermissionService_UpdatePermission_async + */ updatePermission( - request?: protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.IPermission, + ( + | protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest + | undefined + ), + {} | undefined, + ] + >; updatePermission( - request: protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.IPermission, + | protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updatePermission( - request: protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.IPermission, + | protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updatePermission( - request?: protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta3.IPermission, + | protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.IPermission, + ( + | protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest + | 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({ - 'permission.name': request.permission!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'permission.name': request.permission!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updatePermission request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta3.IPermission, + | protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updatePermission response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updatePermission(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta3.IPermission, - protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest|undefined, - {}|undefined - ]) => { - this._log.info('updatePermission response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updatePermission(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta3.IPermission, + ( + | protos.google.ai.generativelanguage.v1beta3.IUpdatePermissionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updatePermission response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes the permission. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the permission. - * Format: `tunedModels/{tuned_model}/permissions/{permission}` - * @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/v1beta3/permission_service.delete_permission.js - * region_tag:generativelanguage_v1beta3_generated_PermissionService_DeletePermission_async - */ + /** + * Deletes the permission. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the permission. + * Format: `tunedModels/{tuned_model}/permissions/{permission}` + * @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/v1beta3/permission_service.delete_permission.js + * region_tag:generativelanguage_v1beta3_generated_PermissionService_DeletePermission_async + */ deletePermission( - request?: protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest + | undefined + ), + {} | undefined, + ] + >; deletePermission( - request: protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deletePermission( - request: protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deletePermission( - request?: protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest + | 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('deletePermission request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deletePermission response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deletePermission(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest|undefined, - {}|undefined - ]) => { - this._log.info('deletePermission response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deletePermission(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.ai.generativelanguage.v1beta3.IDeletePermissionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deletePermission response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Transfers ownership of the tuned model. - * This is the only way to change ownership of the tuned model. - * The current owner will be downgraded to writer role. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the tuned model to transfer ownership . - * - * Format: `tunedModels/my-model-id` - * @param {string} request.emailAddress - * Required. The email address of the user to whom the tuned model is being - * transferred to. - * @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.ai.generativelanguage.v1beta3.TransferOwnershipResponse|TransferOwnershipResponse}. - * 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/v1beta3/permission_service.transfer_ownership.js - * region_tag:generativelanguage_v1beta3_generated_PermissionService_TransferOwnership_async - */ + /** + * Transfers ownership of the tuned model. + * This is the only way to change ownership of the tuned model. + * The current owner will be downgraded to writer role. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the tuned model to transfer ownership . + * + * Format: `tunedModels/my-model-id` + * @param {string} request.emailAddress + * Required. The email address of the user to whom the tuned model is being + * transferred to. + * @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.ai.generativelanguage.v1beta3.TransferOwnershipResponse|TransferOwnershipResponse}. + * 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/v1beta3/permission_service.transfer_ownership.js + * region_tag:generativelanguage_v1beta3_generated_PermissionService_TransferOwnership_async + */ transferOwnership( - request?: protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipResponse, + ( + | protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest + | undefined + ), + {} | undefined, + ] + >; transferOwnership( - request: protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipResponse, + | protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest + | null + | undefined, + {} | null | undefined + >, + ): void; transferOwnership( - request: protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipResponse, + | protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest + | null + | undefined, + {} | null | undefined + >, + ): void; transferOwnership( - request?: protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipResponse, + | protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipResponse, + ( + | protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest + | 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('transferOwnership request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipResponse, + | protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('transferOwnership response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.transferOwnership(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipResponse, - protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest|undefined, - {}|undefined - ]) => { - this._log.info('transferOwnership response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .transferOwnership(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipResponse, + ( + | protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('transferOwnership response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists permissions for the specific resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource of the permissions. - * Format: tunedModels/{tuned_model} - * @param {number} [request.pageSize] - * Optional. The maximum number of `Permission`s to return (per page). - * The service may return fewer permissions. - * - * If unspecified, at most 10 permissions will be returned. - * This method returns at most 1000 permissions per page, even if you pass - * larger page_size. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListPermissions` call. - * - * Provide the `page_token` returned by one request as an argument to the - * next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListPermissions` - * must match the call that provided the page token. - * @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.ai.generativelanguage.v1beta3.Permission|Permission}. - * 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 `listPermissionsAsync()` - * 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 permissions for the specific resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource of the permissions. + * Format: tunedModels/{tuned_model} + * @param {number} [request.pageSize] + * Optional. The maximum number of `Permission`s to return (per page). + * The service may return fewer permissions. + * + * If unspecified, at most 10 permissions will be returned. + * This method returns at most 1000 permissions per page, even if you pass + * larger page_size. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListPermissions` call. + * + * Provide the `page_token` returned by one request as an argument to the + * next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListPermissions` + * must match the call that provided the page token. + * @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.ai.generativelanguage.v1beta3.Permission|Permission}. + * 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 `listPermissionsAsync()` + * 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. + */ listPermissions( - request?: protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.IPermission[], - protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest|null, - protos.google.ai.generativelanguage.v1beta3.IListPermissionsResponse - ]>; + request?: protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.IPermission[], + protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest | null, + protos.google.ai.generativelanguage.v1beta3.IListPermissionsResponse, + ] + >; listPermissions( - request: protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest, - protos.google.ai.generativelanguage.v1beta3.IListPermissionsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta3.IPermission>): void; + request: protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest, + | protos.google.ai.generativelanguage.v1beta3.IListPermissionsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta3.IPermission + >, + ): void; listPermissions( - request: protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest, - callback: PaginationCallback< - protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest, - protos.google.ai.generativelanguage.v1beta3.IListPermissionsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta3.IPermission>): void; + request: protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest, + callback: PaginationCallback< + protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest, + | protos.google.ai.generativelanguage.v1beta3.IListPermissionsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta3.IPermission + >, + ): void; listPermissions( - request?: protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest, - protos.google.ai.generativelanguage.v1beta3.IListPermissionsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta3.IPermission>, - callback?: PaginationCallback< - protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest, - protos.google.ai.generativelanguage.v1beta3.IListPermissionsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta3.IPermission>): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.IPermission[], - protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest|null, - protos.google.ai.generativelanguage.v1beta3.IListPermissionsResponse - ]>|void { + | protos.google.ai.generativelanguage.v1beta3.IListPermissionsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta3.IPermission + >, + callback?: PaginationCallback< + protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest, + | protos.google.ai.generativelanguage.v1beta3.IListPermissionsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta3.IPermission + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.IPermission[], + protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest | null, + protos.google.ai.generativelanguage.v1beta3.IListPermissionsResponse, + ] + > | 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.ai.generativelanguage.v1beta3.IListPermissionsRequest, - protos.google.ai.generativelanguage.v1beta3.IListPermissionsResponse|null|undefined, - protos.google.ai.generativelanguage.v1beta3.IPermission>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest, + | protos.google.ai.generativelanguage.v1beta3.IListPermissionsResponse + | null + | undefined, + protos.google.ai.generativelanguage.v1beta3.IPermission + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listPermissions values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -930,130 +1253,134 @@ export class PermissionServiceClient { this._log.info('listPermissions request %j', request); return this.innerApiCalls .listPermissions(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.ai.generativelanguage.v1beta3.IPermission[], - protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest|null, - protos.google.ai.generativelanguage.v1beta3.IListPermissionsResponse - ]) => { - this._log.info('listPermissions values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.ai.generativelanguage.v1beta3.IPermission[], + protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest | null, + protos.google.ai.generativelanguage.v1beta3.IListPermissionsResponse, + ]) => { + this._log.info('listPermissions values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listPermissions`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource of the permissions. - * Format: tunedModels/{tuned_model} - * @param {number} [request.pageSize] - * Optional. The maximum number of `Permission`s to return (per page). - * The service may return fewer permissions. - * - * If unspecified, at most 10 permissions will be returned. - * This method returns at most 1000 permissions per page, even if you pass - * larger page_size. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListPermissions` call. - * - * Provide the `page_token` returned by one request as an argument to the - * next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListPermissions` - * must match the call that provided the page token. - * @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.ai.generativelanguage.v1beta3.Permission|Permission} 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 `listPermissionsAsync()` - * 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 `listPermissions`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource of the permissions. + * Format: tunedModels/{tuned_model} + * @param {number} [request.pageSize] + * Optional. The maximum number of `Permission`s to return (per page). + * The service may return fewer permissions. + * + * If unspecified, at most 10 permissions will be returned. + * This method returns at most 1000 permissions per page, even if you pass + * larger page_size. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListPermissions` call. + * + * Provide the `page_token` returned by one request as an argument to the + * next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListPermissions` + * must match the call that provided the page token. + * @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.ai.generativelanguage.v1beta3.Permission|Permission} 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 `listPermissionsAsync()` + * 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. + */ listPermissionsStream( - request?: protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest, + 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['listPermissions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listPermissions stream %j', request); return this.descriptors.page.listPermissions.createStream( this.innerApiCalls.listPermissions as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listPermissions`, 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 of the permissions. - * Format: tunedModels/{tuned_model} - * @param {number} [request.pageSize] - * Optional. The maximum number of `Permission`s to return (per page). - * The service may return fewer permissions. - * - * If unspecified, at most 10 permissions will be returned. - * This method returns at most 1000 permissions per page, even if you pass - * larger page_size. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListPermissions` call. - * - * Provide the `page_token` returned by one request as an argument to the - * next request to retrieve the next page. - * - * When paginating, all other parameters provided to `ListPermissions` - * must match the call that provided the 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 protos.google.ai.generativelanguage.v1beta3.Permission|Permission}. 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 include:samples/generated/v1beta3/permission_service.list_permissions.js - * region_tag:generativelanguage_v1beta3_generated_PermissionService_ListPermissions_async - */ + /** + * Equivalent to `listPermissions`, 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 of the permissions. + * Format: tunedModels/{tuned_model} + * @param {number} [request.pageSize] + * Optional. The maximum number of `Permission`s to return (per page). + * The service may return fewer permissions. + * + * If unspecified, at most 10 permissions will be returned. + * This method returns at most 1000 permissions per page, even if you pass + * larger page_size. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListPermissions` call. + * + * Provide the `page_token` returned by one request as an argument to the + * next request to retrieve the next page. + * + * When paginating, all other parameters provided to `ListPermissions` + * must match the call that provided the 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 protos.google.ai.generativelanguage.v1beta3.Permission|Permission}. 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 include:samples/generated/v1beta3/permission_service.list_permissions.js + * region_tag:generativelanguage_v1beta3_generated_PermissionService_ListPermissions_async + */ listPermissionsAsync( - request?: protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.ai.generativelanguage.v1beta3.IListPermissionsRequest, + 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['listPermissions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listPermissions iterate %j', request); return this.descriptors.page.listPermissions.asyncIterate( this.innerApiCalls['listPermissions'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1066,7 +1393,7 @@ export class PermissionServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -1090,7 +1417,7 @@ export class PermissionServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - permissionPath(tunedModel:string,permission:string) { + permissionPath(tunedModel: string, permission: string) { return this.pathTemplates.permissionPathTemplate.render({ tuned_model: tunedModel, permission: permission, @@ -1105,7 +1432,8 @@ export class PermissionServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromPermissionName(permissionName: string) { - return this.pathTemplates.permissionPathTemplate.match(permissionName).tuned_model; + return this.pathTemplates.permissionPathTemplate.match(permissionName) + .tuned_model; } /** @@ -1116,7 +1444,8 @@ export class PermissionServiceClient { * @returns {string} A string representing the permission. */ matchPermissionFromPermissionName(permissionName: string) { - return this.pathTemplates.permissionPathTemplate.match(permissionName).permission; + return this.pathTemplates.permissionPathTemplate.match(permissionName) + .permission; } /** @@ -1125,7 +1454,7 @@ export class PermissionServiceClient { * @param {string} tuned_model * @returns {string} Resource name string. */ - tunedModelPath(tunedModel:string) { + tunedModelPath(tunedModel: string) { return this.pathTemplates.tunedModelPathTemplate.render({ tuned_model: tunedModel, }); @@ -1139,7 +1468,8 @@ export class PermissionServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromTunedModelName(tunedModelName: string) { - return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName).tuned_model; + return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName) + .tuned_model; } /** @@ -1150,7 +1480,7 @@ export class PermissionServiceClient { */ close(): Promise { if (this.permissionServiceStub && !this._terminated) { - return this.permissionServiceStub.then(stub => { + return this.permissionServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1158,4 +1488,4 @@ export class PermissionServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/src/v1beta3/text_service_client.ts b/packages/google-ai-generativelanguage/src/v1beta3/text_service_client.ts index d56cb7bc0fd4..a7d0bdc72d85 100644 --- a/packages/google-ai-generativelanguage/src/v1beta3/text_service_client.ts +++ b/packages/google-ai-generativelanguage/src/v1beta3/text_service_client.ts @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +52,7 @@ export class TextServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('generativelanguage'); @@ -60,9 +65,9 @@ export class TextServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - textServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + textServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of TextServiceClient. @@ -103,21 +108,42 @@ export class TextServiceClient { * const client = new TextServiceClient({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 TextServiceClient; - 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 = 'generativelanguage.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -142,7 +168,7 @@ export class TextServiceClient { 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; @@ -156,10 +182,7 @@ export class TextServiceClient { } // 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 { @@ -180,21 +203,22 @@ export class TextServiceClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { - modelPathTemplate: new this._gaxModule.PathTemplate( - 'models/{model}' - ), + modelPathTemplate: new this._gaxModule.PathTemplate('models/{model}'), permissionPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}/permissions/{permission}' + 'tunedModels/{tuned_model}/permissions/{permission}', ), tunedModelPathTemplate: new this._gaxModule.PathTemplate( - 'tunedModels/{tuned_model}' + 'tunedModels/{tuned_model}', ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.ai.generativelanguage.v1beta3.TextService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.ai.generativelanguage.v1beta3.TextService', + 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 @@ -225,36 +249,46 @@ export class TextServiceClient { // Put together the "service stub" for // google.ai.generativelanguage.v1beta3.TextService. this.textServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.ai.generativelanguage.v1beta3.TextService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.ai.generativelanguage.v1beta3.TextService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.ai.generativelanguage.v1beta3.TextService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.ai.generativelanguage.v1beta3 + .TextService, + 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 textServiceStubMethods = - ['generateText', 'embedText', 'batchEmbedText', 'countTextTokens']; + const textServiceStubMethods = [ + 'generateText', + 'embedText', + 'batchEmbedText', + 'countTextTokens', + ]; for (const methodName of textServiceStubMethods) { const callPromise = this.textServiceStub.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 = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -269,8 +303,14 @@ export class TextServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -281,8 +321,14 @@ export class TextServiceClient { * @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 'generativelanguage.googleapis.com'; } @@ -322,8 +368,9 @@ export class TextServiceClient { * 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; @@ -334,461 +381,651 @@ export class TextServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Generates a response from the model given an input message. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The name of the `Model` or `TunedModel` to use for generating the - * completion. - * Examples: - * models/text-bison-001 - * tunedModels/sentence-translator-u3b7m - * @param {google.ai.generativelanguage.v1beta3.TextPrompt} request.prompt - * Required. The free-form input text given to the model as a prompt. - * - * Given a prompt, the model will generate a TextCompletion response it - * predicts as the completion of the input text. - * @param {number} [request.temperature] - * Optional. Controls the randomness of the output. - * Note: The default value varies by model, see the `Model.temperature` - * attribute of the `Model` returned the `getModel` function. - * - * Values can range from [0.0,1.0], - * inclusive. A value closer to 1.0 will produce responses that are more - * varied and creative, while a value closer to 0.0 will typically result in - * more straightforward responses from the model. - * @param {number} [request.candidateCount] - * Optional. Number of generated responses to return. - * - * This value must be between [1, 8], inclusive. If unset, this will default - * to 1. - * @param {number} [request.maxOutputTokens] - * Optional. The maximum number of tokens to include in a candidate. - * - * If unset, this will default to output_token_limit specified in the `Model` - * specification. - * @param {number} [request.topP] - * Optional. The maximum cumulative probability of tokens to consider when - * sampling. - * - * The model uses combined Top-k and nucleus sampling. - * - * Tokens are sorted based on their assigned probabilities so that only the - * most likely tokens are considered. Top-k sampling directly limits the - * maximum number of tokens to consider, while Nucleus sampling limits number - * of tokens based on the cumulative probability. - * - * Note: The default value varies by model, see the `Model.top_p` - * attribute of the `Model` returned the `getModel` function. - * @param {number} [request.topK] - * Optional. The maximum number of tokens to consider when sampling. - * - * The model uses combined Top-k and nucleus sampling. - * - * Top-k sampling considers the set of `top_k` most probable tokens. - * Defaults to 40. - * - * Note: The default value varies by model, see the `Model.top_k` - * attribute of the `Model` returned the `getModel` function. - * @param {number[]} request.safetySettings - * A list of unique `SafetySetting` instances for blocking unsafe content. - * - * that will be enforced on the `GenerateTextRequest.prompt` and - * `GenerateTextResponse.candidates`. There should not be more than one - * setting for each `SafetyCategory` type. The API will block any prompts and - * responses that fail to meet the thresholds set by these settings. This list - * overrides the default settings for each `SafetyCategory` specified in the - * safety_settings. If there is no `SafetySetting` for a given - * `SafetyCategory` provided in the list, the API will use the default safety - * setting for that category. - * @param {string[]} request.stopSequences - * The set of character sequences (up to 5) that will stop output generation. - * If specified, the API will stop at the first appearance of a stop - * sequence. The stop sequence will not be included as part of 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.ai.generativelanguage.v1beta3.GenerateTextResponse|GenerateTextResponse}. - * 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/v1beta3/text_service.generate_text.js - * region_tag:generativelanguage_v1beta3_generated_TextService_GenerateText_async - */ + /** + * Generates a response from the model given an input message. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The name of the `Model` or `TunedModel` to use for generating the + * completion. + * Examples: + * models/text-bison-001 + * tunedModels/sentence-translator-u3b7m + * @param {google.ai.generativelanguage.v1beta3.TextPrompt} request.prompt + * Required. The free-form input text given to the model as a prompt. + * + * Given a prompt, the model will generate a TextCompletion response it + * predicts as the completion of the input text. + * @param {number} [request.temperature] + * Optional. Controls the randomness of the output. + * Note: The default value varies by model, see the `Model.temperature` + * attribute of the `Model` returned the `getModel` function. + * + * Values can range from [0.0,1.0], + * inclusive. A value closer to 1.0 will produce responses that are more + * varied and creative, while a value closer to 0.0 will typically result in + * more straightforward responses from the model. + * @param {number} [request.candidateCount] + * Optional. Number of generated responses to return. + * + * This value must be between [1, 8], inclusive. If unset, this will default + * to 1. + * @param {number} [request.maxOutputTokens] + * Optional. The maximum number of tokens to include in a candidate. + * + * If unset, this will default to output_token_limit specified in the `Model` + * specification. + * @param {number} [request.topP] + * Optional. The maximum cumulative probability of tokens to consider when + * sampling. + * + * The model uses combined Top-k and nucleus sampling. + * + * Tokens are sorted based on their assigned probabilities so that only the + * most likely tokens are considered. Top-k sampling directly limits the + * maximum number of tokens to consider, while Nucleus sampling limits number + * of tokens based on the cumulative probability. + * + * Note: The default value varies by model, see the `Model.top_p` + * attribute of the `Model` returned the `getModel` function. + * @param {number} [request.topK] + * Optional. The maximum number of tokens to consider when sampling. + * + * The model uses combined Top-k and nucleus sampling. + * + * Top-k sampling considers the set of `top_k` most probable tokens. + * Defaults to 40. + * + * Note: The default value varies by model, see the `Model.top_k` + * attribute of the `Model` returned the `getModel` function. + * @param {number[]} request.safetySettings + * A list of unique `SafetySetting` instances for blocking unsafe content. + * + * that will be enforced on the `GenerateTextRequest.prompt` and + * `GenerateTextResponse.candidates`. There should not be more than one + * setting for each `SafetyCategory` type. The API will block any prompts and + * responses that fail to meet the thresholds set by these settings. This list + * overrides the default settings for each `SafetyCategory` specified in the + * safety_settings. If there is no `SafetySetting` for a given + * `SafetyCategory` provided in the list, the API will use the default safety + * setting for that category. + * @param {string[]} request.stopSequences + * The set of character sequences (up to 5) that will stop output generation. + * If specified, the API will stop at the first appearance of a stop + * sequence. The stop sequence will not be included as part of 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.ai.generativelanguage.v1beta3.GenerateTextResponse|GenerateTextResponse}. + * 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/v1beta3/text_service.generate_text.js + * region_tag:generativelanguage_v1beta3_generated_TextService_GenerateText_async + */ generateText( - request?: protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.IGenerateTextResponse, + ( + | protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest + | undefined + ), + {} | undefined, + ] + >; generateText( - request: protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.IGenerateTextResponse, + | protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateText( - request: protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.IGenerateTextResponse, + | protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; generateText( - request?: protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta3.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1beta3.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta3.IGenerateTextResponse, + | protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.IGenerateTextResponse, + ( + | protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('generateText request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta3.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta3.IGenerateTextResponse, + | protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('generateText response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.generateText(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta3.IGenerateTextResponse, - protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest|undefined, - {}|undefined - ]) => { - this._log.info('generateText response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .generateText(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta3.IGenerateTextResponse, + ( + | protos.google.ai.generativelanguage.v1beta3.IGenerateTextRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('generateText response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Generates an embedding from the model given an input message. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The model name to use with the format model=models/{model}. - * @param {string} request.text - * Required. The free-form input text that the model will turn into an - * embedding. - * @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.ai.generativelanguage.v1beta3.EmbedTextResponse|EmbedTextResponse}. - * 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/v1beta3/text_service.embed_text.js - * region_tag:generativelanguage_v1beta3_generated_TextService_EmbedText_async - */ + /** + * Generates an embedding from the model given an input message. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The model name to use with the format model=models/{model}. + * @param {string} request.text + * Required. The free-form input text that the model will turn into an + * embedding. + * @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.ai.generativelanguage.v1beta3.EmbedTextResponse|EmbedTextResponse}. + * 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/v1beta3/text_service.embed_text.js + * region_tag:generativelanguage_v1beta3_generated_TextService_EmbedText_async + */ embedText( - request?: protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.IEmbedTextResponse, + protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest | undefined, + {} | undefined, + ] + >; embedText( - request: protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.IEmbedTextResponse, + | protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; embedText( - request: protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.IEmbedTextResponse, + | protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; embedText( - request?: protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta3.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1beta3.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta3.IEmbedTextResponse, + | protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.IEmbedTextResponse, + protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('embedText request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta3.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta3.IEmbedTextResponse, + | protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('embedText response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.embedText(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta3.IEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest|undefined, - {}|undefined - ]) => { - this._log.info('embedText response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .embedText(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta3.IEmbedTextResponse, + ( + | protos.google.ai.generativelanguage.v1beta3.IEmbedTextRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('embedText response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Generates multiple embeddings from the model given input text in a - * synchronous call. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The name of the `Model` to use for generating the embedding. - * Examples: - * models/embedding-gecko-001 - * @param {string[]} request.texts - * Required. The free-form input texts that the model will turn into an - * embedding. The current limit is 100 texts, over which an error will be - * thrown. - * @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.ai.generativelanguage.v1beta3.BatchEmbedTextResponse|BatchEmbedTextResponse}. - * 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/v1beta3/text_service.batch_embed_text.js - * region_tag:generativelanguage_v1beta3_generated_TextService_BatchEmbedText_async - */ + /** + * Generates multiple embeddings from the model given input text in a + * synchronous call. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The name of the `Model` to use for generating the embedding. + * Examples: + * models/embedding-gecko-001 + * @param {string[]} request.texts + * Required. The free-form input texts that the model will turn into an + * embedding. The current limit is 100 texts, over which an error will be + * thrown. + * @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.ai.generativelanguage.v1beta3.BatchEmbedTextResponse|BatchEmbedTextResponse}. + * 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/v1beta3/text_service.batch_embed_text.js + * region_tag:generativelanguage_v1beta3_generated_TextService_BatchEmbedText_async + */ batchEmbedText( - request?: protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextResponse, + ( + | protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest + | undefined + ), + {} | undefined, + ] + >; batchEmbedText( - request: protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextResponse, + | protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchEmbedText( - request: protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextResponse, + | protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchEmbedText( - request?: protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextResponse, + | protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextResponse, + ( + | protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('batchEmbedText request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextResponse, + | protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchEmbedText response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.batchEmbedText(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextResponse, - protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest|undefined, - {}|undefined - ]) => { - this._log.info('batchEmbedText response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchEmbedText(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextResponse, + ( + | protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchEmbedText response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Runs a model's tokenizer on a text and returns the token count. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.model - * Required. The model's resource name. This serves as an ID for the Model to - * use. - * - * This name should match a model name returned by the `ListModels` method. - * - * Format: `models/{model}` - * @param {google.ai.generativelanguage.v1beta3.TextPrompt} request.prompt - * Required. The free-form input text given to the model as a prompt. - * @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.ai.generativelanguage.v1beta3.CountTextTokensResponse|CountTextTokensResponse}. - * 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/v1beta3/text_service.count_text_tokens.js - * region_tag:generativelanguage_v1beta3_generated_TextService_CountTextTokens_async - */ + /** + * Runs a model's tokenizer on a text and returns the token count. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.model + * Required. The model's resource name. This serves as an ID for the Model to + * use. + * + * This name should match a model name returned by the `ListModels` method. + * + * Format: `models/{model}` + * @param {google.ai.generativelanguage.v1beta3.TextPrompt} request.prompt + * Required. The free-form input text given to the model as a prompt. + * @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.ai.generativelanguage.v1beta3.CountTextTokensResponse|CountTextTokensResponse}. + * 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/v1beta3/text_service.count_text_tokens.js + * region_tag:generativelanguage_v1beta3_generated_TextService_CountTextTokens_async + */ countTextTokens( - request?: protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest, - options?: CallOptions): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest|undefined, {}|undefined - ]>; + request?: protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.ICountTextTokensResponse, + ( + | protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest + | undefined + ), + {} | undefined, + ] + >; countTextTokens( - request: protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest, - options: CallOptions, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest, + options: CallOptions, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.ICountTextTokensResponse, + | protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): void; countTextTokens( - request: protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest, - callback: Callback< - protos.google.ai.generativelanguage.v1beta3.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest, + callback: Callback< + protos.google.ai.generativelanguage.v1beta3.ICountTextTokensResponse, + | protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): void; countTextTokens( - request?: protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.ai.generativelanguage.v1beta3.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.ai.generativelanguage.v1beta3.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.ai.generativelanguage.v1beta3.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest|undefined, {}|undefined - ]>|void { + | protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.ai.generativelanguage.v1beta3.ICountTextTokensResponse, + | protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.ai.generativelanguage.v1beta3.ICountTextTokensResponse, + ( + | protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest + | 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({ - 'model': request.model ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + model: request.model ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('countTextTokens request %j', request); - const wrappedCallback: Callback< - protos.google.ai.generativelanguage.v1beta3.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.ai.generativelanguage.v1beta3.ICountTextTokensResponse, + | protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('countTextTokens response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.countTextTokens(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.ai.generativelanguage.v1beta3.ICountTextTokensResponse, - protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest|undefined, - {}|undefined - ]) => { - this._log.info('countTextTokens response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .countTextTokens(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.ai.generativelanguage.v1beta3.ICountTextTokensResponse, + ( + | protos.google.ai.generativelanguage.v1beta3.ICountTextTokensRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('countTextTokens response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -804,7 +1041,7 @@ export class TextServiceClient { * @param {string} model * @returns {string} Resource name string. */ - modelPath(model:string) { + modelPath(model: string) { return this.pathTemplates.modelPathTemplate.render({ model: model, }); @@ -828,7 +1065,7 @@ export class TextServiceClient { * @param {string} permission * @returns {string} Resource name string. */ - permissionPath(tunedModel:string,permission:string) { + permissionPath(tunedModel: string, permission: string) { return this.pathTemplates.permissionPathTemplate.render({ tuned_model: tunedModel, permission: permission, @@ -843,7 +1080,8 @@ export class TextServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromPermissionName(permissionName: string) { - return this.pathTemplates.permissionPathTemplate.match(permissionName).tuned_model; + return this.pathTemplates.permissionPathTemplate.match(permissionName) + .tuned_model; } /** @@ -854,7 +1092,8 @@ export class TextServiceClient { * @returns {string} A string representing the permission. */ matchPermissionFromPermissionName(permissionName: string) { - return this.pathTemplates.permissionPathTemplate.match(permissionName).permission; + return this.pathTemplates.permissionPathTemplate.match(permissionName) + .permission; } /** @@ -863,7 +1102,7 @@ export class TextServiceClient { * @param {string} tuned_model * @returns {string} Resource name string. */ - tunedModelPath(tunedModel:string) { + tunedModelPath(tunedModel: string) { return this.pathTemplates.tunedModelPathTemplate.render({ tuned_model: tunedModel, }); @@ -877,7 +1116,8 @@ export class TextServiceClient { * @returns {string} A string representing the tuned_model. */ matchTunedModelFromTunedModelName(tunedModelName: string) { - return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName).tuned_model; + return this.pathTemplates.tunedModelPathTemplate.match(tunedModelName) + .tuned_model; } /** @@ -888,7 +1128,7 @@ export class TextServiceClient { */ close(): Promise { if (this.textServiceStub && !this._terminated) { - return this.textServiceStub.then(stub => { + return this.textServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -896,4 +1136,4 @@ export class TextServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-ai-generativelanguage/system-test/fixtures/sample/src/index.ts b/packages/google-ai-generativelanguage/system-test/fixtures/sample/src/index.ts index 8eca60bc6cf2..fc1d44f5c99f 100644 --- a/packages/google-ai-generativelanguage/system-test/fixtures/sample/src/index.ts +++ b/packages/google-ai-generativelanguage/system-test/fixtures/sample/src/index.ts @@ -16,7 +16,17 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {CacheServiceClient, DiscussServiceClient, FileServiceClient, GenerativeServiceClient, ModelServiceClient, PermissionServiceClient, PredictionServiceClient, RetrieverServiceClient, TextServiceClient} from '@google-ai/generativelanguage'; +import { + CacheServiceClient, + DiscussServiceClient, + FileServiceClient, + GenerativeServiceClient, + ModelServiceClient, + PermissionServiceClient, + PredictionServiceClient, + RetrieverServiceClient, + TextServiceClient, +} from '@google-ai/generativelanguage'; // check that the client class type name can be used function doStuffWithCacheServiceClient(client: CacheServiceClient) { diff --git a/packages/google-ai-generativelanguage/system-test/install.ts b/packages/google-ai-generativelanguage/system-test/install.ts index 394f3362d203..ccf167042d2e 100644 --- a/packages/google-ai-generativelanguage/system-test/install.ts +++ b/packages/google-ai-generativelanguage/system-test/install.ts @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - ts: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/packages/google-ai-generativelanguage/test/gapic_cache_service_v1alpha.ts b/packages/google-ai-generativelanguage/test/gapic_cache_service_v1alpha.ts index 197337d04b8b..36341a4e2ff1 100644 --- a/packages/google-ai-generativelanguage/test/gapic_cache_service_v1alpha.ts +++ b/packages/google-ai-generativelanguage/test/gapic_cache_service_v1alpha.ts @@ -19,1134 +19,1464 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as cacheserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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 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('v1alpha.CacheServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient(); - 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 = cacheserviceModule.v1alpha.CacheServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = cacheserviceModule.v1alpha.CacheServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); + it('has universeDomain', () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.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 cacheserviceModule.v1alpha.CacheServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 cacheserviceModule.v1alpha.CacheServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 cacheserviceModule.v1alpha.CacheServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + cacheserviceModule.v1alpha.CacheServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + cacheserviceModule.v1alpha.CacheServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('has port', () => { - const port = cacheserviceModule.v1alpha.CacheServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('should create a client with no option', () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient(); - assert(client); + 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 cacheserviceModule.v1alpha.CacheServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with gRPC fallback', () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - fallback: true, - }); - assert(client); + 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 cacheserviceModule.v1alpha.CacheServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.cacheServiceStub, undefined); - await client.initialize(); - assert(client.cacheServiceStub); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new cacheserviceModule.v1alpha.CacheServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has close method for the initialized client', done => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.cacheServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = cacheserviceModule.v1alpha.CacheServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the non-initialized client', done => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.cacheServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient(); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - 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('should create a client with gRPC fallback', () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - 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('has initialize method and supports deferred initialization', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.cacheServiceStub, undefined); + await client.initialize(); + assert(client.cacheServiceStub); }); - describe('createCachedContent', () => { - it('invokes createCachedContent without error', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateCachedContentRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CachedContent() - ); - client.innerApiCalls.createCachedContent = stubSimpleCall(expectedResponse); - const [response] = await client.createCachedContent(request); - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the initialized client', (done) => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.cacheServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createCachedContent without error using callback', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateCachedContentRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CachedContent() - ); - client.innerApiCalls.createCachedContent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createCachedContent( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.ICachedContent|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the non-initialized client', (done) => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.cacheServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createCachedContent with error', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateCachedContentRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createCachedContent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createCachedContent(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + 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 createCachedContent with closed client', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateCachedContentRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createCachedContent(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + 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('createCachedContent', () => { + it('invokes createCachedContent without error', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateCachedContentRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CachedContent(), + ); + client.innerApiCalls.createCachedContent = + stubSimpleCall(expectedResponse); + const [response] = await client.createCachedContent(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('getCachedContent', () => { - it('invokes getCachedContent without error', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetCachedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetCachedContentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CachedContent() - ); - client.innerApiCalls.getCachedContent = stubSimpleCall(expectedResponse); - const [response] = await client.getCachedContent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCachedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCachedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createCachedContent without error using callback', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateCachedContentRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CachedContent(), + ); + client.innerApiCalls.createCachedContent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createCachedContent( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.ICachedContent | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes getCachedContent without error using callback', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetCachedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetCachedContentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CachedContent() - ); - client.innerApiCalls.getCachedContent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getCachedContent( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.ICachedContent|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCachedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCachedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createCachedContent with error', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateCachedContentRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createCachedContent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createCachedContent(request), expectedError); + }); - it('invokes getCachedContent with error', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetCachedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetCachedContentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getCachedContent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getCachedContent(request), expectedError); - const actualRequest = (client.innerApiCalls.getCachedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCachedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createCachedContent with closed client', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateCachedContentRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createCachedContent(request), expectedError); + }); + }); + + describe('getCachedContent', () => { + it('invokes getCachedContent without error', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetCachedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetCachedContentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CachedContent(), + ); + client.innerApiCalls.getCachedContent = stubSimpleCall(expectedResponse); + const [response] = await client.getCachedContent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCachedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCachedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getCachedContent with closed client', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetCachedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetCachedContentRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getCachedContent(request), expectedError); - }); + it('invokes getCachedContent without error using callback', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetCachedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetCachedContentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CachedContent(), + ); + client.innerApiCalls.getCachedContent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getCachedContent( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.ICachedContent | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCachedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCachedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateCachedContent', () => { - it('invokes updateCachedContent without error', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdateCachedContentRequest() - ); - request.cachedContent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.UpdateCachedContentRequest', ['cachedContent', 'name']); - request.cachedContent.name = defaultValue1; - const expectedHeaderRequestParams = `cached_content.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CachedContent() - ); - client.innerApiCalls.updateCachedContent = stubSimpleCall(expectedResponse); - const [response] = await client.updateCachedContent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCachedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCachedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getCachedContent with error', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetCachedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetCachedContentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getCachedContent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getCachedContent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getCachedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCachedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateCachedContent without error using callback', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdateCachedContentRequest() - ); - request.cachedContent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.UpdateCachedContentRequest', ['cachedContent', 'name']); - request.cachedContent.name = defaultValue1; - const expectedHeaderRequestParams = `cached_content.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CachedContent() - ); - client.innerApiCalls.updateCachedContent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateCachedContent( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.ICachedContent|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCachedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCachedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getCachedContent with closed client', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetCachedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetCachedContentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getCachedContent(request), expectedError); + }); + }); + + describe('updateCachedContent', () => { + it('invokes updateCachedContent without error', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdateCachedContentRequest(), + ); + request.cachedContent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.UpdateCachedContentRequest', + ['cachedContent', 'name'], + ); + request.cachedContent.name = defaultValue1; + const expectedHeaderRequestParams = `cached_content.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CachedContent(), + ); + client.innerApiCalls.updateCachedContent = + stubSimpleCall(expectedResponse); + const [response] = await client.updateCachedContent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCachedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCachedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateCachedContent with error', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdateCachedContentRequest() - ); - request.cachedContent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.UpdateCachedContentRequest', ['cachedContent', 'name']); - request.cachedContent.name = defaultValue1; - const expectedHeaderRequestParams = `cached_content.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateCachedContent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateCachedContent(request), expectedError); - const actualRequest = (client.innerApiCalls.updateCachedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCachedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateCachedContent without error using callback', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdateCachedContentRequest(), + ); + request.cachedContent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.UpdateCachedContentRequest', + ['cachedContent', 'name'], + ); + request.cachedContent.name = defaultValue1; + const expectedHeaderRequestParams = `cached_content.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CachedContent(), + ); + client.innerApiCalls.updateCachedContent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateCachedContent( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.ICachedContent | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCachedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCachedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateCachedContent with closed client', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdateCachedContentRequest() - ); - request.cachedContent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.UpdateCachedContentRequest', ['cachedContent', 'name']); - request.cachedContent.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateCachedContent(request), expectedError); - }); + it('invokes updateCachedContent with error', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdateCachedContentRequest(), + ); + request.cachedContent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.UpdateCachedContentRequest', + ['cachedContent', 'name'], + ); + request.cachedContent.name = defaultValue1; + const expectedHeaderRequestParams = `cached_content.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateCachedContent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateCachedContent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateCachedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCachedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteCachedContent', () => { - it('invokes deleteCachedContent without error', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteCachedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeleteCachedContentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteCachedContent = stubSimpleCall(expectedResponse); - const [response] = await client.deleteCachedContent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteCachedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteCachedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateCachedContent with closed client', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdateCachedContentRequest(), + ); + request.cachedContent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.UpdateCachedContentRequest', + ['cachedContent', 'name'], + ); + request.cachedContent.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateCachedContent(request), expectedError); + }); + }); + + describe('deleteCachedContent', () => { + it('invokes deleteCachedContent without error', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteCachedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeleteCachedContentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteCachedContent = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteCachedContent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteCachedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteCachedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteCachedContent without error using callback', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteCachedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeleteCachedContentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteCachedContent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteCachedContent( - 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.deleteCachedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteCachedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteCachedContent without error using callback', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteCachedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeleteCachedContentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteCachedContent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteCachedContent( + 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.deleteCachedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteCachedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteCachedContent with error', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteCachedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeleteCachedContentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteCachedContent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteCachedContent(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteCachedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteCachedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteCachedContent with error', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteCachedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeleteCachedContentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteCachedContent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteCachedContent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteCachedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteCachedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteCachedContent with closed client', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteCachedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeleteCachedContentRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteCachedContent(request), expectedError); - }); + it('invokes deleteCachedContent with closed client', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteCachedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeleteCachedContentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteCachedContent(request), expectedError); + }); + }); + + describe('listCachedContents', () => { + it('invokes listCachedContents without error', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListCachedContentsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CachedContent(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CachedContent(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CachedContent(), + ), + ]; + client.innerApiCalls.listCachedContents = + stubSimpleCall(expectedResponse); + const [response] = await client.listCachedContents(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('listCachedContents', () => { - it('invokes listCachedContents without error', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListCachedContentsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.CachedContent()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.CachedContent()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.CachedContent()), - ]; - client.innerApiCalls.listCachedContents = stubSimpleCall(expectedResponse); - const [response] = await client.listCachedContents(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listCachedContents without error using callback', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListCachedContentsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CachedContent(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CachedContent(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CachedContent(), + ), + ]; + client.innerApiCalls.listCachedContents = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listCachedContents( + request, + ( + err?: Error | null, + result?: + | protos.google.ai.generativelanguage.v1alpha.ICachedContent[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes listCachedContents without error using callback', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListCachedContentsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.CachedContent()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.CachedContent()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.CachedContent()), - ]; - client.innerApiCalls.listCachedContents = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listCachedContents( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.ICachedContent[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listCachedContents with error', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListCachedContentsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listCachedContents = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listCachedContents(request), expectedError); + }); - it('invokes listCachedContents with error', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListCachedContentsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listCachedContents = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listCachedContents(request), expectedError); + it('invokes listCachedContentsStream without error', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListCachedContentsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CachedContent(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CachedContent(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CachedContent(), + ), + ]; + client.descriptors.page.listCachedContents.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listCachedContentsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1alpha.CachedContent[] = + []; + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1alpha.CachedContent, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listCachedContentsStream without error', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListCachedContentsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.CachedContent()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.CachedContent()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.CachedContent()), - ]; - client.descriptors.page.listCachedContents.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listCachedContentsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1alpha.CachedContent[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1alpha.CachedContent) => { - 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.listCachedContents.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCachedContents, request)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listCachedContents.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCachedContents, request), + ); + }); - it('invokes listCachedContentsStream with error', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListCachedContentsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listCachedContents.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listCachedContentsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1alpha.CachedContent[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1alpha.CachedContent) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listCachedContents.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCachedContents, request)); + it('invokes listCachedContentsStream with error', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListCachedContentsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listCachedContents.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listCachedContentsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1alpha.CachedContent[] = + []; + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1alpha.CachedContent, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with listCachedContents without error', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListCachedContentsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.CachedContent()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.CachedContent()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.CachedContent()), - ]; - client.descriptors.page.listCachedContents.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ai.generativelanguage.v1alpha.ICachedContent[] = []; - const iterable = client.listCachedContentsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listCachedContents.asyncIterate as SinonStub) - .getCall(0).args[1], request); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listCachedContents.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCachedContents, request), + ); + }); - it('uses async iteration with listCachedContents with error', async () => { - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListCachedContentsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listCachedContents.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listCachedContentsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ai.generativelanguage.v1alpha.ICachedContent[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listCachedContents.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('uses async iteration with listCachedContents without error', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListCachedContentsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CachedContent(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CachedContent(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CachedContent(), + ), + ]; + client.descriptors.page.listCachedContents.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ai.generativelanguage.v1alpha.ICachedContent[] = + []; + const iterable = client.listCachedContentsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listCachedContents.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); }); - describe('Path templates', () => { - - describe('cachedContent', async () => { - const fakePath = "/rendered/path/cachedContent"; - const expectedParameters = { - id: "idValue", - }; - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.cachedContentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.cachedContentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('cachedContentPath', () => { - const result = client.cachedContentPath("idValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.cachedContentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchIdFromCachedContentName', () => { - const result = client.matchIdFromCachedContentName(fakePath); - assert.strictEqual(result, "idValue"); - assert((client.pathTemplates.cachedContentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listCachedContents with error', async () => { + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListCachedContentsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listCachedContents.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listCachedContentsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ai.generativelanguage.v1alpha.ICachedContent[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listCachedContents.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('cachedContent', async () => { + const fakePath = '/rendered/path/cachedContent'; + const expectedParameters = { + id: 'idValue', + }; + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.cachedContentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.cachedContentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('cachedContentPath', () => { + const result = client.cachedContentPath('idValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.cachedContentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchIdFromCachedContentName', () => { + const result = client.matchIdFromCachedContentName(fakePath); + assert.strictEqual(result, 'idValue'); + assert( + (client.pathTemplates.cachedContentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('chunk', async () => { - const fakePath = "/rendered/path/chunk"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - chunk: "chunkValue", - }; - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.chunkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.chunkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('chunkPath', () => { - const result = client.chunkPath("corpusValue", "documentValue", "chunkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.chunkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromChunkName', () => { - const result = client.matchCorpusFromChunkName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromChunkName', () => { - const result = client.matchDocumentFromChunkName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChunkFromChunkName', () => { - const result = client.matchChunkFromChunkName(fakePath); - assert.strictEqual(result, "chunkValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('chunk', async () => { + const fakePath = '/rendered/path/chunk'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + chunk: 'chunkValue', + }; + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.chunkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.chunkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('chunkPath', () => { + const result = client.chunkPath( + 'corpusValue', + 'documentValue', + 'chunkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.chunkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromChunkName', () => { + const result = client.matchCorpusFromChunkName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromChunkName', () => { + const result = client.matchDocumentFromChunkName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChunkFromChunkName', () => { + const result = client.matchChunkFromChunkName(fakePath); + assert.strictEqual(result, 'chunkValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('corpus', async () => { - const fakePath = "/rendered/path/corpus"; - const expectedParameters = { - corpus: "corpusValue", - }; - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPath', () => { - const result = client.corpusPath("corpusValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusName', () => { - const result = client.matchCorpusFromCorpusName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpus', async () => { + const fakePath = '/rendered/path/corpus'; + const expectedParameters = { + corpus: 'corpusValue', + }; + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPath', () => { + const result = client.corpusPath('corpusValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.corpusPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusName', () => { + const result = client.matchCorpusFromCorpusName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.corpusPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('corpusPermissions', async () => { - const fakePath = "/rendered/path/corpusPermissions"; - const expectedParameters = { - corpus: "corpusValue", - permission: "permissionValue", - }; - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPermissionsPath', () => { - const result = client.corpusPermissionsPath("corpusValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusPermissionsName', () => { - const result = client.matchCorpusFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromCorpusPermissionsName', () => { - const result = client.matchPermissionFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpusPermissions', async () => { + const fakePath = '/rendered/path/corpusPermissions'; + const expectedParameters = { + corpus: 'corpusValue', + permission: 'permissionValue', + }; + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPermissionsPath', () => { + const result = client.corpusPermissionsPath( + 'corpusValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusPermissionsName', () => { + const result = client.matchCorpusFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromCorpusPermissionsName', () => { + const result = + client.matchPermissionFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('document', async () => { - const fakePath = "/rendered/path/document"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - }; - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.documentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.documentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('documentPath', () => { - const result = client.documentPath("corpusValue", "documentValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.documentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromDocumentName', () => { - const result = client.matchCorpusFromDocumentName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromDocumentName', () => { - const result = client.matchDocumentFromDocumentName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('document', async () => { + const fakePath = '/rendered/path/document'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + }; + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.documentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.documentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('documentPath', () => { + const result = client.documentPath('corpusValue', 'documentValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.documentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromDocumentName', () => { + const result = client.matchCorpusFromDocumentName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromDocumentName', () => { + const result = client.matchDocumentFromDocumentName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('file', async () => { - const fakePath = "/rendered/path/file"; - const expectedParameters = { - file: "fileValue", - }; - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.filePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.filePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('filePath', () => { - const result = client.filePath("fileValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.filePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFileFromFileName', () => { - const result = client.matchFileFromFileName(fakePath); - assert.strictEqual(result, "fileValue"); - assert((client.pathTemplates.filePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('file', async () => { + const fakePath = '/rendered/path/file'; + const expectedParameters = { + file: 'fileValue', + }; + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.filePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.filePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('filePath', () => { + const result = client.filePath('fileValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.filePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFileFromFileName', () => { + const result = client.matchFileFromFileName(fakePath); + assert.strictEqual(result, 'fileValue'); + assert( + (client.pathTemplates.filePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModel', async () => { - const fakePath = "/rendered/path/tunedModel"; - const expectedParameters = { - tuned_model: "tunedModelValue", - }; - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPath', () => { - const result = client.tunedModelPath("tunedModelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelName', () => { - const result = client.matchTunedModelFromTunedModelName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModel', async () => { + const fakePath = '/rendered/path/tunedModel'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + }; + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPath', () => { + const result = client.tunedModelPath('tunedModelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.tunedModelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelName', () => { + const result = client.matchTunedModelFromTunedModelName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.tunedModelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModelPermissions', async () => { - const fakePath = "/rendered/path/tunedModelPermissions"; - const expectedParameters = { - tuned_model: "tunedModelValue", - permission: "permissionValue", - }; - const client = new cacheserviceModule.v1alpha.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPermissionsPath', () => { - const result = client.tunedModelPermissionsPath("tunedModelValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelPermissionsName', () => { - const result = client.matchTunedModelFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromTunedModelPermissionsName', () => { - const result = client.matchPermissionFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModelPermissions', async () => { + const fakePath = '/rendered/path/tunedModelPermissions'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + permission: 'permissionValue', + }; + const client = new cacheserviceModule.v1alpha.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPermissionsPath', () => { + const result = client.tunedModelPermissionsPath( + 'tunedModelValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelPermissionsName', () => { + const result = + client.matchTunedModelFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromTunedModelPermissionsName', () => { + const result = + client.matchPermissionFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_cache_service_v1beta.ts b/packages/google-ai-generativelanguage/test/gapic_cache_service_v1beta.ts index b55c51cd9302..790b3d8b2c27 100644 --- a/packages/google-ai-generativelanguage/test/gapic_cache_service_v1beta.ts +++ b/packages/google-ai-generativelanguage/test/gapic_cache_service_v1beta.ts @@ -19,1134 +19,1464 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as cacheserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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 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('v1beta.CacheServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient(); - 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 = cacheserviceModule.v1beta.CacheServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = cacheserviceModule.v1beta.CacheServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); + it('has universeDomain', () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.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 cacheserviceModule.v1beta.CacheServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 cacheserviceModule.v1beta.CacheServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 cacheserviceModule.v1beta.CacheServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + cacheserviceModule.v1beta.CacheServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + cacheserviceModule.v1beta.CacheServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('has port', () => { - const port = cacheserviceModule.v1beta.CacheServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('should create a client with no option', () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient(); - assert(client); + 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 cacheserviceModule.v1beta.CacheServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with gRPC fallback', () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - fallback: true, - }); - assert(client); + 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 cacheserviceModule.v1beta.CacheServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.cacheServiceStub, undefined); - await client.initialize(); - assert(client.cacheServiceStub); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new cacheserviceModule.v1beta.CacheServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has close method for the initialized client', done => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.cacheServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = cacheserviceModule.v1beta.CacheServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the non-initialized client', done => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.cacheServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient(); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - 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('should create a client with gRPC fallback', () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - 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('has initialize method and supports deferred initialization', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.cacheServiceStub, undefined); + await client.initialize(); + assert(client.cacheServiceStub); }); - describe('createCachedContent', () => { - it('invokes createCachedContent without error', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateCachedContentRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CachedContent() - ); - client.innerApiCalls.createCachedContent = stubSimpleCall(expectedResponse); - const [response] = await client.createCachedContent(request); - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the initialized client', (done) => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.cacheServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createCachedContent without error using callback', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateCachedContentRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CachedContent() - ); - client.innerApiCalls.createCachedContent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createCachedContent( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.ICachedContent|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the non-initialized client', (done) => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.cacheServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createCachedContent with error', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateCachedContentRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createCachedContent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createCachedContent(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + 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 createCachedContent with closed client', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateCachedContentRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createCachedContent(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + 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('createCachedContent', () => { + it('invokes createCachedContent without error', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateCachedContentRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CachedContent(), + ); + client.innerApiCalls.createCachedContent = + stubSimpleCall(expectedResponse); + const [response] = await client.createCachedContent(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('getCachedContent', () => { - it('invokes getCachedContent without error', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetCachedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetCachedContentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CachedContent() - ); - client.innerApiCalls.getCachedContent = stubSimpleCall(expectedResponse); - const [response] = await client.getCachedContent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCachedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCachedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createCachedContent without error using callback', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateCachedContentRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CachedContent(), + ); + client.innerApiCalls.createCachedContent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createCachedContent( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.ICachedContent | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes getCachedContent without error using callback', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetCachedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetCachedContentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CachedContent() - ); - client.innerApiCalls.getCachedContent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getCachedContent( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.ICachedContent|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCachedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCachedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createCachedContent with error', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateCachedContentRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createCachedContent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createCachedContent(request), expectedError); + }); - it('invokes getCachedContent with error', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetCachedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetCachedContentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getCachedContent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getCachedContent(request), expectedError); - const actualRequest = (client.innerApiCalls.getCachedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCachedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createCachedContent with closed client', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateCachedContentRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createCachedContent(request), expectedError); + }); + }); + + describe('getCachedContent', () => { + it('invokes getCachedContent without error', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetCachedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetCachedContentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CachedContent(), + ); + client.innerApiCalls.getCachedContent = stubSimpleCall(expectedResponse); + const [response] = await client.getCachedContent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCachedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCachedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getCachedContent with closed client', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetCachedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetCachedContentRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getCachedContent(request), expectedError); - }); + it('invokes getCachedContent without error using callback', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetCachedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetCachedContentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CachedContent(), + ); + client.innerApiCalls.getCachedContent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getCachedContent( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.ICachedContent | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCachedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCachedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateCachedContent', () => { - it('invokes updateCachedContent without error', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdateCachedContentRequest() - ); - request.cachedContent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.UpdateCachedContentRequest', ['cachedContent', 'name']); - request.cachedContent.name = defaultValue1; - const expectedHeaderRequestParams = `cached_content.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CachedContent() - ); - client.innerApiCalls.updateCachedContent = stubSimpleCall(expectedResponse); - const [response] = await client.updateCachedContent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCachedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCachedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getCachedContent with error', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetCachedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetCachedContentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getCachedContent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getCachedContent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getCachedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCachedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateCachedContent without error using callback', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdateCachedContentRequest() - ); - request.cachedContent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.UpdateCachedContentRequest', ['cachedContent', 'name']); - request.cachedContent.name = defaultValue1; - const expectedHeaderRequestParams = `cached_content.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CachedContent() - ); - client.innerApiCalls.updateCachedContent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateCachedContent( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.ICachedContent|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCachedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCachedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getCachedContent with closed client', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetCachedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetCachedContentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getCachedContent(request), expectedError); + }); + }); + + describe('updateCachedContent', () => { + it('invokes updateCachedContent without error', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdateCachedContentRequest(), + ); + request.cachedContent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.UpdateCachedContentRequest', + ['cachedContent', 'name'], + ); + request.cachedContent.name = defaultValue1; + const expectedHeaderRequestParams = `cached_content.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CachedContent(), + ); + client.innerApiCalls.updateCachedContent = + stubSimpleCall(expectedResponse); + const [response] = await client.updateCachedContent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCachedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCachedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateCachedContent with error', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdateCachedContentRequest() - ); - request.cachedContent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.UpdateCachedContentRequest', ['cachedContent', 'name']); - request.cachedContent.name = defaultValue1; - const expectedHeaderRequestParams = `cached_content.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateCachedContent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateCachedContent(request), expectedError); - const actualRequest = (client.innerApiCalls.updateCachedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCachedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateCachedContent without error using callback', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdateCachedContentRequest(), + ); + request.cachedContent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.UpdateCachedContentRequest', + ['cachedContent', 'name'], + ); + request.cachedContent.name = defaultValue1; + const expectedHeaderRequestParams = `cached_content.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CachedContent(), + ); + client.innerApiCalls.updateCachedContent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateCachedContent( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.ICachedContent | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCachedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCachedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateCachedContent with closed client', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdateCachedContentRequest() - ); - request.cachedContent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.UpdateCachedContentRequest', ['cachedContent', 'name']); - request.cachedContent.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateCachedContent(request), expectedError); - }); + it('invokes updateCachedContent with error', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdateCachedContentRequest(), + ); + request.cachedContent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.UpdateCachedContentRequest', + ['cachedContent', 'name'], + ); + request.cachedContent.name = defaultValue1; + const expectedHeaderRequestParams = `cached_content.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateCachedContent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateCachedContent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateCachedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCachedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteCachedContent', () => { - it('invokes deleteCachedContent without error', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteCachedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeleteCachedContentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteCachedContent = stubSimpleCall(expectedResponse); - const [response] = await client.deleteCachedContent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteCachedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteCachedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateCachedContent with closed client', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdateCachedContentRequest(), + ); + request.cachedContent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.UpdateCachedContentRequest', + ['cachedContent', 'name'], + ); + request.cachedContent.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateCachedContent(request), expectedError); + }); + }); + + describe('deleteCachedContent', () => { + it('invokes deleteCachedContent without error', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteCachedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeleteCachedContentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteCachedContent = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteCachedContent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteCachedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteCachedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteCachedContent without error using callback', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteCachedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeleteCachedContentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteCachedContent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteCachedContent( - 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.deleteCachedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteCachedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteCachedContent without error using callback', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteCachedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeleteCachedContentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteCachedContent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteCachedContent( + 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.deleteCachedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteCachedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteCachedContent with error', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteCachedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeleteCachedContentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteCachedContent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteCachedContent(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteCachedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteCachedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteCachedContent with error', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteCachedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeleteCachedContentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteCachedContent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteCachedContent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteCachedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteCachedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteCachedContent with closed client', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteCachedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeleteCachedContentRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteCachedContent(request), expectedError); - }); + it('invokes deleteCachedContent with closed client', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteCachedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeleteCachedContentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteCachedContent(request), expectedError); + }); + }); + + describe('listCachedContents', () => { + it('invokes listCachedContents without error', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListCachedContentsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CachedContent(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CachedContent(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CachedContent(), + ), + ]; + client.innerApiCalls.listCachedContents = + stubSimpleCall(expectedResponse); + const [response] = await client.listCachedContents(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('listCachedContents', () => { - it('invokes listCachedContents without error', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListCachedContentsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.CachedContent()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.CachedContent()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.CachedContent()), - ]; - client.innerApiCalls.listCachedContents = stubSimpleCall(expectedResponse); - const [response] = await client.listCachedContents(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listCachedContents without error using callback', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListCachedContentsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CachedContent(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CachedContent(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CachedContent(), + ), + ]; + client.innerApiCalls.listCachedContents = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listCachedContents( + request, + ( + err?: Error | null, + result?: + | protos.google.ai.generativelanguage.v1beta.ICachedContent[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes listCachedContents without error using callback', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListCachedContentsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.CachedContent()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.CachedContent()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.CachedContent()), - ]; - client.innerApiCalls.listCachedContents = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listCachedContents( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.ICachedContent[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listCachedContents with error', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListCachedContentsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listCachedContents = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listCachedContents(request), expectedError); + }); - it('invokes listCachedContents with error', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListCachedContentsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listCachedContents = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listCachedContents(request), expectedError); + it('invokes listCachedContentsStream without error', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListCachedContentsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CachedContent(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CachedContent(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CachedContent(), + ), + ]; + client.descriptors.page.listCachedContents.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listCachedContentsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1beta.CachedContent[] = + []; + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1beta.CachedContent, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listCachedContentsStream without error', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListCachedContentsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.CachedContent()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.CachedContent()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.CachedContent()), - ]; - client.descriptors.page.listCachedContents.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listCachedContentsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1beta.CachedContent[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta.CachedContent) => { - 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.listCachedContents.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCachedContents, request)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listCachedContents.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCachedContents, request), + ); + }); - it('invokes listCachedContentsStream with error', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListCachedContentsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listCachedContents.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listCachedContentsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1beta.CachedContent[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta.CachedContent) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listCachedContents.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCachedContents, request)); + it('invokes listCachedContentsStream with error', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListCachedContentsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listCachedContents.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listCachedContentsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1beta.CachedContent[] = + []; + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1beta.CachedContent, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with listCachedContents without error', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListCachedContentsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.CachedContent()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.CachedContent()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.CachedContent()), - ]; - client.descriptors.page.listCachedContents.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ai.generativelanguage.v1beta.ICachedContent[] = []; - const iterable = client.listCachedContentsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listCachedContents.asyncIterate as SinonStub) - .getCall(0).args[1], request); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listCachedContents.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCachedContents, request), + ); + }); - it('uses async iteration with listCachedContents with error', async () => { - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListCachedContentsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listCachedContents.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listCachedContentsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ai.generativelanguage.v1beta.ICachedContent[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listCachedContents.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('uses async iteration with listCachedContents without error', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListCachedContentsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CachedContent(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CachedContent(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CachedContent(), + ), + ]; + client.descriptors.page.listCachedContents.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ai.generativelanguage.v1beta.ICachedContent[] = + []; + const iterable = client.listCachedContentsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listCachedContents.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); }); - describe('Path templates', () => { - - describe('cachedContent', async () => { - const fakePath = "/rendered/path/cachedContent"; - const expectedParameters = { - id: "idValue", - }; - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.cachedContentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.cachedContentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('cachedContentPath', () => { - const result = client.cachedContentPath("idValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.cachedContentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchIdFromCachedContentName', () => { - const result = client.matchIdFromCachedContentName(fakePath); - assert.strictEqual(result, "idValue"); - assert((client.pathTemplates.cachedContentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listCachedContents with error', async () => { + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListCachedContentsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listCachedContents.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listCachedContentsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ai.generativelanguage.v1beta.ICachedContent[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listCachedContents.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('cachedContent', async () => { + const fakePath = '/rendered/path/cachedContent'; + const expectedParameters = { + id: 'idValue', + }; + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.cachedContentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.cachedContentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('cachedContentPath', () => { + const result = client.cachedContentPath('idValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.cachedContentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchIdFromCachedContentName', () => { + const result = client.matchIdFromCachedContentName(fakePath); + assert.strictEqual(result, 'idValue'); + assert( + (client.pathTemplates.cachedContentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('chunk', async () => { - const fakePath = "/rendered/path/chunk"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - chunk: "chunkValue", - }; - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.chunkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.chunkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('chunkPath', () => { - const result = client.chunkPath("corpusValue", "documentValue", "chunkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.chunkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromChunkName', () => { - const result = client.matchCorpusFromChunkName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromChunkName', () => { - const result = client.matchDocumentFromChunkName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChunkFromChunkName', () => { - const result = client.matchChunkFromChunkName(fakePath); - assert.strictEqual(result, "chunkValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('chunk', async () => { + const fakePath = '/rendered/path/chunk'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + chunk: 'chunkValue', + }; + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.chunkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.chunkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('chunkPath', () => { + const result = client.chunkPath( + 'corpusValue', + 'documentValue', + 'chunkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.chunkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromChunkName', () => { + const result = client.matchCorpusFromChunkName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromChunkName', () => { + const result = client.matchDocumentFromChunkName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChunkFromChunkName', () => { + const result = client.matchChunkFromChunkName(fakePath); + assert.strictEqual(result, 'chunkValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('corpus', async () => { - const fakePath = "/rendered/path/corpus"; - const expectedParameters = { - corpus: "corpusValue", - }; - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPath', () => { - const result = client.corpusPath("corpusValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusName', () => { - const result = client.matchCorpusFromCorpusName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpus', async () => { + const fakePath = '/rendered/path/corpus'; + const expectedParameters = { + corpus: 'corpusValue', + }; + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPath', () => { + const result = client.corpusPath('corpusValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.corpusPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusName', () => { + const result = client.matchCorpusFromCorpusName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.corpusPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('corpusPermissions', async () => { - const fakePath = "/rendered/path/corpusPermissions"; - const expectedParameters = { - corpus: "corpusValue", - permission: "permissionValue", - }; - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPermissionsPath', () => { - const result = client.corpusPermissionsPath("corpusValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusPermissionsName', () => { - const result = client.matchCorpusFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromCorpusPermissionsName', () => { - const result = client.matchPermissionFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpusPermissions', async () => { + const fakePath = '/rendered/path/corpusPermissions'; + const expectedParameters = { + corpus: 'corpusValue', + permission: 'permissionValue', + }; + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPermissionsPath', () => { + const result = client.corpusPermissionsPath( + 'corpusValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusPermissionsName', () => { + const result = client.matchCorpusFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromCorpusPermissionsName', () => { + const result = + client.matchPermissionFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('document', async () => { - const fakePath = "/rendered/path/document"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - }; - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.documentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.documentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('documentPath', () => { - const result = client.documentPath("corpusValue", "documentValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.documentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromDocumentName', () => { - const result = client.matchCorpusFromDocumentName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromDocumentName', () => { - const result = client.matchDocumentFromDocumentName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('document', async () => { + const fakePath = '/rendered/path/document'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + }; + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.documentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.documentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('documentPath', () => { + const result = client.documentPath('corpusValue', 'documentValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.documentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromDocumentName', () => { + const result = client.matchCorpusFromDocumentName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromDocumentName', () => { + const result = client.matchDocumentFromDocumentName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('file', async () => { - const fakePath = "/rendered/path/file"; - const expectedParameters = { - file: "fileValue", - }; - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.filePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.filePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('filePath', () => { - const result = client.filePath("fileValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.filePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFileFromFileName', () => { - const result = client.matchFileFromFileName(fakePath); - assert.strictEqual(result, "fileValue"); - assert((client.pathTemplates.filePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('file', async () => { + const fakePath = '/rendered/path/file'; + const expectedParameters = { + file: 'fileValue', + }; + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.filePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.filePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('filePath', () => { + const result = client.filePath('fileValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.filePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFileFromFileName', () => { + const result = client.matchFileFromFileName(fakePath); + assert.strictEqual(result, 'fileValue'); + assert( + (client.pathTemplates.filePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModel', async () => { - const fakePath = "/rendered/path/tunedModel"; - const expectedParameters = { - tuned_model: "tunedModelValue", - }; - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPath', () => { - const result = client.tunedModelPath("tunedModelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelName', () => { - const result = client.matchTunedModelFromTunedModelName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModel', async () => { + const fakePath = '/rendered/path/tunedModel'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + }; + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPath', () => { + const result = client.tunedModelPath('tunedModelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.tunedModelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelName', () => { + const result = client.matchTunedModelFromTunedModelName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.tunedModelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModelPermissions', async () => { - const fakePath = "/rendered/path/tunedModelPermissions"; - const expectedParameters = { - tuned_model: "tunedModelValue", - permission: "permissionValue", - }; - const client = new cacheserviceModule.v1beta.CacheServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPermissionsPath', () => { - const result = client.tunedModelPermissionsPath("tunedModelValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelPermissionsName', () => { - const result = client.matchTunedModelFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromTunedModelPermissionsName', () => { - const result = client.matchPermissionFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModelPermissions', async () => { + const fakePath = '/rendered/path/tunedModelPermissions'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + permission: 'permissionValue', + }; + const client = new cacheserviceModule.v1beta.CacheServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPermissionsPath', () => { + const result = client.tunedModelPermissionsPath( + 'tunedModelValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelPermissionsName', () => { + const result = + client.matchTunedModelFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromTunedModelPermissionsName', () => { + const result = + client.matchPermissionFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_discuss_service_v1alpha.ts b/packages/google-ai-generativelanguage/test/gapic_discuss_service_v1alpha.ts index 854fb4aa4e1f..2e09c79caf04 100644 --- a/packages/google-ai-generativelanguage/test/gapic_discuss_service_v1alpha.ts +++ b/packages/google-ai-generativelanguage/test/gapic_discuss_service_v1alpha.ts @@ -19,725 +19,937 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as discussserviceModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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); } describe('v1alpha.DiscussServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new discussserviceModule.v1alpha.DiscussServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new discussserviceModule.v1alpha.DiscussServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new discussserviceModule.v1alpha.DiscussServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.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 = discussserviceModule.v1alpha.DiscussServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = discussserviceModule.v1alpha.DiscussServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new discussserviceModule.v1alpha.DiscussServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); + it('has universeDomain', () => { + const client = new discussserviceModule.v1alpha.DiscussServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new discussserviceModule.v1alpha.DiscussServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 = + discussserviceModule.v1alpha.DiscussServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + discussserviceModule.v1alpha.DiscussServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new discussserviceModule.v1alpha.DiscussServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.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 discussserviceModule.v1alpha.DiscussServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 discussserviceModule.v1alpha.DiscussServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 discussserviceModule.v1alpha.DiscussServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new discussserviceModule.v1alpha.DiscussServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('has port', () => { - const port = discussserviceModule.v1alpha.DiscussServiceClient.port; - assert(port); - assert(typeof port === 'number'); + 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 discussserviceModule.v1alpha.DiscussServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with no option', () => { - const client = new discussserviceModule.v1alpha.DiscussServiceClient(); - assert(client); + 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 discussserviceModule.v1alpha.DiscussServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with gRPC fallback', () => { - const client = new discussserviceModule.v1alpha.DiscussServiceClient({ - fallback: true, - }); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new discussserviceModule.v1alpha.DiscussServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new discussserviceModule.v1alpha.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.discussServiceStub, undefined); - await client.initialize(); - assert(client.discussServiceStub); - }); + it('has port', () => { + const port = discussserviceModule.v1alpha.DiscussServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the initialized client', done => { - const client = new discussserviceModule.v1alpha.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.discussServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new discussserviceModule.v1alpha.DiscussServiceClient(); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new discussserviceModule.v1alpha.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.discussServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new discussserviceModule.v1alpha.DiscussServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new discussserviceModule.v1alpha.DiscussServiceClient({ - 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 initialize method and supports deferred initialization', async () => { + const client = new discussserviceModule.v1alpha.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.discussServiceStub, undefined); + await client.initialize(); + assert(client.discussServiceStub); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new discussserviceModule.v1alpha.DiscussServiceClient({ - 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('has close method for the initialized client', (done) => { + const client = new discussserviceModule.v1alpha.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.discussServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('generateMessage', () => { - it('invokes generateMessage without error', async () => { - const client = new discussserviceModule.v1alpha.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateMessageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GenerateMessageRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateMessageResponse() - ); - client.innerApiCalls.generateMessage = stubSimpleCall(expectedResponse); - const [response] = await client.generateMessage(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateMessage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateMessage 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 discussserviceModule.v1alpha.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.discussServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes generateMessage without error using callback', async () => { - const client = new discussserviceModule.v1alpha.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateMessageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GenerateMessageRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateMessageResponse() - ); - client.innerApiCalls.generateMessage = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.generateMessage( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IGenerateMessageResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateMessage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateMessage 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 discussserviceModule.v1alpha.DiscussServiceClient({ + 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 generateMessage with error', async () => { - const client = new discussserviceModule.v1alpha.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateMessageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GenerateMessageRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.generateMessage = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.generateMessage(request), expectedError); - const actualRequest = (client.innerApiCalls.generateMessage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateMessage 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 discussserviceModule.v1alpha.DiscussServiceClient({ + 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('generateMessage', () => { + it('invokes generateMessage without error', async () => { + const client = new discussserviceModule.v1alpha.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateMessageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GenerateMessageRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateMessageResponse(), + ); + client.innerApiCalls.generateMessage = stubSimpleCall(expectedResponse); + const [response] = await client.generateMessage(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes generateMessage with closed client', async () => { - const client = new discussserviceModule.v1alpha.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateMessageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GenerateMessageRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.generateMessage(request), expectedError); - }); + it('invokes generateMessage without error using callback', async () => { + const client = new discussserviceModule.v1alpha.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateMessageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GenerateMessageRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateMessageResponse(), + ); + client.innerApiCalls.generateMessage = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.generateMessage( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.IGenerateMessageResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('countMessageTokens', () => { - it('invokes countMessageTokens without error', async () => { - const client = new discussserviceModule.v1alpha.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CountMessageTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CountMessageTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CountMessageTokensResponse() - ); - client.innerApiCalls.countMessageTokens = stubSimpleCall(expectedResponse); - const [response] = await client.countMessageTokens(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes generateMessage with error', async () => { + const client = new discussserviceModule.v1alpha.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateMessageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GenerateMessageRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.generateMessage = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.generateMessage(request), expectedError); + const actualRequest = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countMessageTokens without error using callback', async () => { - const client = new discussserviceModule.v1alpha.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CountMessageTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CountMessageTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CountMessageTokensResponse() - ); - client.innerApiCalls.countMessageTokens = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.countMessageTokens( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes generateMessage with closed client', async () => { + const client = new discussserviceModule.v1alpha.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateMessageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GenerateMessageRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.generateMessage(request), expectedError); + }); + }); + + describe('countMessageTokens', () => { + it('invokes countMessageTokens without error', async () => { + const client = new discussserviceModule.v1alpha.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CountMessageTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CountMessageTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CountMessageTokensResponse(), + ); + client.innerApiCalls.countMessageTokens = + stubSimpleCall(expectedResponse); + const [response] = await client.countMessageTokens(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countMessageTokens with error', async () => { - const client = new discussserviceModule.v1alpha.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CountMessageTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CountMessageTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.countMessageTokens = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.countMessageTokens(request), expectedError); - const actualRequest = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes countMessageTokens without error using callback', async () => { + const client = new discussserviceModule.v1alpha.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CountMessageTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CountMessageTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CountMessageTokensResponse(), + ); + client.innerApiCalls.countMessageTokens = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.countMessageTokens( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.ICountMessageTokensResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countMessageTokens with closed client', async () => { - const client = new discussserviceModule.v1alpha.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CountMessageTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CountMessageTokensRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.countMessageTokens(request), expectedError); - }); + it('invokes countMessageTokens with error', async () => { + const client = new discussserviceModule.v1alpha.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CountMessageTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CountMessageTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.countMessageTokens = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.countMessageTokens(request), expectedError); + const actualRequest = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('cachedContent', async () => { - const fakePath = "/rendered/path/cachedContent"; - const expectedParameters = { - id: "idValue", - }; - const client = new discussserviceModule.v1alpha.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.cachedContentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.cachedContentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('cachedContentPath', () => { - const result = client.cachedContentPath("idValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.cachedContentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchIdFromCachedContentName', () => { - const result = client.matchIdFromCachedContentName(fakePath); - assert.strictEqual(result, "idValue"); - assert((client.pathTemplates.cachedContentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes countMessageTokens with closed client', async () => { + const client = new discussserviceModule.v1alpha.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CountMessageTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CountMessageTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.countMessageTokens(request), expectedError); + }); + }); + + describe('Path templates', () => { + describe('cachedContent', async () => { + const fakePath = '/rendered/path/cachedContent'; + const expectedParameters = { + id: 'idValue', + }; + const client = new discussserviceModule.v1alpha.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.cachedContentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.cachedContentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('cachedContentPath', () => { + const result = client.cachedContentPath('idValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.cachedContentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchIdFromCachedContentName', () => { + const result = client.matchIdFromCachedContentName(fakePath); + assert.strictEqual(result, 'idValue'); + assert( + (client.pathTemplates.cachedContentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('chunk', async () => { - const fakePath = "/rendered/path/chunk"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - chunk: "chunkValue", - }; - const client = new discussserviceModule.v1alpha.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.chunkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.chunkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('chunkPath', () => { - const result = client.chunkPath("corpusValue", "documentValue", "chunkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.chunkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromChunkName', () => { - const result = client.matchCorpusFromChunkName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromChunkName', () => { - const result = client.matchDocumentFromChunkName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChunkFromChunkName', () => { - const result = client.matchChunkFromChunkName(fakePath); - assert.strictEqual(result, "chunkValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('chunk', async () => { + const fakePath = '/rendered/path/chunk'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + chunk: 'chunkValue', + }; + const client = new discussserviceModule.v1alpha.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.chunkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.chunkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('chunkPath', () => { + const result = client.chunkPath( + 'corpusValue', + 'documentValue', + 'chunkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.chunkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromChunkName', () => { + const result = client.matchCorpusFromChunkName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromChunkName', () => { + const result = client.matchDocumentFromChunkName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChunkFromChunkName', () => { + const result = client.matchChunkFromChunkName(fakePath); + assert.strictEqual(result, 'chunkValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('corpus', async () => { - const fakePath = "/rendered/path/corpus"; - const expectedParameters = { - corpus: "corpusValue", - }; - const client = new discussserviceModule.v1alpha.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPath', () => { - const result = client.corpusPath("corpusValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusName', () => { - const result = client.matchCorpusFromCorpusName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpus', async () => { + const fakePath = '/rendered/path/corpus'; + const expectedParameters = { + corpus: 'corpusValue', + }; + const client = new discussserviceModule.v1alpha.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPath', () => { + const result = client.corpusPath('corpusValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.corpusPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusName', () => { + const result = client.matchCorpusFromCorpusName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.corpusPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('corpusPermissions', async () => { - const fakePath = "/rendered/path/corpusPermissions"; - const expectedParameters = { - corpus: "corpusValue", - permission: "permissionValue", - }; - const client = new discussserviceModule.v1alpha.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPermissionsPath', () => { - const result = client.corpusPermissionsPath("corpusValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusPermissionsName', () => { - const result = client.matchCorpusFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromCorpusPermissionsName', () => { - const result = client.matchPermissionFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpusPermissions', async () => { + const fakePath = '/rendered/path/corpusPermissions'; + const expectedParameters = { + corpus: 'corpusValue', + permission: 'permissionValue', + }; + const client = new discussserviceModule.v1alpha.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPermissionsPath', () => { + const result = client.corpusPermissionsPath( + 'corpusValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusPermissionsName', () => { + const result = client.matchCorpusFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromCorpusPermissionsName', () => { + const result = + client.matchPermissionFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('document', async () => { - const fakePath = "/rendered/path/document"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - }; - const client = new discussserviceModule.v1alpha.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.documentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.documentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('documentPath', () => { - const result = client.documentPath("corpusValue", "documentValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.documentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromDocumentName', () => { - const result = client.matchCorpusFromDocumentName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromDocumentName', () => { - const result = client.matchDocumentFromDocumentName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('document', async () => { + const fakePath = '/rendered/path/document'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + }; + const client = new discussserviceModule.v1alpha.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.documentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.documentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('documentPath', () => { + const result = client.documentPath('corpusValue', 'documentValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.documentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromDocumentName', () => { + const result = client.matchCorpusFromDocumentName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromDocumentName', () => { + const result = client.matchDocumentFromDocumentName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('file', async () => { - const fakePath = "/rendered/path/file"; - const expectedParameters = { - file: "fileValue", - }; - const client = new discussserviceModule.v1alpha.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.filePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.filePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('filePath', () => { - const result = client.filePath("fileValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.filePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFileFromFileName', () => { - const result = client.matchFileFromFileName(fakePath); - assert.strictEqual(result, "fileValue"); - assert((client.pathTemplates.filePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('file', async () => { + const fakePath = '/rendered/path/file'; + const expectedParameters = { + file: 'fileValue', + }; + const client = new discussserviceModule.v1alpha.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.filePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.filePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('filePath', () => { + const result = client.filePath('fileValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.filePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFileFromFileName', () => { + const result = client.matchFileFromFileName(fakePath); + assert.strictEqual(result, 'fileValue'); + assert( + (client.pathTemplates.filePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new discussserviceModule.v1alpha.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = new discussserviceModule.v1alpha.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModel', async () => { - const fakePath = "/rendered/path/tunedModel"; - const expectedParameters = { - tuned_model: "tunedModelValue", - }; - const client = new discussserviceModule.v1alpha.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPath', () => { - const result = client.tunedModelPath("tunedModelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelName', () => { - const result = client.matchTunedModelFromTunedModelName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModel', async () => { + const fakePath = '/rendered/path/tunedModel'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + }; + const client = new discussserviceModule.v1alpha.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPath', () => { + const result = client.tunedModelPath('tunedModelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.tunedModelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelName', () => { + const result = client.matchTunedModelFromTunedModelName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.tunedModelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModelPermissions', async () => { - const fakePath = "/rendered/path/tunedModelPermissions"; - const expectedParameters = { - tuned_model: "tunedModelValue", - permission: "permissionValue", - }; - const client = new discussserviceModule.v1alpha.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPermissionsPath', () => { - const result = client.tunedModelPermissionsPath("tunedModelValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelPermissionsName', () => { - const result = client.matchTunedModelFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromTunedModelPermissionsName', () => { - const result = client.matchPermissionFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModelPermissions', async () => { + const fakePath = '/rendered/path/tunedModelPermissions'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + permission: 'permissionValue', + }; + const client = new discussserviceModule.v1alpha.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPermissionsPath', () => { + const result = client.tunedModelPermissionsPath( + 'tunedModelValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelPermissionsName', () => { + const result = + client.matchTunedModelFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromTunedModelPermissionsName', () => { + const result = + client.matchPermissionFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_discuss_service_v1beta.ts b/packages/google-ai-generativelanguage/test/gapic_discuss_service_v1beta.ts index afd4b77e48a3..cda1e5fa24f6 100644 --- a/packages/google-ai-generativelanguage/test/gapic_discuss_service_v1beta.ts +++ b/packages/google-ai-generativelanguage/test/gapic_discuss_service_v1beta.ts @@ -19,725 +19,936 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as discussserviceModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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); } describe('v1beta.DiscussServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new discussserviceModule.v1beta.DiscussServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new discussserviceModule.v1beta.DiscussServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new discussserviceModule.v1beta.DiscussServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.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 = discussserviceModule.v1beta.DiscussServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = discussserviceModule.v1beta.DiscussServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new discussserviceModule.v1beta.DiscussServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); + it('has universeDomain', () => { + const client = new discussserviceModule.v1beta.DiscussServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new discussserviceModule.v1beta.DiscussServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 = + discussserviceModule.v1beta.DiscussServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + discussserviceModule.v1beta.DiscussServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new discussserviceModule.v1beta.DiscussServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.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 discussserviceModule.v1beta.DiscussServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 discussserviceModule.v1beta.DiscussServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 discussserviceModule.v1beta.DiscussServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new discussserviceModule.v1beta.DiscussServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('has port', () => { - const port = discussserviceModule.v1beta.DiscussServiceClient.port; - assert(port); - assert(typeof port === 'number'); + 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 discussserviceModule.v1beta.DiscussServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with no option', () => { - const client = new discussserviceModule.v1beta.DiscussServiceClient(); - assert(client); + 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 discussserviceModule.v1beta.DiscussServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with gRPC fallback', () => { - const client = new discussserviceModule.v1beta.DiscussServiceClient({ - fallback: true, - }); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new discussserviceModule.v1beta.DiscussServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new discussserviceModule.v1beta.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.discussServiceStub, undefined); - await client.initialize(); - assert(client.discussServiceStub); - }); + it('has port', () => { + const port = discussserviceModule.v1beta.DiscussServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the initialized client', done => { - const client = new discussserviceModule.v1beta.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.discussServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new discussserviceModule.v1beta.DiscussServiceClient(); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new discussserviceModule.v1beta.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.discussServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new discussserviceModule.v1beta.DiscussServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new discussserviceModule.v1beta.DiscussServiceClient({ - 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 initialize method and supports deferred initialization', async () => { + const client = new discussserviceModule.v1beta.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.discussServiceStub, undefined); + await client.initialize(); + assert(client.discussServiceStub); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new discussserviceModule.v1beta.DiscussServiceClient({ - 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('has close method for the initialized client', (done) => { + const client = new discussserviceModule.v1beta.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.discussServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('generateMessage', () => { - it('invokes generateMessage without error', async () => { - const client = new discussserviceModule.v1beta.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateMessageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GenerateMessageRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateMessageResponse() - ); - client.innerApiCalls.generateMessage = stubSimpleCall(expectedResponse); - const [response] = await client.generateMessage(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateMessage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateMessage 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 discussserviceModule.v1beta.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.discussServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes generateMessage without error using callback', async () => { - const client = new discussserviceModule.v1beta.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateMessageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GenerateMessageRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateMessageResponse() - ); - client.innerApiCalls.generateMessage = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.generateMessage( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IGenerateMessageResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateMessage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateMessage 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 discussserviceModule.v1beta.DiscussServiceClient({ + 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 generateMessage with error', async () => { - const client = new discussserviceModule.v1beta.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateMessageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GenerateMessageRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.generateMessage = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.generateMessage(request), expectedError); - const actualRequest = (client.innerApiCalls.generateMessage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateMessage 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 discussserviceModule.v1beta.DiscussServiceClient({ + 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('generateMessage', () => { + it('invokes generateMessage without error', async () => { + const client = new discussserviceModule.v1beta.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateMessageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GenerateMessageRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateMessageResponse(), + ); + client.innerApiCalls.generateMessage = stubSimpleCall(expectedResponse); + const [response] = await client.generateMessage(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes generateMessage with closed client', async () => { - const client = new discussserviceModule.v1beta.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateMessageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GenerateMessageRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.generateMessage(request), expectedError); - }); + it('invokes generateMessage without error using callback', async () => { + const client = new discussserviceModule.v1beta.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateMessageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GenerateMessageRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateMessageResponse(), + ); + client.innerApiCalls.generateMessage = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.generateMessage( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IGenerateMessageResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('countMessageTokens', () => { - it('invokes countMessageTokens without error', async () => { - const client = new discussserviceModule.v1beta.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CountMessageTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CountMessageTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CountMessageTokensResponse() - ); - client.innerApiCalls.countMessageTokens = stubSimpleCall(expectedResponse); - const [response] = await client.countMessageTokens(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes generateMessage with error', async () => { + const client = new discussserviceModule.v1beta.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateMessageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GenerateMessageRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.generateMessage = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.generateMessage(request), expectedError); + const actualRequest = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countMessageTokens without error using callback', async () => { - const client = new discussserviceModule.v1beta.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CountMessageTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CountMessageTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CountMessageTokensResponse() - ); - client.innerApiCalls.countMessageTokens = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.countMessageTokens( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.ICountMessageTokensResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes generateMessage with closed client', async () => { + const client = new discussserviceModule.v1beta.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateMessageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GenerateMessageRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.generateMessage(request), expectedError); + }); + }); + + describe('countMessageTokens', () => { + it('invokes countMessageTokens without error', async () => { + const client = new discussserviceModule.v1beta.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CountMessageTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CountMessageTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CountMessageTokensResponse(), + ); + client.innerApiCalls.countMessageTokens = + stubSimpleCall(expectedResponse); + const [response] = await client.countMessageTokens(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countMessageTokens with error', async () => { - const client = new discussserviceModule.v1beta.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CountMessageTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CountMessageTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.countMessageTokens = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.countMessageTokens(request), expectedError); - const actualRequest = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes countMessageTokens without error using callback', async () => { + const client = new discussserviceModule.v1beta.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CountMessageTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CountMessageTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CountMessageTokensResponse(), + ); + client.innerApiCalls.countMessageTokens = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.countMessageTokens( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.ICountMessageTokensResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countMessageTokens with closed client', async () => { - const client = new discussserviceModule.v1beta.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CountMessageTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CountMessageTokensRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.countMessageTokens(request), expectedError); - }); + it('invokes countMessageTokens with error', async () => { + const client = new discussserviceModule.v1beta.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CountMessageTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CountMessageTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.countMessageTokens = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.countMessageTokens(request), expectedError); + const actualRequest = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('cachedContent', async () => { - const fakePath = "/rendered/path/cachedContent"; - const expectedParameters = { - id: "idValue", - }; - const client = new discussserviceModule.v1beta.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.cachedContentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.cachedContentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('cachedContentPath', () => { - const result = client.cachedContentPath("idValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.cachedContentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchIdFromCachedContentName', () => { - const result = client.matchIdFromCachedContentName(fakePath); - assert.strictEqual(result, "idValue"); - assert((client.pathTemplates.cachedContentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes countMessageTokens with closed client', async () => { + const client = new discussserviceModule.v1beta.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CountMessageTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CountMessageTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.countMessageTokens(request), expectedError); + }); + }); + + describe('Path templates', () => { + describe('cachedContent', async () => { + const fakePath = '/rendered/path/cachedContent'; + const expectedParameters = { + id: 'idValue', + }; + const client = new discussserviceModule.v1beta.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.cachedContentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.cachedContentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('cachedContentPath', () => { + const result = client.cachedContentPath('idValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.cachedContentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchIdFromCachedContentName', () => { + const result = client.matchIdFromCachedContentName(fakePath); + assert.strictEqual(result, 'idValue'); + assert( + (client.pathTemplates.cachedContentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('chunk', async () => { - const fakePath = "/rendered/path/chunk"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - chunk: "chunkValue", - }; - const client = new discussserviceModule.v1beta.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.chunkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.chunkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('chunkPath', () => { - const result = client.chunkPath("corpusValue", "documentValue", "chunkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.chunkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromChunkName', () => { - const result = client.matchCorpusFromChunkName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromChunkName', () => { - const result = client.matchDocumentFromChunkName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChunkFromChunkName', () => { - const result = client.matchChunkFromChunkName(fakePath); - assert.strictEqual(result, "chunkValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('chunk', async () => { + const fakePath = '/rendered/path/chunk'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + chunk: 'chunkValue', + }; + const client = new discussserviceModule.v1beta.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.chunkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.chunkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('chunkPath', () => { + const result = client.chunkPath( + 'corpusValue', + 'documentValue', + 'chunkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.chunkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromChunkName', () => { + const result = client.matchCorpusFromChunkName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromChunkName', () => { + const result = client.matchDocumentFromChunkName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChunkFromChunkName', () => { + const result = client.matchChunkFromChunkName(fakePath); + assert.strictEqual(result, 'chunkValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('corpus', async () => { - const fakePath = "/rendered/path/corpus"; - const expectedParameters = { - corpus: "corpusValue", - }; - const client = new discussserviceModule.v1beta.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPath', () => { - const result = client.corpusPath("corpusValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusName', () => { - const result = client.matchCorpusFromCorpusName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpus', async () => { + const fakePath = '/rendered/path/corpus'; + const expectedParameters = { + corpus: 'corpusValue', + }; + const client = new discussserviceModule.v1beta.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPath', () => { + const result = client.corpusPath('corpusValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.corpusPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusName', () => { + const result = client.matchCorpusFromCorpusName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.corpusPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('corpusPermissions', async () => { - const fakePath = "/rendered/path/corpusPermissions"; - const expectedParameters = { - corpus: "corpusValue", - permission: "permissionValue", - }; - const client = new discussserviceModule.v1beta.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPermissionsPath', () => { - const result = client.corpusPermissionsPath("corpusValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusPermissionsName', () => { - const result = client.matchCorpusFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromCorpusPermissionsName', () => { - const result = client.matchPermissionFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpusPermissions', async () => { + const fakePath = '/rendered/path/corpusPermissions'; + const expectedParameters = { + corpus: 'corpusValue', + permission: 'permissionValue', + }; + const client = new discussserviceModule.v1beta.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPermissionsPath', () => { + const result = client.corpusPermissionsPath( + 'corpusValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusPermissionsName', () => { + const result = client.matchCorpusFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromCorpusPermissionsName', () => { + const result = + client.matchPermissionFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('document', async () => { - const fakePath = "/rendered/path/document"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - }; - const client = new discussserviceModule.v1beta.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.documentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.documentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('documentPath', () => { - const result = client.documentPath("corpusValue", "documentValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.documentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromDocumentName', () => { - const result = client.matchCorpusFromDocumentName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromDocumentName', () => { - const result = client.matchDocumentFromDocumentName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('document', async () => { + const fakePath = '/rendered/path/document'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + }; + const client = new discussserviceModule.v1beta.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.documentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.documentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('documentPath', () => { + const result = client.documentPath('corpusValue', 'documentValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.documentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromDocumentName', () => { + const result = client.matchCorpusFromDocumentName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromDocumentName', () => { + const result = client.matchDocumentFromDocumentName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('file', async () => { - const fakePath = "/rendered/path/file"; - const expectedParameters = { - file: "fileValue", - }; - const client = new discussserviceModule.v1beta.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.filePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.filePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('filePath', () => { - const result = client.filePath("fileValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.filePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFileFromFileName', () => { - const result = client.matchFileFromFileName(fakePath); - assert.strictEqual(result, "fileValue"); - assert((client.pathTemplates.filePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('file', async () => { + const fakePath = '/rendered/path/file'; + const expectedParameters = { + file: 'fileValue', + }; + const client = new discussserviceModule.v1beta.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.filePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.filePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('filePath', () => { + const result = client.filePath('fileValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.filePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFileFromFileName', () => { + const result = client.matchFileFromFileName(fakePath); + assert.strictEqual(result, 'fileValue'); + assert( + (client.pathTemplates.filePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new discussserviceModule.v1beta.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = new discussserviceModule.v1beta.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModel', async () => { - const fakePath = "/rendered/path/tunedModel"; - const expectedParameters = { - tuned_model: "tunedModelValue", - }; - const client = new discussserviceModule.v1beta.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPath', () => { - const result = client.tunedModelPath("tunedModelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelName', () => { - const result = client.matchTunedModelFromTunedModelName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModel', async () => { + const fakePath = '/rendered/path/tunedModel'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + }; + const client = new discussserviceModule.v1beta.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPath', () => { + const result = client.tunedModelPath('tunedModelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.tunedModelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelName', () => { + const result = client.matchTunedModelFromTunedModelName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.tunedModelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModelPermissions', async () => { - const fakePath = "/rendered/path/tunedModelPermissions"; - const expectedParameters = { - tuned_model: "tunedModelValue", - permission: "permissionValue", - }; - const client = new discussserviceModule.v1beta.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPermissionsPath', () => { - const result = client.tunedModelPermissionsPath("tunedModelValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelPermissionsName', () => { - const result = client.matchTunedModelFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromTunedModelPermissionsName', () => { - const result = client.matchPermissionFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModelPermissions', async () => { + const fakePath = '/rendered/path/tunedModelPermissions'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + permission: 'permissionValue', + }; + const client = new discussserviceModule.v1beta.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPermissionsPath', () => { + const result = client.tunedModelPermissionsPath( + 'tunedModelValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelPermissionsName', () => { + const result = + client.matchTunedModelFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromTunedModelPermissionsName', () => { + const result = + client.matchPermissionFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_discuss_service_v1beta2.ts b/packages/google-ai-generativelanguage/test/gapic_discuss_service_v1beta2.ts index 00e63dba6e20..ce91ede549cf 100644 --- a/packages/google-ai-generativelanguage/test/gapic_discuss_service_v1beta2.ts +++ b/packages/google-ai-generativelanguage/test/gapic_discuss_service_v1beta2.ts @@ -19,445 +19,547 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as discussserviceModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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); } describe('v1beta2.DiscussServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new discussserviceModule.v1beta2.DiscussServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new discussserviceModule.v1beta2.DiscussServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new discussserviceModule.v1beta2.DiscussServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.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 = discussserviceModule.v1beta2.DiscussServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = discussserviceModule.v1beta2.DiscussServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new discussserviceModule.v1beta2.DiscussServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); + it('has universeDomain', () => { + const client = new discussserviceModule.v1beta2.DiscussServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new discussserviceModule.v1beta2.DiscussServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 = + discussserviceModule.v1beta2.DiscussServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + discussserviceModule.v1beta2.DiscussServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new discussserviceModule.v1beta2.DiscussServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.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 discussserviceModule.v1beta2.DiscussServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 discussserviceModule.v1beta2.DiscussServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 discussserviceModule.v1beta2.DiscussServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new discussserviceModule.v1beta2.DiscussServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('has port', () => { - const port = discussserviceModule.v1beta2.DiscussServiceClient.port; - assert(port); - assert(typeof port === 'number'); + 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 discussserviceModule.v1beta2.DiscussServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with no option', () => { - const client = new discussserviceModule.v1beta2.DiscussServiceClient(); - assert(client); + 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 discussserviceModule.v1beta2.DiscussServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with gRPC fallback', () => { - const client = new discussserviceModule.v1beta2.DiscussServiceClient({ - fallback: true, - }); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new discussserviceModule.v1beta2.DiscussServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new discussserviceModule.v1beta2.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.discussServiceStub, undefined); - await client.initialize(); - assert(client.discussServiceStub); - }); + it('has port', () => { + const port = discussserviceModule.v1beta2.DiscussServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the initialized client', done => { - const client = new discussserviceModule.v1beta2.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.discussServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new discussserviceModule.v1beta2.DiscussServiceClient(); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new discussserviceModule.v1beta2.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.discussServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new discussserviceModule.v1beta2.DiscussServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new discussserviceModule.v1beta2.DiscussServiceClient({ - 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 initialize method and supports deferred initialization', async () => { + const client = new discussserviceModule.v1beta2.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.discussServiceStub, undefined); + await client.initialize(); + assert(client.discussServiceStub); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new discussserviceModule.v1beta2.DiscussServiceClient({ - 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('has close method for the initialized client', (done) => { + const client = new discussserviceModule.v1beta2.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.discussServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('generateMessage', () => { - it('invokes generateMessage without error', async () => { - const client = new discussserviceModule.v1beta2.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.GenerateMessageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta2.GenerateMessageRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.GenerateMessageResponse() - ); - client.innerApiCalls.generateMessage = stubSimpleCall(expectedResponse); - const [response] = await client.generateMessage(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateMessage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateMessage 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 discussserviceModule.v1beta2.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.discussServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes generateMessage without error using callback', async () => { - const client = new discussserviceModule.v1beta2.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.GenerateMessageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta2.GenerateMessageRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.GenerateMessageResponse() - ); - client.innerApiCalls.generateMessage = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.generateMessage( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta2.IGenerateMessageResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateMessage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateMessage 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 discussserviceModule.v1beta2.DiscussServiceClient({ + 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 generateMessage with error', async () => { - const client = new discussserviceModule.v1beta2.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.GenerateMessageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta2.GenerateMessageRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.generateMessage = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.generateMessage(request), expectedError); - const actualRequest = (client.innerApiCalls.generateMessage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateMessage 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 discussserviceModule.v1beta2.DiscussServiceClient({ + 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('generateMessage', () => { + it('invokes generateMessage without error', async () => { + const client = new discussserviceModule.v1beta2.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.GenerateMessageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta2.GenerateMessageRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.GenerateMessageResponse(), + ); + client.innerApiCalls.generateMessage = stubSimpleCall(expectedResponse); + const [response] = await client.generateMessage(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes generateMessage with closed client', async () => { - const client = new discussserviceModule.v1beta2.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.GenerateMessageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta2.GenerateMessageRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.generateMessage(request), expectedError); - }); + it('invokes generateMessage without error using callback', async () => { + const client = new discussserviceModule.v1beta2.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.GenerateMessageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta2.GenerateMessageRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.GenerateMessageResponse(), + ); + client.innerApiCalls.generateMessage = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.generateMessage( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta2.IGenerateMessageResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('countMessageTokens', () => { - it('invokes countMessageTokens without error', async () => { - const client = new discussserviceModule.v1beta2.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.CountMessageTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta2.CountMessageTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.CountMessageTokensResponse() - ); - client.innerApiCalls.countMessageTokens = stubSimpleCall(expectedResponse); - const [response] = await client.countMessageTokens(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes generateMessage with error', async () => { + const client = new discussserviceModule.v1beta2.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.GenerateMessageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta2.GenerateMessageRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.generateMessage = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.generateMessage(request), expectedError); + const actualRequest = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countMessageTokens without error using callback', async () => { - const client = new discussserviceModule.v1beta2.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.CountMessageTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta2.CountMessageTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.CountMessageTokensResponse() - ); - client.innerApiCalls.countMessageTokens = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.countMessageTokens( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes generateMessage with closed client', async () => { + const client = new discussserviceModule.v1beta2.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.GenerateMessageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta2.GenerateMessageRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.generateMessage(request), expectedError); + }); + }); + + describe('countMessageTokens', () => { + it('invokes countMessageTokens without error', async () => { + const client = new discussserviceModule.v1beta2.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.CountMessageTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta2.CountMessageTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.CountMessageTokensResponse(), + ); + client.innerApiCalls.countMessageTokens = + stubSimpleCall(expectedResponse); + const [response] = await client.countMessageTokens(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countMessageTokens with error', async () => { - const client = new discussserviceModule.v1beta2.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.CountMessageTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta2.CountMessageTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.countMessageTokens = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.countMessageTokens(request), expectedError); - const actualRequest = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes countMessageTokens without error using callback', async () => { + const client = new discussserviceModule.v1beta2.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.CountMessageTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta2.CountMessageTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.CountMessageTokensResponse(), + ); + client.innerApiCalls.countMessageTokens = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.countMessageTokens( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta2.ICountMessageTokensResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countMessageTokens with closed client', async () => { - const client = new discussserviceModule.v1beta2.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.CountMessageTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta2.CountMessageTokensRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.countMessageTokens(request), expectedError); - }); + it('invokes countMessageTokens with error', async () => { + const client = new discussserviceModule.v1beta2.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.CountMessageTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta2.CountMessageTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.countMessageTokens = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.countMessageTokens(request), expectedError); + const actualRequest = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new discussserviceModule.v1beta2.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes countMessageTokens with closed client', async () => { + const client = new discussserviceModule.v1beta2.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.CountMessageTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta2.CountMessageTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.countMessageTokens(request), expectedError); + }); + }); + + describe('Path templates', () => { + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = new discussserviceModule.v1beta2.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_discuss_service_v1beta3.ts b/packages/google-ai-generativelanguage/test/gapic_discuss_service_v1beta3.ts index d16964b9638d..eff71596c387 100644 --- a/packages/google-ai-generativelanguage/test/gapic_discuss_service_v1beta3.ts +++ b/packages/google-ai-generativelanguage/test/gapic_discuss_service_v1beta3.ts @@ -19,513 +19,637 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as discussserviceModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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); } describe('v1beta3.DiscussServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new discussserviceModule.v1beta3.DiscussServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new discussserviceModule.v1beta3.DiscussServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new discussserviceModule.v1beta3.DiscussServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.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 = discussserviceModule.v1beta3.DiscussServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = discussserviceModule.v1beta3.DiscussServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new discussserviceModule.v1beta3.DiscussServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); + it('has universeDomain', () => { + const client = new discussserviceModule.v1beta3.DiscussServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new discussserviceModule.v1beta3.DiscussServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 = + discussserviceModule.v1beta3.DiscussServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + discussserviceModule.v1beta3.DiscussServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new discussserviceModule.v1beta3.DiscussServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.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 discussserviceModule.v1beta3.DiscussServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 discussserviceModule.v1beta3.DiscussServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 discussserviceModule.v1beta3.DiscussServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new discussserviceModule.v1beta3.DiscussServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('has port', () => { - const port = discussserviceModule.v1beta3.DiscussServiceClient.port; - assert(port); - assert(typeof port === 'number'); + 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 discussserviceModule.v1beta3.DiscussServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with no option', () => { - const client = new discussserviceModule.v1beta3.DiscussServiceClient(); - assert(client); + 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 discussserviceModule.v1beta3.DiscussServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with gRPC fallback', () => { - const client = new discussserviceModule.v1beta3.DiscussServiceClient({ - fallback: true, - }); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new discussserviceModule.v1beta3.DiscussServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new discussserviceModule.v1beta3.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.discussServiceStub, undefined); - await client.initialize(); - assert(client.discussServiceStub); - }); + it('has port', () => { + const port = discussserviceModule.v1beta3.DiscussServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the initialized client', done => { - const client = new discussserviceModule.v1beta3.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.discussServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new discussserviceModule.v1beta3.DiscussServiceClient(); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new discussserviceModule.v1beta3.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.discussServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new discussserviceModule.v1beta3.DiscussServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new discussserviceModule.v1beta3.DiscussServiceClient({ - 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 initialize method and supports deferred initialization', async () => { + const client = new discussserviceModule.v1beta3.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.discussServiceStub, undefined); + await client.initialize(); + assert(client.discussServiceStub); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new discussserviceModule.v1beta3.DiscussServiceClient({ - 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('has close method for the initialized client', (done) => { + const client = new discussserviceModule.v1beta3.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.discussServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('generateMessage', () => { - it('invokes generateMessage without error', async () => { - const client = new discussserviceModule.v1beta3.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GenerateMessageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.GenerateMessageRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GenerateMessageResponse() - ); - client.innerApiCalls.generateMessage = stubSimpleCall(expectedResponse); - const [response] = await client.generateMessage(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateMessage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateMessage 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 discussserviceModule.v1beta3.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.discussServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes generateMessage without error using callback', async () => { - const client = new discussserviceModule.v1beta3.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GenerateMessageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.GenerateMessageRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GenerateMessageResponse() - ); - client.innerApiCalls.generateMessage = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.generateMessage( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta3.IGenerateMessageResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateMessage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateMessage 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 discussserviceModule.v1beta3.DiscussServiceClient({ + 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 generateMessage with error', async () => { - const client = new discussserviceModule.v1beta3.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GenerateMessageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.GenerateMessageRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.generateMessage = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.generateMessage(request), expectedError); - const actualRequest = (client.innerApiCalls.generateMessage as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateMessage 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 discussserviceModule.v1beta3.DiscussServiceClient({ + 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('generateMessage', () => { + it('invokes generateMessage without error', async () => { + const client = new discussserviceModule.v1beta3.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GenerateMessageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.GenerateMessageRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GenerateMessageResponse(), + ); + client.innerApiCalls.generateMessage = stubSimpleCall(expectedResponse); + const [response] = await client.generateMessage(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes generateMessage with closed client', async () => { - const client = new discussserviceModule.v1beta3.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GenerateMessageRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.GenerateMessageRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.generateMessage(request), expectedError); - }); + it('invokes generateMessage without error using callback', async () => { + const client = new discussserviceModule.v1beta3.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GenerateMessageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.GenerateMessageRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GenerateMessageResponse(), + ); + client.innerApiCalls.generateMessage = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.generateMessage( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta3.IGenerateMessageResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('countMessageTokens', () => { - it('invokes countMessageTokens without error', async () => { - const client = new discussserviceModule.v1beta3.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.CountMessageTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.CountMessageTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.CountMessageTokensResponse() - ); - client.innerApiCalls.countMessageTokens = stubSimpleCall(expectedResponse); - const [response] = await client.countMessageTokens(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes generateMessage with error', async () => { + const client = new discussserviceModule.v1beta3.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GenerateMessageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.GenerateMessageRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.generateMessage = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.generateMessage(request), expectedError); + const actualRequest = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateMessage as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countMessageTokens without error using callback', async () => { - const client = new discussserviceModule.v1beta3.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.CountMessageTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.CountMessageTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.CountMessageTokensResponse() - ); - client.innerApiCalls.countMessageTokens = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.countMessageTokens( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes generateMessage with closed client', async () => { + const client = new discussserviceModule.v1beta3.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GenerateMessageRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.GenerateMessageRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.generateMessage(request), expectedError); + }); + }); + + describe('countMessageTokens', () => { + it('invokes countMessageTokens without error', async () => { + const client = new discussserviceModule.v1beta3.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.CountMessageTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.CountMessageTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.CountMessageTokensResponse(), + ); + client.innerApiCalls.countMessageTokens = + stubSimpleCall(expectedResponse); + const [response] = await client.countMessageTokens(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countMessageTokens with error', async () => { - const client = new discussserviceModule.v1beta3.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.CountMessageTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.CountMessageTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.countMessageTokens = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.countMessageTokens(request), expectedError); - const actualRequest = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countMessageTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes countMessageTokens without error using callback', async () => { + const client = new discussserviceModule.v1beta3.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.CountMessageTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.CountMessageTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.CountMessageTokensResponse(), + ); + client.innerApiCalls.countMessageTokens = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.countMessageTokens( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta3.ICountMessageTokensResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countMessageTokens with closed client', async () => { - const client = new discussserviceModule.v1beta3.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.CountMessageTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.CountMessageTokensRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.countMessageTokens(request), expectedError); - }); + it('invokes countMessageTokens with error', async () => { + const client = new discussserviceModule.v1beta3.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.CountMessageTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.CountMessageTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.countMessageTokens = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.countMessageTokens(request), expectedError); + const actualRequest = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countMessageTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new discussserviceModule.v1beta3.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes countMessageTokens with closed client', async () => { + const client = new discussserviceModule.v1beta3.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.CountMessageTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.CountMessageTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.countMessageTokens(request), expectedError); + }); + }); + + describe('Path templates', () => { + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = new discussserviceModule.v1beta3.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('permission', async () => { - const fakePath = "/rendered/path/permission"; - const expectedParameters = { - tuned_model: "tunedModelValue", - permission: "permissionValue", - }; - const client = new discussserviceModule.v1beta3.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.permissionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.permissionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('permissionPath', () => { - const result = client.permissionPath("tunedModelValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.permissionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromPermissionName', () => { - const result = client.matchTunedModelFromPermissionName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.permissionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromPermissionName', () => { - const result = client.matchPermissionFromPermissionName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.permissionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('permission', async () => { + const fakePath = '/rendered/path/permission'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + permission: 'permissionValue', + }; + const client = new discussserviceModule.v1beta3.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.permissionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.permissionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('permissionPath', () => { + const result = client.permissionPath( + 'tunedModelValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.permissionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromPermissionName', () => { + const result = client.matchTunedModelFromPermissionName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.permissionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromPermissionName', () => { + const result = client.matchPermissionFromPermissionName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + (client.pathTemplates.permissionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModel', async () => { - const fakePath = "/rendered/path/tunedModel"; - const expectedParameters = { - tuned_model: "tunedModelValue", - }; - const client = new discussserviceModule.v1beta3.DiscussServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPath', () => { - const result = client.tunedModelPath("tunedModelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelName', () => { - const result = client.matchTunedModelFromTunedModelName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModel', async () => { + const fakePath = '/rendered/path/tunedModel'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + }; + const client = new discussserviceModule.v1beta3.DiscussServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPath', () => { + const result = client.tunedModelPath('tunedModelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.tunedModelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelName', () => { + const result = client.matchTunedModelFromTunedModelName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.tunedModelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_file_service_v1alpha.ts b/packages/google-ai-generativelanguage/test/gapic_file_service_v1alpha.ts index 69595c9accc1..34c9cc1035b2 100644 --- a/packages/google-ai-generativelanguage/test/gapic_file_service_v1alpha.ts +++ b/packages/google-ai-generativelanguage/test/gapic_file_service_v1alpha.ts @@ -19,1022 +19,1313 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as fileserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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 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('v1alpha.FileServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new fileserviceModule.v1alpha.FileServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new fileserviceModule.v1alpha.FileServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new fileserviceModule.v1alpha.FileServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.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 = fileserviceModule.v1alpha.FileServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = fileserviceModule.v1alpha.FileServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new fileserviceModule.v1alpha.FileServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); + it('has universeDomain', () => { + const client = new fileserviceModule.v1alpha.FileServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new fileserviceModule.v1alpha.FileServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 = + fileserviceModule.v1alpha.FileServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + fileserviceModule.v1alpha.FileServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.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 fileserviceModule.v1alpha.FileServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 fileserviceModule.v1alpha.FileServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 fileserviceModule.v1alpha.FileServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('has port', () => { - const port = fileserviceModule.v1alpha.FileServiceClient.port; - assert(port); - assert(typeof port === 'number'); + 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 fileserviceModule.v1alpha.FileServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with no option', () => { - const client = new fileserviceModule.v1alpha.FileServiceClient(); - assert(client); + 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 fileserviceModule.v1alpha.FileServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with gRPC fallback', () => { - const client = new fileserviceModule.v1alpha.FileServiceClient({ - fallback: true, - }); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new fileserviceModule.v1alpha.FileServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.fileServiceStub, undefined); - await client.initialize(); - assert(client.fileServiceStub); - }); + it('has port', () => { + const port = fileserviceModule.v1alpha.FileServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the initialized client', done => { - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.fileServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new fileserviceModule.v1alpha.FileServiceClient(); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.fileServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new fileserviceModule.v1alpha.FileServiceClient({ - 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 initialize method and supports deferred initialization', async () => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.fileServiceStub, undefined); + await client.initialize(); + assert(client.fileServiceStub); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new fileserviceModule.v1alpha.FileServiceClient({ - 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('has close method for the initialized client', (done) => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.fileServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('createFile', () => { - it('invokes createFile without error', async () => { - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateFileRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateFileResponse() - ); - client.innerApiCalls.createFile = stubSimpleCall(expectedResponse); - const [response] = await client.createFile(request); - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the non-initialized client', (done) => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.fileServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createFile without error using callback', async () => { - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateFileRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateFileResponse() - ); - client.innerApiCalls.createFile = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createFile( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.ICreateFileResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new fileserviceModule.v1alpha.FileServiceClient({ + 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 createFile with error', async () => { - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateFileRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createFile = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createFile(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new fileserviceModule.v1alpha.FileServiceClient({ + 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('createFile', () => { + it('invokes createFile without error', async () => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateFileRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateFileResponse(), + ); + client.innerApiCalls.createFile = stubSimpleCall(expectedResponse); + const [response] = await client.createFile(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createFile with closed client', async () => { - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateFileRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createFile(request), expectedError); - }); + it('invokes createFile without error using callback', async () => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateFileRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateFileResponse(), + ); + client.innerApiCalls.createFile = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createFile( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.ICreateFileResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('getFile', () => { - it('invokes getFile without error', async () => { - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetFileRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetFileRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.File() - ); - client.innerApiCalls.getFile = stubSimpleCall(expectedResponse); - const [response] = await client.getFile(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getFile as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getFile as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createFile with error', async () => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateFileRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createFile = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createFile(request), expectedError); + }); - it('invokes getFile without error using callback', async () => { - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetFileRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetFileRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.File() - ); - client.innerApiCalls.getFile = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getFile( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IFile|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getFile as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getFile as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createFile with closed client', async () => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateFileRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createFile(request), expectedError); + }); + }); + + describe('getFile', () => { + it('invokes getFile without error', async () => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetFileRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetFileRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.File(), + ); + client.innerApiCalls.getFile = stubSimpleCall(expectedResponse); + const [response] = await client.getFile(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getFile as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getFile as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getFile with error', async () => { - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetFileRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetFileRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getFile = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getFile(request), expectedError); - const actualRequest = (client.innerApiCalls.getFile as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getFile as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getFile without error using callback', async () => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetFileRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetFileRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.File(), + ); + client.innerApiCalls.getFile = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getFile( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.IFile | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getFile as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getFile as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getFile with closed client', async () => { - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetFileRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetFileRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getFile(request), expectedError); - }); + it('invokes getFile with error', async () => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetFileRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetFileRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getFile = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getFile(request), expectedError); + const actualRequest = (client.innerApiCalls.getFile as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getFile as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteFile', () => { - it('invokes deleteFile without error', async () => { - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteFileRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeleteFileRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteFile = stubSimpleCall(expectedResponse); - const [response] = await client.deleteFile(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteFile as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteFile as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getFile with closed client', async () => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetFileRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetFileRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getFile(request), expectedError); + }); + }); + + describe('deleteFile', () => { + it('invokes deleteFile without error', async () => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteFileRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeleteFileRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteFile = stubSimpleCall(expectedResponse); + const [response] = await client.deleteFile(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteFile as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteFile as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteFile without error using callback', async () => { - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteFileRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeleteFileRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteFile = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteFile( - 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.deleteFile as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteFile as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteFile without error using callback', async () => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteFileRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeleteFileRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteFile = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteFile( + 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.deleteFile as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteFile as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteFile with error', async () => { - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteFileRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeleteFileRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteFile = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteFile(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteFile as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteFile as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteFile with error', async () => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteFileRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeleteFileRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteFile = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteFile(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteFile as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteFile as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteFile with closed client', async () => { - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteFileRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeleteFileRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteFile(request), expectedError); - }); + it('invokes deleteFile with closed client', async () => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteFileRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeleteFileRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteFile(request), expectedError); + }); + }); + + describe('listFiles', () => { + it('invokes listFiles without error', async () => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListFilesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.File(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.File(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.File(), + ), + ]; + client.innerApiCalls.listFiles = stubSimpleCall(expectedResponse); + const [response] = await client.listFiles(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('listFiles', () => { - it('invokes listFiles without error', async () => { - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListFilesRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.File()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.File()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.File()), - ]; - client.innerApiCalls.listFiles = stubSimpleCall(expectedResponse); - const [response] = await client.listFiles(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listFiles without error using callback', async () => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListFilesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.File(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.File(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.File(), + ), + ]; + client.innerApiCalls.listFiles = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listFiles( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.IFile[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes listFiles without error using callback', async () => { - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListFilesRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.File()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.File()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.File()), - ]; - client.innerApiCalls.listFiles = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listFiles( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IFile[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listFiles with error', async () => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListFilesRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listFiles = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listFiles(request), expectedError); + }); - it('invokes listFiles with error', async () => { - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListFilesRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listFiles = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listFiles(request), expectedError); + it('invokes listFilesStream without error', async () => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListFilesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.File(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.File(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.File(), + ), + ]; + client.descriptors.page.listFiles.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listFilesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1alpha.File[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1alpha.File) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listFilesStream without error', async () => { - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListFilesRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.File()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.File()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.File()), - ]; - client.descriptors.page.listFiles.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listFilesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1alpha.File[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1alpha.File) => { - 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.listFiles.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listFiles, request)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listFiles.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listFiles, request), + ); + }); - it('invokes listFilesStream with error', async () => { - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListFilesRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listFiles.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listFilesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1alpha.File[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1alpha.File) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listFiles.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listFiles, request)); + it('invokes listFilesStream with error', async () => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListFilesRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listFiles.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listFilesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1alpha.File[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1alpha.File) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with listFiles without error', async () => { - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListFilesRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.File()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.File()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.File()), - ]; - client.descriptors.page.listFiles.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ai.generativelanguage.v1alpha.IFile[] = []; - const iterable = client.listFilesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listFiles.asyncIterate as SinonStub) - .getCall(0).args[1], request); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listFiles.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listFiles, request), + ); + }); - it('uses async iteration with listFiles with error', async () => { - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListFilesRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listFiles.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listFilesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ai.generativelanguage.v1alpha.IFile[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listFiles.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('uses async iteration with listFiles without error', async () => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListFilesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.File(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.File(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.File(), + ), + ]; + client.descriptors.page.listFiles.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ai.generativelanguage.v1alpha.IFile[] = []; + const iterable = client.listFilesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listFiles.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); }); - describe('Path templates', () => { - - describe('cachedContent', async () => { - const fakePath = "/rendered/path/cachedContent"; - const expectedParameters = { - id: "idValue", - }; - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.cachedContentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.cachedContentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('cachedContentPath', () => { - const result = client.cachedContentPath("idValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.cachedContentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchIdFromCachedContentName', () => { - const result = client.matchIdFromCachedContentName(fakePath); - assert.strictEqual(result, "idValue"); - assert((client.pathTemplates.cachedContentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listFiles with error', async () => { + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListFilesRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listFiles.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listFilesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ai.generativelanguage.v1alpha.IFile[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listFiles.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('cachedContent', async () => { + const fakePath = '/rendered/path/cachedContent'; + const expectedParameters = { + id: 'idValue', + }; + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.cachedContentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.cachedContentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('cachedContentPath', () => { + const result = client.cachedContentPath('idValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.cachedContentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchIdFromCachedContentName', () => { + const result = client.matchIdFromCachedContentName(fakePath); + assert.strictEqual(result, 'idValue'); + assert( + (client.pathTemplates.cachedContentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('chunk', async () => { - const fakePath = "/rendered/path/chunk"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - chunk: "chunkValue", - }; - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.chunkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.chunkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('chunkPath', () => { - const result = client.chunkPath("corpusValue", "documentValue", "chunkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.chunkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromChunkName', () => { - const result = client.matchCorpusFromChunkName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromChunkName', () => { - const result = client.matchDocumentFromChunkName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChunkFromChunkName', () => { - const result = client.matchChunkFromChunkName(fakePath); - assert.strictEqual(result, "chunkValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('chunk', async () => { + const fakePath = '/rendered/path/chunk'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + chunk: 'chunkValue', + }; + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.chunkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.chunkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('chunkPath', () => { + const result = client.chunkPath( + 'corpusValue', + 'documentValue', + 'chunkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.chunkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromChunkName', () => { + const result = client.matchCorpusFromChunkName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromChunkName', () => { + const result = client.matchDocumentFromChunkName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChunkFromChunkName', () => { + const result = client.matchChunkFromChunkName(fakePath); + assert.strictEqual(result, 'chunkValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('corpus', async () => { - const fakePath = "/rendered/path/corpus"; - const expectedParameters = { - corpus: "corpusValue", - }; - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPath', () => { - const result = client.corpusPath("corpusValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusName', () => { - const result = client.matchCorpusFromCorpusName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpus', async () => { + const fakePath = '/rendered/path/corpus'; + const expectedParameters = { + corpus: 'corpusValue', + }; + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPath', () => { + const result = client.corpusPath('corpusValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.corpusPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusName', () => { + const result = client.matchCorpusFromCorpusName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.corpusPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('corpusPermissions', async () => { - const fakePath = "/rendered/path/corpusPermissions"; - const expectedParameters = { - corpus: "corpusValue", - permission: "permissionValue", - }; - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPermissionsPath', () => { - const result = client.corpusPermissionsPath("corpusValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusPermissionsName', () => { - const result = client.matchCorpusFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromCorpusPermissionsName', () => { - const result = client.matchPermissionFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpusPermissions', async () => { + const fakePath = '/rendered/path/corpusPermissions'; + const expectedParameters = { + corpus: 'corpusValue', + permission: 'permissionValue', + }; + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPermissionsPath', () => { + const result = client.corpusPermissionsPath( + 'corpusValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusPermissionsName', () => { + const result = client.matchCorpusFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromCorpusPermissionsName', () => { + const result = + client.matchPermissionFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('document', async () => { - const fakePath = "/rendered/path/document"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - }; - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.documentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.documentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('documentPath', () => { - const result = client.documentPath("corpusValue", "documentValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.documentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromDocumentName', () => { - const result = client.matchCorpusFromDocumentName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromDocumentName', () => { - const result = client.matchDocumentFromDocumentName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('document', async () => { + const fakePath = '/rendered/path/document'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + }; + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.documentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.documentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('documentPath', () => { + const result = client.documentPath('corpusValue', 'documentValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.documentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromDocumentName', () => { + const result = client.matchCorpusFromDocumentName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromDocumentName', () => { + const result = client.matchDocumentFromDocumentName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('file', async () => { - const fakePath = "/rendered/path/file"; - const expectedParameters = { - file: "fileValue", - }; - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.filePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.filePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('filePath', () => { - const result = client.filePath("fileValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.filePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFileFromFileName', () => { - const result = client.matchFileFromFileName(fakePath); - assert.strictEqual(result, "fileValue"); - assert((client.pathTemplates.filePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('file', async () => { + const fakePath = '/rendered/path/file'; + const expectedParameters = { + file: 'fileValue', + }; + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.filePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.filePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('filePath', () => { + const result = client.filePath('fileValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.filePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFileFromFileName', () => { + const result = client.matchFileFromFileName(fakePath); + assert.strictEqual(result, 'fileValue'); + assert( + (client.pathTemplates.filePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModel', async () => { - const fakePath = "/rendered/path/tunedModel"; - const expectedParameters = { - tuned_model: "tunedModelValue", - }; - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPath', () => { - const result = client.tunedModelPath("tunedModelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelName', () => { - const result = client.matchTunedModelFromTunedModelName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModel', async () => { + const fakePath = '/rendered/path/tunedModel'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + }; + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPath', () => { + const result = client.tunedModelPath('tunedModelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.tunedModelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelName', () => { + const result = client.matchTunedModelFromTunedModelName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.tunedModelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModelPermissions', async () => { - const fakePath = "/rendered/path/tunedModelPermissions"; - const expectedParameters = { - tuned_model: "tunedModelValue", - permission: "permissionValue", - }; - const client = new fileserviceModule.v1alpha.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPermissionsPath', () => { - const result = client.tunedModelPermissionsPath("tunedModelValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelPermissionsName', () => { - const result = client.matchTunedModelFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromTunedModelPermissionsName', () => { - const result = client.matchPermissionFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModelPermissions', async () => { + const fakePath = '/rendered/path/tunedModelPermissions'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + permission: 'permissionValue', + }; + const client = new fileserviceModule.v1alpha.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPermissionsPath', () => { + const result = client.tunedModelPermissionsPath( + 'tunedModelValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelPermissionsName', () => { + const result = + client.matchTunedModelFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromTunedModelPermissionsName', () => { + const result = + client.matchPermissionFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_file_service_v1beta.ts b/packages/google-ai-generativelanguage/test/gapic_file_service_v1beta.ts index 098bc4fccefd..fb37fffd074f 100644 --- a/packages/google-ai-generativelanguage/test/gapic_file_service_v1beta.ts +++ b/packages/google-ai-generativelanguage/test/gapic_file_service_v1beta.ts @@ -19,1130 +19,1443 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as fileserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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 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('v1beta.FileServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new fileserviceModule.v1beta.FileServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new fileserviceModule.v1beta.FileServiceClient(); - 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 = fileserviceModule.v1beta.FileServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = fileserviceModule.v1beta.FileServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new fileserviceModule.v1beta.FileServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new fileserviceModule.v1beta.FileServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new fileserviceModule.v1beta.FileServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); + it('has universeDomain', () => { + const client = new fileserviceModule.v1beta.FileServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.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 fileserviceModule.v1beta.FileServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 fileserviceModule.v1beta.FileServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 fileserviceModule.v1beta.FileServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + fileserviceModule.v1beta.FileServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + fileserviceModule.v1beta.FileServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('has port', () => { - const port = fileserviceModule.v1beta.FileServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('should create a client with no option', () => { - const client = new fileserviceModule.v1beta.FileServiceClient(); - assert(client); + 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 fileserviceModule.v1beta.FileServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with gRPC fallback', () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - fallback: true, - }); - assert(client); + 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 fileserviceModule.v1beta.FileServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.fileServiceStub, undefined); - await client.initialize(); - assert(client.fileServiceStub); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new fileserviceModule.v1beta.FileServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has close method for the initialized client', done => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.fileServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = fileserviceModule.v1beta.FileServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the non-initialized client', done => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.fileServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new fileserviceModule.v1beta.FileServiceClient(); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new fileserviceModule.v1beta.FileServiceClient({ - 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('should create a client with gRPC fallback', () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new fileserviceModule.v1beta.FileServiceClient({ - 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('has initialize method and supports deferred initialization', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.fileServiceStub, undefined); + await client.initialize(); + assert(client.fileServiceStub); }); - describe('createFile', () => { - it('invokes createFile without error', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateFileRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateFileResponse() - ); - client.innerApiCalls.createFile = stubSimpleCall(expectedResponse); - const [response] = await client.createFile(request); - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the initialized client', (done) => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.fileServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createFile without error using callback', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateFileRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateFileResponse() - ); - client.innerApiCalls.createFile = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createFile( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.ICreateFileResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the non-initialized client', (done) => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.fileServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createFile with error', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateFileRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createFile = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createFile(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new fileserviceModule.v1beta.FileServiceClient({ + 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 createFile with closed client', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateFileRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createFile(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new fileserviceModule.v1beta.FileServiceClient({ + 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('createFile', () => { + it('invokes createFile without error', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateFileRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateFileResponse(), + ); + client.innerApiCalls.createFile = stubSimpleCall(expectedResponse); + const [response] = await client.createFile(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('getFile', () => { - it('invokes getFile without error', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetFileRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetFileRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.File() - ); - client.innerApiCalls.getFile = stubSimpleCall(expectedResponse); - const [response] = await client.getFile(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getFile as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getFile as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createFile without error using callback', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateFileRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateFileResponse(), + ); + client.innerApiCalls.createFile = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createFile( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.ICreateFileResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes getFile without error using callback', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetFileRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetFileRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.File() - ); - client.innerApiCalls.getFile = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getFile( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IFile|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getFile as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getFile as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createFile with error', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateFileRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createFile = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createFile(request), expectedError); + }); - it('invokes getFile with error', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetFileRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetFileRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getFile = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getFile(request), expectedError); - const actualRequest = (client.innerApiCalls.getFile as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getFile as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createFile with closed client', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateFileRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createFile(request), expectedError); + }); + }); + + describe('getFile', () => { + it('invokes getFile without error', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetFileRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetFileRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.File(), + ); + client.innerApiCalls.getFile = stubSimpleCall(expectedResponse); + const [response] = await client.getFile(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getFile as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getFile as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getFile with closed client', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetFileRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetFileRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getFile(request), expectedError); - }); + it('invokes getFile without error using callback', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetFileRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetFileRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.File(), + ); + client.innerApiCalls.getFile = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getFile( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IFile | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getFile as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getFile as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteFile', () => { - it('invokes deleteFile without error', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteFileRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeleteFileRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteFile = stubSimpleCall(expectedResponse); - const [response] = await client.deleteFile(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteFile as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteFile as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getFile with error', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetFileRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetFileRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getFile = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getFile(request), expectedError); + const actualRequest = (client.innerApiCalls.getFile as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getFile as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteFile without error using callback', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteFileRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeleteFileRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteFile = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteFile( - 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.deleteFile as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteFile as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getFile with closed client', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetFileRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetFileRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getFile(request), expectedError); + }); + }); + + describe('deleteFile', () => { + it('invokes deleteFile without error', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteFileRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeleteFileRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteFile = stubSimpleCall(expectedResponse); + const [response] = await client.deleteFile(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteFile as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteFile as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteFile with error', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteFileRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeleteFileRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteFile = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteFile(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteFile as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteFile as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteFile without error using callback', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteFileRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeleteFileRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteFile = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteFile( + 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.deleteFile as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteFile as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteFile with closed client', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteFileRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeleteFileRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteFile(request), expectedError); - }); + it('invokes deleteFile with error', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteFileRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeleteFileRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteFile = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteFile(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteFile as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteFile as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('downloadFile', () => { - it('invokes downloadFile without error', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DownloadFileRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DownloadFileRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DownloadFileResponse() - ); - client.innerApiCalls.downloadFile = stubSimpleCall(expectedResponse); - const [response] = await client.downloadFile(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.downloadFile as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.downloadFile as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteFile with closed client', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteFileRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeleteFileRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteFile(request), expectedError); + }); + }); + + describe('downloadFile', () => { + it('invokes downloadFile without error', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DownloadFileRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DownloadFileRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DownloadFileResponse(), + ); + client.innerApiCalls.downloadFile = stubSimpleCall(expectedResponse); + const [response] = await client.downloadFile(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.downloadFile as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.downloadFile as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes downloadFile without error using callback', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DownloadFileRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DownloadFileRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DownloadFileResponse() - ); - client.innerApiCalls.downloadFile = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.downloadFile( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IDownloadFileResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.downloadFile as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.downloadFile as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes downloadFile without error using callback', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DownloadFileRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DownloadFileRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DownloadFileResponse(), + ); + client.innerApiCalls.downloadFile = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.downloadFile( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IDownloadFileResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.downloadFile as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.downloadFile as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes downloadFile with error', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DownloadFileRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DownloadFileRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.downloadFile = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.downloadFile(request), expectedError); - const actualRequest = (client.innerApiCalls.downloadFile as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.downloadFile as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes downloadFile with error', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DownloadFileRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DownloadFileRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.downloadFile = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.downloadFile(request), expectedError); + const actualRequest = ( + client.innerApiCalls.downloadFile as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.downloadFile as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes downloadFile with closed client', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DownloadFileRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DownloadFileRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.downloadFile(request), expectedError); - }); + it('invokes downloadFile with closed client', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DownloadFileRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DownloadFileRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.downloadFile(request), expectedError); + }); + }); + + describe('listFiles', () => { + it('invokes listFiles without error', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListFilesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.File(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.File(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.File(), + ), + ]; + client.innerApiCalls.listFiles = stubSimpleCall(expectedResponse); + const [response] = await client.listFiles(request); + assert.deepStrictEqual(response, expectedResponse); }); - describe('listFiles', () => { - it('invokes listFiles without error', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListFilesRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.File()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.File()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.File()), - ]; - client.innerApiCalls.listFiles = stubSimpleCall(expectedResponse); - const [response] = await client.listFiles(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listFiles without error using callback', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListFilesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.File(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.File(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.File(), + ), + ]; + client.innerApiCalls.listFiles = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listFiles( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IFile[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes listFiles without error using callback', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListFilesRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.File()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.File()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.File()), - ]; - client.innerApiCalls.listFiles = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listFiles( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IFile[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listFiles with error', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListFilesRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listFiles = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listFiles(request), expectedError); + }); - it('invokes listFiles with error', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListFilesRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listFiles = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listFiles(request), expectedError); + it('invokes listFilesStream without error', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListFilesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.File(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.File(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.File(), + ), + ]; + client.descriptors.page.listFiles.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listFilesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1beta.File[] = []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1beta.File) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listFilesStream without error', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListFilesRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.File()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.File()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.File()), - ]; - client.descriptors.page.listFiles.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listFilesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1beta.File[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta.File) => { - 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.listFiles.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listFiles, request)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listFiles.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listFiles, request), + ); + }); - it('invokes listFilesStream with error', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListFilesRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listFiles.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listFilesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1beta.File[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta.File) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listFiles.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listFiles, request)); + it('invokes listFilesStream with error', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListFilesRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listFiles.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listFilesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1beta.File[] = []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1beta.File) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with listFiles without error', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListFilesRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.File()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.File()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.File()), - ]; - client.descriptors.page.listFiles.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ai.generativelanguage.v1beta.IFile[] = []; - const iterable = client.listFilesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listFiles.asyncIterate as SinonStub) - .getCall(0).args[1], request); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listFiles.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listFiles, request), + ); + }); - it('uses async iteration with listFiles with error', async () => { - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListFilesRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listFiles.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listFilesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ai.generativelanguage.v1beta.IFile[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listFiles.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('uses async iteration with listFiles without error', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListFilesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.File(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.File(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.File(), + ), + ]; + client.descriptors.page.listFiles.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ai.generativelanguage.v1beta.IFile[] = []; + const iterable = client.listFilesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listFiles.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); }); - describe('Path templates', () => { - - describe('cachedContent', async () => { - const fakePath = "/rendered/path/cachedContent"; - const expectedParameters = { - id: "idValue", - }; - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.cachedContentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.cachedContentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('cachedContentPath', () => { - const result = client.cachedContentPath("idValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.cachedContentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchIdFromCachedContentName', () => { - const result = client.matchIdFromCachedContentName(fakePath); - assert.strictEqual(result, "idValue"); - assert((client.pathTemplates.cachedContentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listFiles with error', async () => { + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListFilesRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listFiles.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listFilesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ai.generativelanguage.v1beta.IFile[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listFiles.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('cachedContent', async () => { + const fakePath = '/rendered/path/cachedContent'; + const expectedParameters = { + id: 'idValue', + }; + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.cachedContentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.cachedContentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('cachedContentPath', () => { + const result = client.cachedContentPath('idValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.cachedContentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchIdFromCachedContentName', () => { + const result = client.matchIdFromCachedContentName(fakePath); + assert.strictEqual(result, 'idValue'); + assert( + (client.pathTemplates.cachedContentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('chunk', async () => { - const fakePath = "/rendered/path/chunk"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - chunk: "chunkValue", - }; - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.chunkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.chunkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('chunkPath', () => { - const result = client.chunkPath("corpusValue", "documentValue", "chunkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.chunkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromChunkName', () => { - const result = client.matchCorpusFromChunkName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromChunkName', () => { - const result = client.matchDocumentFromChunkName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChunkFromChunkName', () => { - const result = client.matchChunkFromChunkName(fakePath); - assert.strictEqual(result, "chunkValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('chunk', async () => { + const fakePath = '/rendered/path/chunk'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + chunk: 'chunkValue', + }; + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.chunkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.chunkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('chunkPath', () => { + const result = client.chunkPath( + 'corpusValue', + 'documentValue', + 'chunkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.chunkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromChunkName', () => { + const result = client.matchCorpusFromChunkName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromChunkName', () => { + const result = client.matchDocumentFromChunkName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChunkFromChunkName', () => { + const result = client.matchChunkFromChunkName(fakePath); + assert.strictEqual(result, 'chunkValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('corpus', async () => { - const fakePath = "/rendered/path/corpus"; - const expectedParameters = { - corpus: "corpusValue", - }; - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPath', () => { - const result = client.corpusPath("corpusValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusName', () => { - const result = client.matchCorpusFromCorpusName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpus', async () => { + const fakePath = '/rendered/path/corpus'; + const expectedParameters = { + corpus: 'corpusValue', + }; + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPath', () => { + const result = client.corpusPath('corpusValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.corpusPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusName', () => { + const result = client.matchCorpusFromCorpusName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.corpusPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('corpusPermissions', async () => { - const fakePath = "/rendered/path/corpusPermissions"; - const expectedParameters = { - corpus: "corpusValue", - permission: "permissionValue", - }; - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPermissionsPath', () => { - const result = client.corpusPermissionsPath("corpusValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusPermissionsName', () => { - const result = client.matchCorpusFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromCorpusPermissionsName', () => { - const result = client.matchPermissionFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpusPermissions', async () => { + const fakePath = '/rendered/path/corpusPermissions'; + const expectedParameters = { + corpus: 'corpusValue', + permission: 'permissionValue', + }; + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPermissionsPath', () => { + const result = client.corpusPermissionsPath( + 'corpusValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusPermissionsName', () => { + const result = client.matchCorpusFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromCorpusPermissionsName', () => { + const result = + client.matchPermissionFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('document', async () => { - const fakePath = "/rendered/path/document"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - }; - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.documentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.documentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('documentPath', () => { - const result = client.documentPath("corpusValue", "documentValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.documentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromDocumentName', () => { - const result = client.matchCorpusFromDocumentName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromDocumentName', () => { - const result = client.matchDocumentFromDocumentName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('document', async () => { + const fakePath = '/rendered/path/document'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + }; + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.documentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.documentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('documentPath', () => { + const result = client.documentPath('corpusValue', 'documentValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.documentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromDocumentName', () => { + const result = client.matchCorpusFromDocumentName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromDocumentName', () => { + const result = client.matchDocumentFromDocumentName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('file', async () => { - const fakePath = "/rendered/path/file"; - const expectedParameters = { - file: "fileValue", - }; - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.filePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.filePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('filePath', () => { - const result = client.filePath("fileValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.filePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFileFromFileName', () => { - const result = client.matchFileFromFileName(fakePath); - assert.strictEqual(result, "fileValue"); - assert((client.pathTemplates.filePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('file', async () => { + const fakePath = '/rendered/path/file'; + const expectedParameters = { + file: 'fileValue', + }; + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.filePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.filePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('filePath', () => { + const result = client.filePath('fileValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.filePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFileFromFileName', () => { + const result = client.matchFileFromFileName(fakePath); + assert.strictEqual(result, 'fileValue'); + assert( + (client.pathTemplates.filePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModel', async () => { - const fakePath = "/rendered/path/tunedModel"; - const expectedParameters = { - tuned_model: "tunedModelValue", - }; - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPath', () => { - const result = client.tunedModelPath("tunedModelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelName', () => { - const result = client.matchTunedModelFromTunedModelName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModel', async () => { + const fakePath = '/rendered/path/tunedModel'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + }; + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPath', () => { + const result = client.tunedModelPath('tunedModelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.tunedModelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelName', () => { + const result = client.matchTunedModelFromTunedModelName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.tunedModelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModelPermissions', async () => { - const fakePath = "/rendered/path/tunedModelPermissions"; - const expectedParameters = { - tuned_model: "tunedModelValue", - permission: "permissionValue", - }; - const client = new fileserviceModule.v1beta.FileServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPermissionsPath', () => { - const result = client.tunedModelPermissionsPath("tunedModelValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelPermissionsName', () => { - const result = client.matchTunedModelFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromTunedModelPermissionsName', () => { - const result = client.matchPermissionFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModelPermissions', async () => { + const fakePath = '/rendered/path/tunedModelPermissions'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + permission: 'permissionValue', + }; + const client = new fileserviceModule.v1beta.FileServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPermissionsPath', () => { + const result = client.tunedModelPermissionsPath( + 'tunedModelValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelPermissionsName', () => { + const result = + client.matchTunedModelFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromTunedModelPermissionsName', () => { + const result = + client.matchPermissionFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_generative_service_v1.ts b/packages/google-ai-generativelanguage/test/gapic_generative_service_v1.ts index 8de331441042..7e8241071b50 100644 --- a/packages/google-ai-generativelanguage/test/gapic_generative_service_v1.ts +++ b/packages/google-ai-generativelanguage/test/gapic_generative_service_v1.ts @@ -19,815 +19,1017 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as generativeserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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); } describe('v1.GenerativeServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient(); + 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 = generativeserviceModule.v1.GenerativeServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = generativeserviceModule.v1.GenerativeServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 = + generativeserviceModule.v1.GenerativeServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + generativeserviceModule.v1.GenerativeServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.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 generativeserviceModule.v1.GenerativeServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 generativeserviceModule.v1.GenerativeServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 generativeserviceModule.v1.GenerativeServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('has port', () => { - const port = generativeserviceModule.v1.GenerativeServiceClient.port; - assert(port); - assert(typeof port === 'number'); + 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 generativeserviceModule.v1.GenerativeServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with no option', () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient(); - assert(client); + 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 generativeserviceModule.v1.GenerativeServiceClient( + { universeDomain: 'configured.example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with gRPC fallback', () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - fallback: true, - }); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new generativeserviceModule.v1.GenerativeServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.generativeServiceStub, undefined); - await client.initialize(); - assert(client.generativeServiceStub); - }); + it('has port', () => { + const port = generativeserviceModule.v1.GenerativeServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the initialized client', done => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.generativeServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient(); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.generativeServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - 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 initialize method and supports deferred initialization', async () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.generativeServiceStub, undefined); + await client.initialize(); + assert(client.generativeServiceStub); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - 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('has close method for the initialized client', (done) => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.generativeServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('generateContent', () => { - it('invokes generateContent without error', async () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.GenerateContentResponse() - ); - client.innerApiCalls.generateContent = stubSimpleCall(expectedResponse); - const [response] = await client.generateContent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateContent 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 generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.generativeServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes generateContent without error using callback', async () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.GenerateContentResponse() - ); - client.innerApiCalls.generateContent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.generateContent( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1.IGenerateContentResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateContent 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 generativeserviceModule.v1.GenerativeServiceClient({ + 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 generateContent with error', async () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.generateContent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.generateContent(request), expectedError); - const actualRequest = (client.innerApiCalls.generateContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateContent 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 generativeserviceModule.v1.GenerativeServiceClient({ + 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 generateContent with closed client', async () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.generateContent(request), expectedError); - }); + describe('generateContent', () => { + it('invokes generateContent without error', async () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.GenerateContentResponse(), + ); + client.innerApiCalls.generateContent = stubSimpleCall(expectedResponse); + const [response] = await client.generateContent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('embedContent', () => { - it('invokes embedContent without error', async () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.EmbedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.EmbedContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.EmbedContentResponse() - ); - client.innerApiCalls.embedContent = stubSimpleCall(expectedResponse); - const [response] = await client.embedContent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.embedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.embedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes generateContent without error using callback', async () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.GenerateContentResponse(), + ); + client.innerApiCalls.generateContent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.generateContent( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1.IGenerateContentResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes embedContent without error using callback', async () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.EmbedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.EmbedContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.EmbedContentResponse() - ); - client.innerApiCalls.embedContent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.embedContent( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1.IEmbedContentResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.embedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.embedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes generateContent with error', async () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.generateContent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.generateContent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.generateContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes embedContent with error', async () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.EmbedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.EmbedContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.embedContent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.embedContent(request), expectedError); - const actualRequest = (client.innerApiCalls.embedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.embedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes generateContent with closed client', async () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.generateContent(request), expectedError); + }); + }); - it('invokes embedContent with closed client', async () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.EmbedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.EmbedContentRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.embedContent(request), expectedError); - }); + describe('embedContent', () => { + it('invokes embedContent without error', async () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.EmbedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.EmbedContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.EmbedContentResponse(), + ); + client.innerApiCalls.embedContent = stubSimpleCall(expectedResponse); + const [response] = await client.embedContent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.embedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.embedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('batchEmbedContents', () => { - it('invokes batchEmbedContents without error', async () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.BatchEmbedContentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.BatchEmbedContentsRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.BatchEmbedContentsResponse() - ); - client.innerApiCalls.batchEmbedContents = stubSimpleCall(expectedResponse); - const [response] = await client.batchEmbedContents(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchEmbedContents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchEmbedContents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes embedContent without error using callback', async () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.EmbedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.EmbedContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.EmbedContentResponse(), + ); + client.innerApiCalls.embedContent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.embedContent( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1.IEmbedContentResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.embedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.embedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchEmbedContents without error using callback', async () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.BatchEmbedContentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.BatchEmbedContentsRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.BatchEmbedContentsResponse() - ); - client.innerApiCalls.batchEmbedContents = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchEmbedContents( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1.IBatchEmbedContentsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchEmbedContents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchEmbedContents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes embedContent with error', async () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.EmbedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.EmbedContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.embedContent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.embedContent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.embedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.embedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchEmbedContents with error', async () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.BatchEmbedContentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.BatchEmbedContentsRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchEmbedContents = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchEmbedContents(request), expectedError); - const actualRequest = (client.innerApiCalls.batchEmbedContents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchEmbedContents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes embedContent with closed client', async () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.EmbedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.EmbedContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.embedContent(request), expectedError); + }); + }); - it('invokes batchEmbedContents with closed client', async () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.BatchEmbedContentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.BatchEmbedContentsRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchEmbedContents(request), expectedError); - }); + describe('batchEmbedContents', () => { + it('invokes batchEmbedContents without error', async () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.BatchEmbedContentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.BatchEmbedContentsRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.BatchEmbedContentsResponse(), + ); + client.innerApiCalls.batchEmbedContents = + stubSimpleCall(expectedResponse); + const [response] = await client.batchEmbedContents(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchEmbedContents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchEmbedContents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('countTokens', () => { - it('invokes countTokens without error', async () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.CountTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.CountTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.CountTokensResponse() - ); - client.innerApiCalls.countTokens = stubSimpleCall(expectedResponse); - const [response] = await client.countTokens(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.countTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchEmbedContents without error using callback', async () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.BatchEmbedContentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.BatchEmbedContentsRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.BatchEmbedContentsResponse(), + ); + client.innerApiCalls.batchEmbedContents = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchEmbedContents( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1.IBatchEmbedContentsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchEmbedContents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchEmbedContents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countTokens without error using callback', async () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.CountTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.CountTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.CountTokensResponse() - ); - client.innerApiCalls.countTokens = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.countTokens( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1.ICountTokensResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.countTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchEmbedContents with error', async () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.BatchEmbedContentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.BatchEmbedContentsRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchEmbedContents = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.batchEmbedContents(request), expectedError); + const actualRequest = ( + client.innerApiCalls.batchEmbedContents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchEmbedContents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countTokens with error', async () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.CountTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.CountTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.countTokens = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.countTokens(request), expectedError); - const actualRequest = (client.innerApiCalls.countTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchEmbedContents with closed client', async () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.BatchEmbedContentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.BatchEmbedContentsRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.batchEmbedContents(request), expectedError); + }); + }); - it('invokes countTokens with closed client', async () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.CountTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.CountTokensRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.countTokens(request), expectedError); - }); + describe('countTokens', () => { + it('invokes countTokens without error', async () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.CountTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.CountTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.CountTokensResponse(), + ); + client.innerApiCalls.countTokens = stubSimpleCall(expectedResponse); + const [response] = await client.countTokens(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.countTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('streamGenerateContent', () => { - it('invokes streamGenerateContent without error', async () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.GenerateContentResponse() - ); - client.innerApiCalls.streamGenerateContent = stubServerStreamingCall(expectedResponse); - const stream = client.streamGenerateContent(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.ai.generativelanguage.v1.GenerateContentResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.streamGenerateContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.streamGenerateContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes countTokens without error using callback', async () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.CountTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.CountTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.CountTokensResponse(), + ); + client.innerApiCalls.countTokens = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.countTokens( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1.ICountTokensResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.countTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes streamGenerateContent without error and gaxServerStreamingRetries enabled', async () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - gaxServerStreamingRetries: true - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.GenerateContentResponse() - ); - client.innerApiCalls.streamGenerateContent = stubServerStreamingCall(expectedResponse); - const stream = client.streamGenerateContent(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.ai.generativelanguage.v1.GenerateContentResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.streamGenerateContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.streamGenerateContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes countTokens with error', async () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.CountTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.CountTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.countTokens = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.countTokens(request), expectedError); + const actualRequest = ( + client.innerApiCalls.countTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes countTokens with closed client', async () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.CountTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.CountTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.countTokens(request), expectedError); + }); + }); - it('invokes streamGenerateContent with error', async () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.streamGenerateContent = stubServerStreamingCall(undefined, expectedError); - const stream = client.streamGenerateContent(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.ai.generativelanguage.v1.GenerateContentResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - const actualRequest = (client.innerApiCalls.streamGenerateContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.streamGenerateContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + describe('streamGenerateContent', () => { + it('invokes streamGenerateContent without error', async () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.GenerateContentResponse(), + ); + client.innerApiCalls.streamGenerateContent = + stubServerStreamingCall(expectedResponse); + const stream = client.streamGenerateContent(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1.GenerateContentResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.streamGenerateContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamGenerateContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes streamGenerateContent with closed client', async () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - const stream = client.streamGenerateContent(request, {retryRequestOptions: {noResponseRetries: 0}}); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.ai.generativelanguage.v1.GenerateContentResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); + it('invokes streamGenerateContent without error and gaxServerStreamingRetries enabled', async () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + gaxServerStreamingRetries: true, + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.GenerateContentResponse(), + ); + client.innerApiCalls.streamGenerateContent = + stubServerStreamingCall(expectedResponse); + const stream = client.streamGenerateContent(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1.GenerateContentResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); - it('should create a client with gaxServerStreamingRetries enabled', () => { - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - gaxServerStreamingRetries: true, - }); - assert(client); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.streamGenerateContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamGenerateContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes streamGenerateContent with error', async () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.streamGenerateContent = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.streamGenerateContent(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1.GenerateContentResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.streamGenerateContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamGenerateContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new generativeserviceModule.v1.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes streamGenerateContent with closed client', async () => { + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + const stream = client.streamGenerateContent(request, { + retryRequestOptions: { noResponseRetries: 0 }, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1.GenerateContentResponse, + ) => { + 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 generativeserviceModule.v1.GenerativeServiceClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('Path templates', () => { + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = new generativeserviceModule.v1.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_generative_service_v1alpha.ts b/packages/google-ai-generativelanguage/test/gapic_generative_service_v1alpha.ts index 803da9ea4b26..2305410dea20 100644 --- a/packages/google-ai-generativelanguage/test/gapic_generative_service_v1alpha.ts +++ b/packages/google-ai-generativelanguage/test/gapic_generative_service_v1alpha.ts @@ -19,1276 +19,1691 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as generativeserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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); } describe('v1alpha.GenerativeServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.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 = generativeserviceModule.v1alpha.GenerativeServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + it('has universeDomain', () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = generativeserviceModule.v1alpha.GenerativeServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 = + generativeserviceModule.v1alpha.GenerativeServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + generativeserviceModule.v1alpha.GenerativeServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + universeDomain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + universe_domain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.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 generativeserviceModule.v1alpha.GenerativeServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 generativeserviceModule.v1alpha.GenerativeServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 generativeserviceModule.v1alpha.GenerativeServiceClient({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 generativeserviceModule.v1alpha.GenerativeServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = generativeserviceModule.v1alpha.GenerativeServiceClient.port; - assert(port); - assert(typeof port === 'number'); + 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 generativeserviceModule.v1alpha.GenerativeServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = generativeserviceModule.v1alpha.GenerativeServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.generativeServiceStub, undefined); - await client.initialize(); - assert(client.generativeServiceStub); - }); + it('should create a client with no option', () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.generativeServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('should create a client with gRPC fallback', () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + fallback: true, }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.generativeServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has initialize method and supports deferred initialization', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.generativeServiceStub, undefined); + await client.initialize(); + assert(client.generativeServiceStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - 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 close method for the initialized client', (done) => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - 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); + client.initialize().catch((err) => { + throw err; + }); + assert(client.generativeServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('generateContent', () => { - it('invokes generateContent without error', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateContentResponse() - ); - client.innerApiCalls.generateContent = stubSimpleCall(expectedResponse); - const [response] = await client.generateContent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateContent 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 generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes generateContent without error using callback', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateContentResponse() - ); - client.innerApiCalls.generateContent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.generateContent( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IGenerateContentResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + assert.strictEqual(client.generativeServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes generateContent with error', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.generateContent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.generateContent(request), expectedError); - const actualRequest = (client.innerApiCalls.generateContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateContent 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 generativeserviceModule.v1alpha.GenerativeServiceClient({ + 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 generateContent with closed client', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.generateContent(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + 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('generateAnswer', () => { - it('invokes generateAnswer without error', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateAnswerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GenerateAnswerRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateAnswerResponse() - ); - client.innerApiCalls.generateAnswer = stubSimpleCall(expectedResponse); - const [response] = await client.generateAnswer(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateAnswer as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateAnswer as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('generateContent', () => { + it('invokes generateContent without error', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateContentResponse(), + ); + client.innerApiCalls.generateContent = stubSimpleCall(expectedResponse); + const [response] = await client.generateContent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes generateAnswer without error using callback', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateAnswerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GenerateAnswerRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateAnswerResponse() - ); - client.innerApiCalls.generateAnswer = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.generateAnswer( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateAnswer as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateAnswer as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes generateContent without error using callback', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateContentResponse(), + ); + client.innerApiCalls.generateContent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.generateContent( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.IGenerateContentResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes generateAnswer with error', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateAnswerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GenerateAnswerRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.generateAnswer = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.generateAnswer(request), expectedError); - const actualRequest = (client.innerApiCalls.generateAnswer as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateAnswer as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes generateContent with error', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.generateContent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.generateContent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.generateContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes generateAnswer with closed client', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateAnswerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GenerateAnswerRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.generateAnswer(request), expectedError); + it('invokes generateContent with closed client', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.generateContent(request), expectedError); }); - - describe('embedContent', () => { - it('invokes embedContent without error', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.EmbedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.EmbedContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.EmbedContentResponse() - ); - client.innerApiCalls.embedContent = stubSimpleCall(expectedResponse); - const [response] = await client.embedContent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.embedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.embedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('generateAnswer', () => { + it('invokes generateAnswer without error', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateAnswerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GenerateAnswerRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateAnswerResponse(), + ); + client.innerApiCalls.generateAnswer = stubSimpleCall(expectedResponse); + const [response] = await client.generateAnswer(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateAnswer as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateAnswer as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes embedContent without error using callback', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.EmbedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.EmbedContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.EmbedContentResponse() - ); - client.innerApiCalls.embedContent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.embedContent( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IEmbedContentResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.embedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.embedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes generateAnswer without error using callback', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateAnswerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GenerateAnswerRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateAnswerResponse(), + ); + client.innerApiCalls.generateAnswer = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.generateAnswer( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.IGenerateAnswerResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateAnswer as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateAnswer as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes embedContent with error', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.EmbedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.EmbedContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.embedContent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.embedContent(request), expectedError); - const actualRequest = (client.innerApiCalls.embedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.embedContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes generateAnswer with error', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateAnswerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GenerateAnswerRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.generateAnswer = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.generateAnswer(request), expectedError); + const actualRequest = ( + client.innerApiCalls.generateAnswer as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateAnswer as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes embedContent with closed client', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.EmbedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.EmbedContentRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.embedContent(request), expectedError); + it('invokes generateAnswer with closed client', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateAnswerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GenerateAnswerRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.generateAnswer(request), expectedError); }); - - describe('batchEmbedContents', () => { - it('invokes batchEmbedContents without error', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchEmbedContentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.BatchEmbedContentsRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchEmbedContentsResponse() - ); - client.innerApiCalls.batchEmbedContents = stubSimpleCall(expectedResponse); - const [response] = await client.batchEmbedContents(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchEmbedContents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchEmbedContents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('embedContent', () => { + it('invokes embedContent without error', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.EmbedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.EmbedContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.EmbedContentResponse(), + ); + client.innerApiCalls.embedContent = stubSimpleCall(expectedResponse); + const [response] = await client.embedContent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.embedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.embedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchEmbedContents without error using callback', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchEmbedContentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.BatchEmbedContentsRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchEmbedContentsResponse() - ); - client.innerApiCalls.batchEmbedContents = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchEmbedContents( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchEmbedContents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchEmbedContents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes embedContent without error using callback', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.EmbedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.EmbedContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.EmbedContentResponse(), + ); + client.innerApiCalls.embedContent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.embedContent( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.IEmbedContentResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.embedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.embedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchEmbedContents with error', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchEmbedContentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.BatchEmbedContentsRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchEmbedContents = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchEmbedContents(request), expectedError); - const actualRequest = (client.innerApiCalls.batchEmbedContents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchEmbedContents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes embedContent with error', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.EmbedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.EmbedContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.embedContent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.embedContent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.embedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.embedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchEmbedContents with closed client', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchEmbedContentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.BatchEmbedContentsRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchEmbedContents(request), expectedError); + it('invokes embedContent with closed client', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.EmbedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.EmbedContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.embedContent(request), expectedError); }); - - describe('countTokens', () => { - it('invokes countTokens without error', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CountTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CountTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CountTokensResponse() - ); - client.innerApiCalls.countTokens = stubSimpleCall(expectedResponse); - const [response] = await client.countTokens(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.countTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('batchEmbedContents', () => { + it('invokes batchEmbedContents without error', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchEmbedContentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.BatchEmbedContentsRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchEmbedContentsResponse(), + ); + client.innerApiCalls.batchEmbedContents = + stubSimpleCall(expectedResponse); + const [response] = await client.batchEmbedContents(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchEmbedContents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchEmbedContents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countTokens without error using callback', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CountTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CountTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CountTokensResponse() - ); - client.innerApiCalls.countTokens = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.countTokens( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.ICountTokensResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.countTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes batchEmbedContents without error using callback', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchEmbedContentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.BatchEmbedContentsRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchEmbedContentsResponse(), + ); + client.innerApiCalls.batchEmbedContents = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchEmbedContents( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.IBatchEmbedContentsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchEmbedContents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchEmbedContents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countTokens with error', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CountTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CountTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.countTokens = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.countTokens(request), expectedError); - const actualRequest = (client.innerApiCalls.countTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes batchEmbedContents with error', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchEmbedContentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.BatchEmbedContentsRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchEmbedContents = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.batchEmbedContents(request), expectedError); + const actualRequest = ( + client.innerApiCalls.batchEmbedContents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchEmbedContents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countTokens with closed client', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CountTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CountTokensRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.countTokens(request), expectedError); + it('invokes batchEmbedContents with closed client', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchEmbedContentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.BatchEmbedContentsRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.batchEmbedContents(request), expectedError); }); - - describe('streamGenerateContent', () => { - it('invokes streamGenerateContent without error', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateContentResponse() - ); - client.innerApiCalls.streamGenerateContent = stubServerStreamingCall(expectedResponse); - const stream = client.streamGenerateContent(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.ai.generativelanguage.v1alpha.GenerateContentResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.streamGenerateContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.streamGenerateContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('countTokens', () => { + it('invokes countTokens without error', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CountTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CountTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CountTokensResponse(), + ); + client.innerApiCalls.countTokens = stubSimpleCall(expectedResponse); + const [response] = await client.countTokens(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.countTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes streamGenerateContent without error and gaxServerStreamingRetries enabled', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - gaxServerStreamingRetries: true - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateContentResponse() - ); - client.innerApiCalls.streamGenerateContent = stubServerStreamingCall(expectedResponse); - const stream = client.streamGenerateContent(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.ai.generativelanguage.v1alpha.GenerateContentResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.streamGenerateContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.streamGenerateContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes countTokens without error using callback', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CountTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CountTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CountTokensResponse(), + ); + client.innerApiCalls.countTokens = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.countTokens( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.ICountTokensResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.countTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes streamGenerateContent with error', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.streamGenerateContent = stubServerStreamingCall(undefined, expectedError); - const stream = client.streamGenerateContent(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.ai.generativelanguage.v1alpha.GenerateContentResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - const actualRequest = (client.innerApiCalls.streamGenerateContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.streamGenerateContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes countTokens with error', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CountTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CountTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.countTokens = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.countTokens(request), expectedError); + const actualRequest = ( + client.innerApiCalls.countTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes streamGenerateContent with closed client', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - const stream = client.streamGenerateContent(request, {retryRequestOptions: {noResponseRetries: 0}}); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.ai.generativelanguage.v1alpha.GenerateContentResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); + it('invokes countTokens with closed client', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - it('should create a client with gaxServerStreamingRetries enabled', () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - gaxServerStreamingRetries: true, - }); - assert(client); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CountTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CountTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.countTokens(request), expectedError); + }); + }); + + describe('streamGenerateContent', () => { + it('invokes streamGenerateContent without error', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateContentResponse(), + ); + client.innerApiCalls.streamGenerateContent = + stubServerStreamingCall(expectedResponse); + const stream = client.streamGenerateContent(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1alpha.GenerateContentResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.streamGenerateContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamGenerateContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('bidiGenerateContent', () => { - it('invokes bidiGenerateContent without error', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BidiGenerateContentClientMessage() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BidiGenerateContentServerMessage() - ); - client.innerApiCalls.bidiGenerateContent = stubBidiStreamingCall(expectedResponse); - const stream = client.bidiGenerateContent(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.ai.generativelanguage.v1alpha.BidiGenerateContentServerMessage) => { - 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.bidiGenerateContent as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); + it('invokes streamGenerateContent without error and gaxServerStreamingRetries enabled', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + gaxServerStreamingRetries: true, }); - - it('invokes bidiGenerateContent with error', async () => { - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BidiGenerateContentClientMessage() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.bidiGenerateContent = stubBidiStreamingCall(undefined, expectedError); - const stream = client.bidiGenerateContent(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.ai.generativelanguage.v1alpha.BidiGenerateContentServerMessage) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.bidiGenerateContent as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateContentResponse(), + ); + client.innerApiCalls.streamGenerateContent = + stubServerStreamingCall(expectedResponse); + const stream = client.streamGenerateContent(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1alpha.GenerateContentResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.streamGenerateContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamGenerateContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('cachedContent', async () => { - const fakePath = "/rendered/path/cachedContent"; - const expectedParameters = { - id: "idValue", - }; - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.cachedContentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.cachedContentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('cachedContentPath', () => { - const result = client.cachedContentPath("idValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.cachedContentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchIdFromCachedContentName', () => { - const result = client.matchIdFromCachedContentName(fakePath); - assert.strictEqual(result, "idValue"); - assert((client.pathTemplates.cachedContentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes streamGenerateContent with error', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - describe('chunk', async () => { - const fakePath = "/rendered/path/chunk"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - chunk: "chunkValue", - }; - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.chunkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.chunkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('chunkPath', () => { - const result = client.chunkPath("corpusValue", "documentValue", "chunkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.chunkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromChunkName', () => { - const result = client.matchCorpusFromChunkName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromChunkName', () => { - const result = client.matchDocumentFromChunkName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChunkFromChunkName', () => { - const result = client.matchChunkFromChunkName(fakePath); - assert.strictEqual(result, "chunkValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.streamGenerateContent = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.streamGenerateContent(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1alpha.GenerateContentResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.streamGenerateContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamGenerateContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('corpus', async () => { - const fakePath = "/rendered/path/corpus"; - const expectedParameters = { - corpus: "corpusValue", - }; - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPath', () => { - const result = client.corpusPath("corpusValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusName', () => { - const result = client.matchCorpusFromCorpusName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes streamGenerateContent with closed client', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - describe('corpusPermissions', async () => { - const fakePath = "/rendered/path/corpusPermissions"; - const expectedParameters = { - corpus: "corpusValue", - permission: "permissionValue", - }; - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPermissionsPath', () => { - const result = client.corpusPermissionsPath("corpusValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusPermissionsName', () => { - const result = client.matchCorpusFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromCorpusPermissionsName', () => { - const result = client.matchPermissionFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + const stream = client.streamGenerateContent(request, { + retryRequestOptions: { noResponseRetries: 0 }, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1alpha.GenerateContentResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); - - describe('document', async () => { - const fakePath = "/rendered/path/document"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - }; - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.documentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.documentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('documentPath', () => { - const result = client.documentPath("corpusValue", "documentValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.documentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromDocumentName', () => { - const result = client.matchCorpusFromDocumentName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromDocumentName', () => { - const result = client.matchDocumentFromDocumentName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('bidiGenerateContent', () => { + it('invokes bidiGenerateContent without error', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BidiGenerateContentClientMessage(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BidiGenerateContentServerMessage(), + ); + client.innerApiCalls.bidiGenerateContent = + stubBidiStreamingCall(expectedResponse); + const stream = client.bidiGenerateContent(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1alpha.BidiGenerateContentServerMessage, + ) => { + 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.bidiGenerateContent as SinonStub) + .getCall(0) + .calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); - describe('file', async () => { - const fakePath = "/rendered/path/file"; - const expectedParameters = { - file: "fileValue", - }; - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.filePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.filePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('filePath', () => { - const result = client.filePath("fileValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.filePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes bidiGenerateContent with error', async () => { + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BidiGenerateContentClientMessage(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.bidiGenerateContent = stubBidiStreamingCall( + undefined, + expectedError, + ); + const stream = client.bidiGenerateContent(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1alpha.BidiGenerateContentServerMessage, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.bidiGenerateContent as SinonStub) + .getCall(0) + .calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('cachedContent', async () => { + const fakePath = '/rendered/path/cachedContent'; + const expectedParameters = { + id: 'idValue', + }; + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.cachedContentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.cachedContentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('cachedContentPath', () => { + const result = client.cachedContentPath('idValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.cachedContentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchIdFromCachedContentName', () => { + const result = client.matchIdFromCachedContentName(fakePath); + assert.strictEqual(result, 'idValue'); + assert( + (client.pathTemplates.cachedContentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchFileFromFileName', () => { - const result = client.matchFileFromFileName(fakePath); - assert.strictEqual(result, "fileValue"); - assert((client.pathTemplates.filePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('chunk', async () => { + const fakePath = '/rendered/path/chunk'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + chunk: 'chunkValue', + }; + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.chunkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.chunkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('chunkPath', () => { + const result = client.chunkPath( + 'corpusValue', + 'documentValue', + 'chunkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.chunkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromChunkName', () => { + const result = client.matchCorpusFromChunkName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromChunkName', () => { + const result = client.matchDocumentFromChunkName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChunkFromChunkName', () => { + const result = client.matchChunkFromChunkName(fakePath); + assert.strictEqual(result, 'chunkValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('corpus', async () => { + const fakePath = '/rendered/path/corpus'; + const expectedParameters = { + corpus: 'corpusValue', + }; + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPath', () => { + const result = client.corpusPath('corpusValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.corpusPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusName', () => { + const result = client.matchCorpusFromCorpusName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.corpusPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('corpusPermissions', async () => { + const fakePath = '/rendered/path/corpusPermissions'; + const expectedParameters = { + corpus: 'corpusValue', + permission: 'permissionValue', + }; + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.corpusPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPermissionsPath', () => { + const result = client.corpusPermissionsPath( + 'corpusValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusPermissionsName', () => { + const result = client.matchCorpusFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromCorpusPermissionsName', () => { + const result = + client.matchPermissionFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModel', async () => { - const fakePath = "/rendered/path/tunedModel"; - const expectedParameters = { - tuned_model: "tunedModelValue", - }; - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPath', () => { - const result = client.tunedModelPath("tunedModelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('document', async () => { + const fakePath = '/rendered/path/document'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + }; + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.documentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.documentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('documentPath', () => { + const result = client.documentPath('corpusValue', 'documentValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.documentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromDocumentName', () => { + const result = client.matchCorpusFromDocumentName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromDocumentName', () => { + const result = client.matchDocumentFromDocumentName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchTunedModelFromTunedModelName', () => { - const result = client.matchTunedModelFromTunedModelName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('file', async () => { + const fakePath = '/rendered/path/file'; + const expectedParameters = { + file: 'fileValue', + }; + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.filePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.filePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('filePath', () => { + const result = client.filePath('fileValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.filePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFileFromFileName', () => { + const result = client.matchFileFromFileName(fakePath); + assert.strictEqual(result, 'fileValue'); + assert( + (client.pathTemplates.filePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModelPermissions', async () => { - const fakePath = "/rendered/path/tunedModelPermissions"; - const expectedParameters = { - tuned_model: "tunedModelValue", - permission: "permissionValue", - }; - const client = new generativeserviceModule.v1alpha.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPermissionsPath', () => { - const result = client.tunedModelPermissionsPath("tunedModelValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchTunedModelFromTunedModelPermissionsName', () => { - const result = client.matchTunedModelFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('tunedModel', async () => { + const fakePath = '/rendered/path/tunedModel'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + }; + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPath', () => { + const result = client.tunedModelPath('tunedModelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.tunedModelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelName', () => { + const result = client.matchTunedModelFromTunedModelName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.tunedModelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchPermissionFromTunedModelPermissionsName', () => { - const result = client.matchPermissionFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('tunedModelPermissions', async () => { + const fakePath = '/rendered/path/tunedModelPermissions'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + permission: 'permissionValue', + }; + const client = + new generativeserviceModule.v1alpha.GenerativeServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.tunedModelPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPermissionsPath', () => { + const result = client.tunedModelPermissionsPath( + 'tunedModelValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelPermissionsName', () => { + const result = + client.matchTunedModelFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromTunedModelPermissionsName', () => { + const result = + client.matchPermissionFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_generative_service_v1beta.ts b/packages/google-ai-generativelanguage/test/gapic_generative_service_v1beta.ts index 7fbecb4b38b2..cb3eb674183d 100644 --- a/packages/google-ai-generativelanguage/test/gapic_generative_service_v1beta.ts +++ b/packages/google-ai-generativelanguage/test/gapic_generative_service_v1beta.ts @@ -19,1276 +19,1731 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as generativeserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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); } describe('v1beta.GenerativeServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient(); - 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 = generativeserviceModule.v1beta.GenerativeServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = generativeserviceModule.v1beta.GenerativeServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 generativeserviceModule.v1beta.GenerativeServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 generativeserviceModule.v1beta.GenerativeServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 generativeserviceModule.v1beta.GenerativeServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = generativeserviceModule.v1beta.GenerativeServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.generativeServiceStub, undefined); - await client.initialize(); - assert(client.generativeServiceStub); - }); - - it('has close method for the initialized client', done => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.generativeServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new generativeserviceModule.v1beta.GenerativeServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + }); - it('has close method for the non-initialized client', done => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.generativeServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has universeDomain', () => { + const client = + new generativeserviceModule.v1beta.GenerativeServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - 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()); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + generativeserviceModule.v1beta.GenerativeServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + generativeserviceModule.v1beta.GenerativeServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { universeDomain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - 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('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { universe_domain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); }); - describe('generateContent', () => { - it('invokes generateContent without error', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateContentResponse() - ); - client.innerApiCalls.generateContent = stubSimpleCall(expectedResponse); - const [response] = await client.generateContent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateContent 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 generativeserviceModule.v1beta.GenerativeServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('invokes generateContent without error using callback', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateContentResponse() - ); - client.innerApiCalls.generateContent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.generateContent( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IGenerateContentResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + 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 generativeserviceModule.v1beta.GenerativeServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('invokes generateContent with error', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.generateContent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.generateContent(request), expectedError); - const actualRequest = (client.innerApiCalls.generateContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new generativeserviceModule.v1beta.GenerativeServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes generateContent with closed client', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.generateContent(request), expectedError); - }); + it('has port', () => { + const port = generativeserviceModule.v1beta.GenerativeServiceClient.port; + assert(port); + assert(typeof port === 'number'); }); - describe('generateAnswer', () => { - it('invokes generateAnswer without error', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateAnswerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GenerateAnswerRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateAnswerResponse() - ); - client.innerApiCalls.generateAnswer = stubSimpleCall(expectedResponse); - const [response] = await client.generateAnswer(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateAnswer as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateAnswer 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 generativeserviceModule.v1beta.GenerativeServiceClient(); + assert(client); + }); - it('invokes generateAnswer without error using callback', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateAnswerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GenerateAnswerRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateAnswerResponse() - ); - client.innerApiCalls.generateAnswer = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.generateAnswer( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IGenerateAnswerResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateAnswer as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateAnswer 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 generativeserviceModule.v1beta.GenerativeServiceClient( + { + fallback: true, + }, + ); + assert(client); + }); - it('invokes generateAnswer with error', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateAnswerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GenerateAnswerRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.generateAnswer = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.generateAnswer(request), expectedError); - const actualRequest = (client.innerApiCalls.generateAnswer as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateAnswer 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 generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.generativeServiceStub, undefined); + await client.initialize(); + assert(client.generativeServiceStub); + }); - it('invokes generateAnswer with closed client', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateAnswerRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GenerateAnswerRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.generateAnswer(request), expectedError); + it('has close method for the initialized client', (done) => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + assert(client.generativeServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('embedContent', () => { - it('invokes embedContent without error', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.EmbedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.EmbedContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.EmbedContentResponse() - ); - client.innerApiCalls.embedContent = stubSimpleCall(expectedResponse); - const [response] = await client.embedContent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.embedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.embedContent 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 generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.generativeServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes embedContent without error using callback', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.EmbedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.EmbedContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.EmbedContentResponse() - ); - client.innerApiCalls.embedContent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.embedContent( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IEmbedContentResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.embedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.embedContent 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 generativeserviceModule.v1beta.GenerativeServiceClient( + { + 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 embedContent with error', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.EmbedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.EmbedContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.embedContent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.embedContent(request), expectedError); - const actualRequest = (client.innerApiCalls.embedContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.embedContent 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 generativeserviceModule.v1beta.GenerativeServiceClient( + { + 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('generateContent', () => { + it('invokes generateContent without error', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateContentResponse(), + ); + client.innerApiCalls.generateContent = stubSimpleCall(expectedResponse); + const [response] = await client.generateContent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes embedContent with closed client', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.EmbedContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.EmbedContentRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.embedContent(request), expectedError); - }); + it('invokes generateContent without error using callback', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateContentResponse(), + ); + client.innerApiCalls.generateContent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.generateContent( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IGenerateContentResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('batchEmbedContents', () => { - it('invokes batchEmbedContents without error', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchEmbedContentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.BatchEmbedContentsRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchEmbedContentsResponse() - ); - client.innerApiCalls.batchEmbedContents = stubSimpleCall(expectedResponse); - const [response] = await client.batchEmbedContents(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchEmbedContents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchEmbedContents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes generateContent with error', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.generateContent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.generateContent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.generateContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchEmbedContents without error using callback', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchEmbedContentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.BatchEmbedContentsRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchEmbedContentsResponse() - ); - client.innerApiCalls.batchEmbedContents = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchEmbedContents( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchEmbedContents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchEmbedContents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes generateContent with closed client', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.generateContent(request), expectedError); + }); + }); + + describe('generateAnswer', () => { + it('invokes generateAnswer without error', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateAnswerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GenerateAnswerRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateAnswerResponse(), + ); + client.innerApiCalls.generateAnswer = stubSimpleCall(expectedResponse); + const [response] = await client.generateAnswer(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateAnswer as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateAnswer as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchEmbedContents with error', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchEmbedContentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.BatchEmbedContentsRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchEmbedContents = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchEmbedContents(request), expectedError); - const actualRequest = (client.innerApiCalls.batchEmbedContents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchEmbedContents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes generateAnswer without error using callback', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateAnswerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GenerateAnswerRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateAnswerResponse(), + ); + client.innerApiCalls.generateAnswer = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.generateAnswer( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IGenerateAnswerResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateAnswer as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateAnswer as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchEmbedContents with closed client', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchEmbedContentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.BatchEmbedContentsRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchEmbedContents(request), expectedError); - }); + it('invokes generateAnswer with error', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateAnswerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GenerateAnswerRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.generateAnswer = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.generateAnswer(request), expectedError); + const actualRequest = ( + client.innerApiCalls.generateAnswer as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateAnswer as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('countTokens', () => { - it('invokes countTokens without error', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CountTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CountTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CountTokensResponse() - ); - client.innerApiCalls.countTokens = stubSimpleCall(expectedResponse); - const [response] = await client.countTokens(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.countTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes generateAnswer with closed client', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateAnswerRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GenerateAnswerRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.generateAnswer(request), expectedError); + }); + }); + + describe('embedContent', () => { + it('invokes embedContent without error', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.EmbedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.EmbedContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.EmbedContentResponse(), + ); + client.innerApiCalls.embedContent = stubSimpleCall(expectedResponse); + const [response] = await client.embedContent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.embedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.embedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countTokens without error using callback', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CountTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CountTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CountTokensResponse() - ); - client.innerApiCalls.countTokens = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.countTokens( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.ICountTokensResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.countTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes embedContent without error using callback', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.EmbedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.EmbedContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.EmbedContentResponse(), + ); + client.innerApiCalls.embedContent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.embedContent( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IEmbedContentResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.embedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.embedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countTokens with error', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CountTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CountTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.countTokens = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.countTokens(request), expectedError); - const actualRequest = (client.innerApiCalls.countTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes embedContent with error', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.EmbedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.EmbedContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.embedContent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.embedContent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.embedContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.embedContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countTokens with closed client', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CountTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CountTokensRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.countTokens(request), expectedError); - }); + it('invokes embedContent with closed client', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.EmbedContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.EmbedContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.embedContent(request), expectedError); + }); + }); + + describe('batchEmbedContents', () => { + it('invokes batchEmbedContents without error', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchEmbedContentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.BatchEmbedContentsRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchEmbedContentsResponse(), + ); + client.innerApiCalls.batchEmbedContents = + stubSimpleCall(expectedResponse); + const [response] = await client.batchEmbedContents(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchEmbedContents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchEmbedContents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('streamGenerateContent', () => { - it('invokes streamGenerateContent without error', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateContentResponse() - ); - client.innerApiCalls.streamGenerateContent = stubServerStreamingCall(expectedResponse); - const stream = client.streamGenerateContent(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta.GenerateContentResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.streamGenerateContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.streamGenerateContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchEmbedContents without error using callback', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchEmbedContentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.BatchEmbedContentsRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchEmbedContentsResponse(), + ); + client.innerApiCalls.batchEmbedContents = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchEmbedContents( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IBatchEmbedContentsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchEmbedContents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchEmbedContents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes streamGenerateContent without error and gaxServerStreamingRetries enabled', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - gaxServerStreamingRetries: true - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateContentResponse() - ); - client.innerApiCalls.streamGenerateContent = stubServerStreamingCall(expectedResponse); - const stream = client.streamGenerateContent(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta.GenerateContentResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.streamGenerateContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.streamGenerateContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchEmbedContents with error', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchEmbedContentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.BatchEmbedContentsRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchEmbedContents = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.batchEmbedContents(request), expectedError); + const actualRequest = ( + client.innerApiCalls.batchEmbedContents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchEmbedContents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes streamGenerateContent with error', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.streamGenerateContent = stubServerStreamingCall(undefined, expectedError); - const stream = client.streamGenerateContent(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta.GenerateContentResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - const actualRequest = (client.innerApiCalls.streamGenerateContent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.streamGenerateContent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchEmbedContents with closed client', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchEmbedContentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.BatchEmbedContentsRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.batchEmbedContents(request), expectedError); + }); + }); + + describe('countTokens', () => { + it('invokes countTokens without error', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CountTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CountTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CountTokensResponse(), + ); + client.innerApiCalls.countTokens = stubSimpleCall(expectedResponse); + const [response] = await client.countTokens(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.countTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes streamGenerateContent with closed client', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateContentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GenerateContentRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - const stream = client.streamGenerateContent(request, {retryRequestOptions: {noResponseRetries: 0}}); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta.GenerateContentResponse) => { - 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 generativeserviceModule.v1beta.GenerativeServiceClient({ - gaxServerStreamingRetries: true, - }); - assert(client); - }); + it('invokes countTokens without error using callback', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CountTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CountTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CountTokensResponse(), + ); + client.innerApiCalls.countTokens = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.countTokens( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.ICountTokensResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.countTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('bidiGenerateContent', () => { - it('invokes bidiGenerateContent without error', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BidiGenerateContentClientMessage() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BidiGenerateContentServerMessage() - ); - client.innerApiCalls.bidiGenerateContent = stubBidiStreamingCall(expectedResponse); - const stream = client.bidiGenerateContent(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta.BidiGenerateContentServerMessage) => { - 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.bidiGenerateContent as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); - }); + it('invokes countTokens with error', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CountTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CountTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.countTokens = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.countTokens(request), expectedError); + const actualRequest = ( + client.innerApiCalls.countTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes bidiGenerateContent with error', async () => { - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BidiGenerateContentClientMessage() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.bidiGenerateContent = stubBidiStreamingCall(undefined, expectedError); - const stream = client.bidiGenerateContent(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta.BidiGenerateContentServerMessage) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.bidiGenerateContent as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); + it('invokes countTokens with closed client', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CountTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CountTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.countTokens(request), expectedError); + }); + }); + + describe('streamGenerateContent', () => { + it('invokes streamGenerateContent without error', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateContentResponse(), + ); + client.innerApiCalls.streamGenerateContent = + stubServerStreamingCall(expectedResponse); + const stream = client.streamGenerateContent(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1beta.GenerateContentResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.streamGenerateContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamGenerateContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('cachedContent', async () => { - const fakePath = "/rendered/path/cachedContent"; - const expectedParameters = { - id: "idValue", - }; - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.cachedContentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.cachedContentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('cachedContentPath', () => { - const result = client.cachedContentPath("idValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.cachedContentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchIdFromCachedContentName', () => { - const result = client.matchIdFromCachedContentName(fakePath); - assert.strictEqual(result, "idValue"); - assert((client.pathTemplates.cachedContentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes streamGenerateContent without error and gaxServerStreamingRetries enabled', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + gaxServerStreamingRetries: true, + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateContentResponse(), + ); + client.innerApiCalls.streamGenerateContent = + stubServerStreamingCall(expectedResponse); + const stream = client.streamGenerateContent(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1beta.GenerateContentResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.streamGenerateContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamGenerateContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('chunk', async () => { - const fakePath = "/rendered/path/chunk"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - chunk: "chunkValue", - }; - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.chunkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.chunkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('chunkPath', () => { - const result = client.chunkPath("corpusValue", "documentValue", "chunkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.chunkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromChunkName', () => { - const result = client.matchCorpusFromChunkName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromChunkName', () => { - const result = client.matchDocumentFromChunkName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChunkFromChunkName', () => { - const result = client.matchChunkFromChunkName(fakePath); - assert.strictEqual(result, "chunkValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes streamGenerateContent with error', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.streamGenerateContent = stubServerStreamingCall( + undefined, + expectedError, + ); + const stream = client.streamGenerateContent(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1beta.GenerateContentResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.streamGenerateContent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.streamGenerateContent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('corpus', async () => { - const fakePath = "/rendered/path/corpus"; - const expectedParameters = { - corpus: "corpusValue", - }; - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPath', () => { - const result = client.corpusPath("corpusValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusName', () => { - const result = client.matchCorpusFromCorpusName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes streamGenerateContent with closed client', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateContentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GenerateContentRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + const stream = client.streamGenerateContent(request, { + retryRequestOptions: { noResponseRetries: 0 }, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1beta.GenerateContentResponse, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); - - describe('corpusPermissions', async () => { - const fakePath = "/rendered/path/corpusPermissions"; - const expectedParameters = { - corpus: "corpusValue", - permission: "permissionValue", - }; - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPermissionsPath', () => { - const result = client.corpusPermissionsPath("corpusValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusPermissionsName', () => { - const result = client.matchCorpusFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromCorpusPermissionsName', () => { - const result = client.matchPermissionFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + gaxServerStreamingRetries: true, + }, + ); + assert(client); + }); + }); + + describe('bidiGenerateContent', () => { + it('invokes bidiGenerateContent without error', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BidiGenerateContentClientMessage(), + ); + + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BidiGenerateContentServerMessage(), + ); + client.innerApiCalls.bidiGenerateContent = + stubBidiStreamingCall(expectedResponse); + const stream = client.bidiGenerateContent(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1beta.BidiGenerateContentServerMessage, + ) => { + 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.bidiGenerateContent as SinonStub) + .getCall(0) + .calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); - describe('document', async () => { - const fakePath = "/rendered/path/document"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - }; - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.documentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.documentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('documentPath', () => { - const result = client.documentPath("corpusValue", "documentValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.documentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromDocumentName', () => { - const result = client.matchCorpusFromDocumentName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromDocumentName', () => { - const result = client.matchDocumentFromDocumentName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes bidiGenerateContent with error', async () => { + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BidiGenerateContentClientMessage(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.bidiGenerateContent = stubBidiStreamingCall( + undefined, + expectedError, + ); + const stream = client.bidiGenerateContent(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1beta.BidiGenerateContentServerMessage, + ) => { + resolve(response); + }, + ); + stream.on('error', (err: Error) => { + reject(err); }); + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.bidiGenerateContent as SinonStub) + .getCall(0) + .calledWith(null), + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('cachedContent', async () => { + const fakePath = '/rendered/path/cachedContent'; + const expectedParameters = { + id: 'idValue', + }; + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.cachedContentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.cachedContentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('cachedContentPath', () => { + const result = client.cachedContentPath('idValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.cachedContentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchIdFromCachedContentName', () => { + const result = client.matchIdFromCachedContentName(fakePath); + assert.strictEqual(result, 'idValue'); + assert( + (client.pathTemplates.cachedContentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('file', async () => { - const fakePath = "/rendered/path/file"; - const expectedParameters = { - file: "fileValue", - }; - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.filePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.filePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('filePath', () => { - const result = client.filePath("fileValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.filePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFileFromFileName', () => { - const result = client.matchFileFromFileName(fakePath); - assert.strictEqual(result, "fileValue"); - assert((client.pathTemplates.filePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('chunk', async () => { + const fakePath = '/rendered/path/chunk'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + chunk: 'chunkValue', + }; + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.chunkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.chunkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('chunkPath', () => { + const result = client.chunkPath( + 'corpusValue', + 'documentValue', + 'chunkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.chunkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromChunkName', () => { + const result = client.matchCorpusFromChunkName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromChunkName', () => { + const result = client.matchDocumentFromChunkName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChunkFromChunkName', () => { + const result = client.matchChunkFromChunkName(fakePath); + assert.strictEqual(result, 'chunkValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('corpus', async () => { + const fakePath = '/rendered/path/corpus'; + const expectedParameters = { + corpus: 'corpusValue', + }; + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.corpusPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPath', () => { + const result = client.corpusPath('corpusValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.corpusPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusName', () => { + const result = client.matchCorpusFromCorpusName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.corpusPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpusPermissions', async () => { + const fakePath = '/rendered/path/corpusPermissions'; + const expectedParameters = { + corpus: 'corpusValue', + permission: 'permissionValue', + }; + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.corpusPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPermissionsPath', () => { + const result = client.corpusPermissionsPath( + 'corpusValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusPermissionsName', () => { + const result = client.matchCorpusFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromCorpusPermissionsName', () => { + const result = + client.matchPermissionFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModel', async () => { - const fakePath = "/rendered/path/tunedModel"; - const expectedParameters = { - tuned_model: "tunedModelValue", - }; - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPath', () => { - const result = client.tunedModelPath("tunedModelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('document', async () => { + const fakePath = '/rendered/path/document'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + }; + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.documentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.documentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('documentPath', () => { + const result = client.documentPath('corpusValue', 'documentValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.documentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromDocumentName', () => { + const result = client.matchCorpusFromDocumentName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromDocumentName', () => { + const result = client.matchDocumentFromDocumentName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchTunedModelFromTunedModelName', () => { - const result = client.matchTunedModelFromTunedModelName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('file', async () => { + const fakePath = '/rendered/path/file'; + const expectedParameters = { + file: 'fileValue', + }; + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.filePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.filePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('filePath', () => { + const result = client.filePath('fileValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.filePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFileFromFileName', () => { + const result = client.matchFileFromFileName(fakePath); + assert.strictEqual(result, 'fileValue'); + assert( + (client.pathTemplates.filePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModelPermissions', async () => { - const fakePath = "/rendered/path/tunedModelPermissions"; - const expectedParameters = { - tuned_model: "tunedModelValue", - permission: "permissionValue", - }; - const client = new generativeserviceModule.v1beta.GenerativeServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPermissionsPath', () => { - const result = client.tunedModelPermissionsPath("tunedModelValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchTunedModelFromTunedModelPermissionsName', () => { - const result = client.matchTunedModelFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('tunedModel', async () => { + const fakePath = '/rendered/path/tunedModel'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + }; + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.tunedModelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPath', () => { + const result = client.tunedModelPath('tunedModelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.tunedModelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelName', () => { + const result = client.matchTunedModelFromTunedModelName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.tunedModelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchPermissionFromTunedModelPermissionsName', () => { - const result = client.matchPermissionFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModelPermissions', async () => { + const fakePath = '/rendered/path/tunedModelPermissions'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + permission: 'permissionValue', + }; + const client = new generativeserviceModule.v1beta.GenerativeServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.tunedModelPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPermissionsPath', () => { + const result = client.tunedModelPermissionsPath( + 'tunedModelValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelPermissionsName', () => { + const result = + client.matchTunedModelFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromTunedModelPermissionsName', () => { + const result = + client.matchPermissionFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_model_service_v1.ts b/packages/google-ai-generativelanguage/test/gapic_model_service_v1.ts index d131a2c8ed82..575c4f0ddeab 100644 --- a/packages/google-ai-generativelanguage/test/gapic_model_service_v1.ts +++ b/packages/google-ai-generativelanguage/test/gapic_model_service_v1.ts @@ -19,559 +19,708 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as modelserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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 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.ModelServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new modelserviceModule.v1.ModelServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new modelserviceModule.v1.ModelServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new modelserviceModule.v1.ModelServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = new modelserviceModule.v1.ModelServiceClient(); + 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 = modelserviceModule.v1.ModelServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = modelserviceModule.v1.ModelServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new modelserviceModule.v1.ModelServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 = + modelserviceModule.v1.ModelServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + modelserviceModule.v1.ModelServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new modelserviceModule.v1.ModelServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new modelserviceModule.v1.ModelServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new modelserviceModule.v1.ModelServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.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 modelserviceModule.v1.ModelServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 modelserviceModule.v1.ModelServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 modelserviceModule.v1.ModelServiceClient({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 modelserviceModule.v1.ModelServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = modelserviceModule.v1.ModelServiceClient.port; - assert(port); - assert(typeof port === 'number'); + 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 modelserviceModule.v1.ModelServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new modelserviceModule.v1.ModelServiceClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new modelserviceModule.v1.ModelServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new modelserviceModule.v1.ModelServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = modelserviceModule.v1.ModelServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new modelserviceModule.v1.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.modelServiceStub, undefined); - await client.initialize(); - assert(client.modelServiceStub); - }); + it('should create a client with no option', () => { + const client = new modelserviceModule.v1.ModelServiceClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new modelserviceModule.v1.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.modelServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new modelserviceModule.v1.ModelServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new modelserviceModule.v1.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.modelServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new modelserviceModule.v1.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.modelServiceStub, undefined); + await client.initialize(); + assert(client.modelServiceStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new modelserviceModule.v1.ModelServiceClient({ - 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 close method for the initialized client', (done) => { + const client = new modelserviceModule.v1.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.modelServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new modelserviceModule.v1.ModelServiceClient({ - 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('has close method for the non-initialized client', (done) => { + const client = new modelserviceModule.v1.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.modelServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('getModel', () => { - it('invokes getModel without error', async () => { - const client = new modelserviceModule.v1.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.Model() - ); - client.innerApiCalls.getModel = stubSimpleCall(expectedResponse); - const [response] = await client.getModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel 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 modelserviceModule.v1.ModelServiceClient({ + 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 getModel without error using callback', async () => { - const client = new modelserviceModule.v1.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.Model() - ); - client.innerApiCalls.getModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getModel( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1.IModel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel 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 modelserviceModule.v1.ModelServiceClient({ + 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('getModel', () => { + it('invokes getModel without error', async () => { + const client = new modelserviceModule.v1.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.Model(), + ); + client.innerApiCalls.getModel = stubSimpleCall(expectedResponse); + const [response] = await client.getModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getModel with error', async () => { - const client = new modelserviceModule.v1.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getModel(request), expectedError); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getModel without error using callback', async () => { + const client = new modelserviceModule.v1.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.Model(), + ); + client.innerApiCalls.getModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getModel( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1.IModel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getModel with closed client', async () => { - const client = new modelserviceModule.v1.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getModel(request), expectedError); - }); + it('invokes getModel with error', async () => { + const client = new modelserviceModule.v1.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getModel = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listModels', () => { - it('invokes listModels without error', async () => { - const client = new modelserviceModule.v1.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.ListModelsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1.Model()), - ]; - client.innerApiCalls.listModels = stubSimpleCall(expectedResponse); - const [response] = await client.listModels(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes getModel with closed client', async () => { + const client = new modelserviceModule.v1.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getModel(request), expectedError); + }); + }); + + describe('listModels', () => { + it('invokes listModels without error', async () => { + const client = new modelserviceModule.v1.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.ListModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1.Model(), + ), + ]; + client.innerApiCalls.listModels = stubSimpleCall(expectedResponse); + const [response] = await client.listModels(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes listModels without error using callback', async () => { - const client = new modelserviceModule.v1.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.ListModelsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1.Model()), - ]; - client.innerApiCalls.listModels = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listModels( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1.IModel[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listModels without error using callback', async () => { + const client = new modelserviceModule.v1.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.ListModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1.Model(), + ), + ]; + client.innerApiCalls.listModels = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listModels( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1.IModel[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes listModels with error', async () => { - const client = new modelserviceModule.v1.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.ListModelsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listModels = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listModels(request), expectedError); - }); + it('invokes listModels with error', async () => { + const client = new modelserviceModule.v1.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.ListModelsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listModels = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listModels(request), expectedError); + }); - it('invokes listModelsStream without error', async () => { - const client = new modelserviceModule.v1.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.ListModelsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1.Model()), - ]; - client.descriptors.page.listModels.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1.Model[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1.Model) => { - 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.listModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listModels, request)); + it('invokes listModelsStream without error', async () => { + const client = new modelserviceModule.v1.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.ListModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1.Model(), + ), + ]; + client.descriptors.page.listModels.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1.Model[] = []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1.Model) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listModelsStream with error', async () => { - const client = new modelserviceModule.v1.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.ListModelsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listModels.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1.Model[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1.Model) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listModels, request)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listModels, request), + ); + }); - it('uses async iteration with listModels without error', async () => { - const client = new modelserviceModule.v1.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.ListModelsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1.Model()), - ]; - client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ai.generativelanguage.v1.IModel[] = []; - const iterable = client.listModelsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); + it('invokes listModelsStream with error', async () => { + const client = new modelserviceModule.v1.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.ListModelsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listModels.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1.Model[] = []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1.Model) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with listModels with error', async () => { - const client = new modelserviceModule.v1.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1.ListModelsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listModelsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ai.generativelanguage.v1.IModel[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listModels, request), + ); }); - describe('Path templates', () => { - - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new modelserviceModule.v1.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listModels without error', async () => { + const client = new modelserviceModule.v1.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.ListModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1.Model(), + ), + ]; + client.descriptors.page.listModels.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ai.generativelanguage.v1.IModel[] = []; + const iterable = client.listModelsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listModels.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); + + it('uses async iteration with listModels with error', async () => { + const client = new modelserviceModule.v1.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1.ListModelsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listModelsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ai.generativelanguage.v1.IModel[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listModels.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = new modelserviceModule.v1.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_model_service_v1alpha.ts b/packages/google-ai-generativelanguage/test/gapic_model_service_v1alpha.ts index f43e0d395633..fd15a6cac0ae 100644 --- a/packages/google-ai-generativelanguage/test/gapic_model_service_v1alpha.ts +++ b/packages/google-ai-generativelanguage/test/gapic_model_service_v1alpha.ts @@ -19,1727 +19,2230 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as modelserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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('v1alpha.ModelServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient(); - 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 = modelserviceModule.v1alpha.ModelServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = modelserviceModule.v1alpha.ModelServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 modelserviceModule.v1alpha.ModelServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 modelserviceModule.v1alpha.ModelServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 modelserviceModule.v1alpha.ModelServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + }); - it('has port', () => { - const port = modelserviceModule.v1alpha.ModelServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('has universeDomain', () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('should create a client with no option', () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient(); - assert(client); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + modelserviceModule.v1alpha.ModelServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + modelserviceModule.v1alpha.ModelServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - fallback: true, - }); - assert(client); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.modelServiceStub, undefined); - await client.initialize(); - assert(client.modelServiceStub); + 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 modelserviceModule.v1alpha.ModelServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.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 modelserviceModule.v1alpha.ModelServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.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 modelserviceModule.v1alpha.ModelServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has close method for the initialized client', done => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.modelServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = modelserviceModule.v1alpha.ModelServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the non-initialized client', done => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.modelServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient(); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - 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('should create a client with gRPC fallback', () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - 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('has initialize method and supports deferred initialization', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.modelServiceStub, undefined); + await client.initialize(); + assert(client.modelServiceStub); }); - describe('getModel', () => { - it('invokes getModel without error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.Model() - ); - client.innerApiCalls.getModel = stubSimpleCall(expectedResponse); - const [response] = await client.getModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel 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 modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.modelServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getModel without error using callback', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.Model() - ); - client.innerApiCalls.getModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getModel( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IModel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel 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 modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.modelServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getModel with error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getModel(request), expectedError); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel 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 modelserviceModule.v1alpha.ModelServiceClient({ + 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 getModel with closed client', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getModel(request), expectedError); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + 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('getModel', () => { + it('invokes getModel without error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Model(), + ); + client.innerApiCalls.getModel = stubSimpleCall(expectedResponse); + const [response] = await client.getModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getTunedModel', () => { - it('invokes getTunedModel without error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.TunedModel() - ); - client.innerApiCalls.getTunedModel = stubSimpleCall(expectedResponse); - const [response] = await client.getTunedModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getModel without error using callback', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Model(), + ); + client.innerApiCalls.getModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getModel( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.IModel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getTunedModel without error using callback', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.TunedModel() - ); - client.innerApiCalls.getTunedModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getTunedModel( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.ITunedModel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getModel with error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getModel = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getTunedModel with error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getTunedModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getTunedModel(request), expectedError); - const actualRequest = (client.innerApiCalls.getTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getModel with closed client', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getModel(request), expectedError); + }); + }); + + describe('getTunedModel', () => { + it('invokes getTunedModel without error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.TunedModel(), + ); + client.innerApiCalls.getTunedModel = stubSimpleCall(expectedResponse); + const [response] = await client.getTunedModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getTunedModel with closed client', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getTunedModel(request), expectedError); - }); + it('invokes getTunedModel without error using callback', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.TunedModel(), + ); + client.innerApiCalls.getTunedModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getTunedModel( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.ITunedModel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateTunedModel', () => { - it('invokes updateTunedModel without error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdateTunedModelRequest() - ); - request.tunedModel ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.UpdateTunedModelRequest', ['tunedModel', 'name']); - request.tunedModel.name = defaultValue1; - const expectedHeaderRequestParams = `tuned_model.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.TunedModel() - ); - client.innerApiCalls.updateTunedModel = stubSimpleCall(expectedResponse); - const [response] = await client.updateTunedModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getTunedModel with error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getTunedModel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getTunedModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateTunedModel without error using callback', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdateTunedModelRequest() - ); - request.tunedModel ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.UpdateTunedModelRequest', ['tunedModel', 'name']); - request.tunedModel.name = defaultValue1; - const expectedHeaderRequestParams = `tuned_model.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.TunedModel() - ); - client.innerApiCalls.updateTunedModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateTunedModel( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.ITunedModel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getTunedModel with closed client', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getTunedModel(request), expectedError); + }); + }); + + describe('updateTunedModel', () => { + it('invokes updateTunedModel without error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdateTunedModelRequest(), + ); + request.tunedModel ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.UpdateTunedModelRequest', + ['tunedModel', 'name'], + ); + request.tunedModel.name = defaultValue1; + const expectedHeaderRequestParams = `tuned_model.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.TunedModel(), + ); + client.innerApiCalls.updateTunedModel = stubSimpleCall(expectedResponse); + const [response] = await client.updateTunedModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateTunedModel with error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdateTunedModelRequest() - ); - request.tunedModel ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.UpdateTunedModelRequest', ['tunedModel', 'name']); - request.tunedModel.name = defaultValue1; - const expectedHeaderRequestParams = `tuned_model.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateTunedModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateTunedModel(request), expectedError); - const actualRequest = (client.innerApiCalls.updateTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateTunedModel without error using callback', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdateTunedModelRequest(), + ); + request.tunedModel ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.UpdateTunedModelRequest', + ['tunedModel', 'name'], + ); + request.tunedModel.name = defaultValue1; + const expectedHeaderRequestParams = `tuned_model.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.TunedModel(), + ); + client.innerApiCalls.updateTunedModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateTunedModel( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.ITunedModel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateTunedModel with closed client', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdateTunedModelRequest() - ); - request.tunedModel ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.UpdateTunedModelRequest', ['tunedModel', 'name']); - request.tunedModel.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateTunedModel(request), expectedError); - }); + it('invokes updateTunedModel with error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdateTunedModelRequest(), + ); + request.tunedModel ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.UpdateTunedModelRequest', + ['tunedModel', 'name'], + ); + request.tunedModel.name = defaultValue1; + const expectedHeaderRequestParams = `tuned_model.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateTunedModel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateTunedModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteTunedModel', () => { - it('invokes deleteTunedModel without error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeleteTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteTunedModel = stubSimpleCall(expectedResponse); - const [response] = await client.deleteTunedModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateTunedModel with closed client', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdateTunedModelRequest(), + ); + request.tunedModel ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.UpdateTunedModelRequest', + ['tunedModel', 'name'], + ); + request.tunedModel.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateTunedModel(request), expectedError); + }); + }); + + describe('deleteTunedModel', () => { + it('invokes deleteTunedModel without error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeleteTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteTunedModel = stubSimpleCall(expectedResponse); + const [response] = await client.deleteTunedModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTunedModel without error using callback', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeleteTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteTunedModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteTunedModel( - 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.deleteTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteTunedModel without error using callback', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeleteTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteTunedModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteTunedModel( + 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.deleteTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTunedModel with error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeleteTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteTunedModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteTunedModel(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteTunedModel with error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeleteTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteTunedModel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteTunedModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTunedModel with closed client', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeleteTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteTunedModel(request), expectedError); - }); + it('invokes deleteTunedModel with closed client', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeleteTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteTunedModel(request), expectedError); + }); + }); + + describe('createTunedModel', () => { + it('invokes createTunedModel without error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateTunedModelRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createTunedModel = + stubLongRunningCall(expectedResponse); + const [operation] = await client.createTunedModel(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); }); - describe('createTunedModel', () => { - it('invokes createTunedModel without error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateTunedModelRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createTunedModel = stubLongRunningCall(expectedResponse); - const [operation] = await client.createTunedModel(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes createTunedModel without error using callback', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateTunedModelRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createTunedModel = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createTunedModel( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + protos.google.ai.generativelanguage.v1alpha.ICreateTunedModelMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.ai.generativelanguage.v1alpha.ITunedModel, + protos.google.ai.generativelanguage.v1alpha.ICreateTunedModelMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createTunedModel without error using callback', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateTunedModelRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createTunedModel = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createTunedModel( - 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); - }); + it('invokes createTunedModel with call error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateTunedModelRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createTunedModel = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.createTunedModel(request), expectedError); + }); - it('invokes createTunedModel with call error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateTunedModelRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createTunedModel = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.createTunedModel(request), expectedError); - }); + it('invokes createTunedModel with LRO error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateTunedModelRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createTunedModel = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.createTunedModel(request); + await assert.rejects(operation.promise(), expectedError); + }); - it('invokes createTunedModel with LRO error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateTunedModelRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createTunedModel = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.createTunedModel(request); - await assert.rejects(operation.promise(), expectedError); - }); + it('invokes checkCreateTunedModelProgress without error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + 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.checkCreateTunedModelProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes checkCreateTunedModelProgress without error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - 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.checkCreateTunedModelProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes checkCreateTunedModelProgress with error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + 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.checkCreateTunedModelProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('listModels', () => { + it('invokes listModels without error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Model(), + ), + ]; + client.innerApiCalls.listModels = stubSimpleCall(expectedResponse); + const [response] = await client.listModels(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes checkCreateTunedModelProgress with error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - 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.checkCreateTunedModelProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes listModels without error using callback', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Model(), + ), + ]; + client.innerApiCalls.listModels = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listModels( + request, + ( + err?: Error | null, + result?: + | protos.google.ai.generativelanguage.v1alpha.IModel[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('listModels', () => { - it('invokes listModels without error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListModelsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Model()), - ]; - client.innerApiCalls.listModels = stubSimpleCall(expectedResponse); - const [response] = await client.listModels(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listModels with error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListModelsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listModels = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listModels(request), expectedError); + }); - it('invokes listModels without error using callback', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListModelsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Model()), - ]; - client.innerApiCalls.listModels = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listModels( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IModel[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listModelsStream without error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Model(), + ), + ]; + client.descriptors.page.listModels.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1alpha.Model[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1alpha.Model) => { + 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.listModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listModels, request), + ); + }); - it('invokes listModels with error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListModelsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listModels = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listModels(request), expectedError); - }); + it('invokes listModelsStream with error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListModelsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listModels.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1alpha.Model[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1alpha.Model) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listModels, request), + ); + }); - it('invokes listModelsStream without error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListModelsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Model()), - ]; - client.descriptors.page.listModels.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1alpha.Model[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1alpha.Model) => { - 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.listModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listModels, request)); - }); + it('uses async iteration with listModels without error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Model(), + ), + ]; + client.descriptors.page.listModels.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ai.generativelanguage.v1alpha.IModel[] = + []; + const iterable = client.listModelsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listModels.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); - it('invokes listModelsStream with error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListModelsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listModels.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1alpha.Model[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1alpha.Model) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listModels, request)); - }); + it('uses async iteration with listModels with error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListModelsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listModelsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ai.generativelanguage.v1alpha.IModel[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listModels.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); + }); + + describe('listTunedModels', () => { + it('invokes listTunedModels without error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListTunedModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.TunedModel(), + ), + ]; + client.innerApiCalls.listTunedModels = stubSimpleCall(expectedResponse); + const [response] = await client.listTunedModels(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('uses async iteration with listModels without error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListModelsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Model()), - ]; - client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ai.generativelanguage.v1alpha.IModel[] = []; - const iterable = client.listModelsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listTunedModels without error using callback', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListTunedModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.TunedModel(), + ), + ]; + client.innerApiCalls.listTunedModels = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listTunedModels( + request, + ( + err?: Error | null, + result?: + | protos.google.ai.generativelanguage.v1alpha.ITunedModel[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); - - it('uses async iteration with listModels with error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListModelsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listModelsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ai.generativelanguage.v1alpha.IModel[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('listTunedModels', () => { - it('invokes listTunedModels without error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListTunedModelsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.TunedModel()), - ]; - client.innerApiCalls.listTunedModels = stubSimpleCall(expectedResponse); - const [response] = await client.listTunedModels(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes listTunedModels without error using callback', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListTunedModelsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.TunedModel()), - ]; - client.innerApiCalls.listTunedModels = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listTunedModels( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.ITunedModel[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes listTunedModels with error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListTunedModelsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listTunedModels = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listTunedModels(request), expectedError); - }); + it('invokes listTunedModels with error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListTunedModelsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listTunedModels = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listTunedModels(request), expectedError); + }); - it('invokes listTunedModelsStream without error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListTunedModelsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.TunedModel()), - ]; - client.descriptors.page.listTunedModels.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listTunedModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1alpha.TunedModel[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1alpha.TunedModel) => { - 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.listTunedModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTunedModels, request)); - }); + it('invokes listTunedModelsStream without error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListTunedModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.TunedModel(), + ), + ]; + client.descriptors.page.listTunedModels.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listTunedModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1alpha.TunedModel[] = + []; + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1alpha.TunedModel, + ) => { + 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.listTunedModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTunedModels, request), + ); + }); - it('invokes listTunedModelsStream with error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListTunedModelsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listTunedModels.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listTunedModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1alpha.TunedModel[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1alpha.TunedModel) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listTunedModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTunedModels, request)); - }); + it('invokes listTunedModelsStream with error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListTunedModelsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listTunedModels.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listTunedModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1alpha.TunedModel[] = + []; + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1alpha.TunedModel, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listTunedModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTunedModels, request), + ); + }); - it('uses async iteration with listTunedModels without error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListTunedModelsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.TunedModel()), - ]; - client.descriptors.page.listTunedModels.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ai.generativelanguage.v1alpha.ITunedModel[] = []; - const iterable = client.listTunedModelsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listTunedModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('uses async iteration with listTunedModels without error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListTunedModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.TunedModel(), + ), + ]; + client.descriptors.page.listTunedModels.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ai.generativelanguage.v1alpha.ITunedModel[] = + []; + const iterable = client.listTunedModelsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listTunedModels.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); - it('uses async iteration with listTunedModels with error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListTunedModelsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listTunedModels.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listTunedModelsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ai.generativelanguage.v1alpha.ITunedModel[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listTunedModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('uses async iteration with listTunedModels with error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListTunedModelsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listTunedModels.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listTunedModelsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ai.generativelanguage.v1alpha.ITunedModel[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listTunedModels.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); }); - describe('getOperation', () => { - it('invokes getOperation without error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - 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 modelserviceModule.v1alpha.ModelServiceClient({ - 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 modelserviceModule.v1alpha.ModelServiceClient({ - 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('getOperation', () => { + it('invokes getOperation without error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + 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('cancelOperation', () => { - it('invokes cancelOperation without error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - 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 modelserviceModule.v1alpha.ModelServiceClient({ - 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 modelserviceModule.v1alpha.ModelServiceClient({ - 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)); - }); + it('invokes getOperation without error using callback', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + 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)); }); - describe('deleteOperation', () => { - it('invokes deleteOperation without error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - 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 modelserviceModule.v1alpha.ModelServiceClient({ - 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 modelserviceModule.v1alpha.ModelServiceClient({ - 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 getOperation with error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + 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('listOperationsAsync', () => { - it('uses async iteration with listOperations without error', async () => { - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - 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 modelserviceModule.v1alpha.ModelServiceClient({ - 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('cancelOperation', () => { + it('invokes cancelOperation without error', async () => { + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + 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 modelserviceModule.v1alpha.ModelServiceClient({ + 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 modelserviceModule.v1alpha.ModelServiceClient({ + 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 modelserviceModule.v1alpha.ModelServiceClient({ + 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 modelserviceModule.v1alpha.ModelServiceClient({ + 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 modelserviceModule.v1alpha.ModelServiceClient({ + 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 modelserviceModule.v1alpha.ModelServiceClient({ + 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 modelserviceModule.v1alpha.ModelServiceClient({ + 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('cachedContent', async () => { + const fakePath = '/rendered/path/cachedContent'; + const expectedParameters = { + id: 'idValue', + }; + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.cachedContentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.cachedContentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('cachedContentPath', () => { + const result = client.cachedContentPath('idValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.cachedContentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchIdFromCachedContentName', () => { + const result = client.matchIdFromCachedContentName(fakePath); + assert.strictEqual(result, 'idValue'); + assert( + (client.pathTemplates.cachedContentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); - describe('Path templates', () => { - - describe('cachedContent', async () => { - const fakePath = "/rendered/path/cachedContent"; - const expectedParameters = { - id: "idValue", - }; - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.cachedContentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.cachedContentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('cachedContentPath', () => { - const result = client.cachedContentPath("idValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.cachedContentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchIdFromCachedContentName', () => { - const result = client.matchIdFromCachedContentName(fakePath); - assert.strictEqual(result, "idValue"); - assert((client.pathTemplates.cachedContentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('chunk', async () => { - const fakePath = "/rendered/path/chunk"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - chunk: "chunkValue", - }; - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.chunkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.chunkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('chunkPath', () => { - const result = client.chunkPath("corpusValue", "documentValue", "chunkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.chunkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromChunkName', () => { - const result = client.matchCorpusFromChunkName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromChunkName', () => { - const result = client.matchDocumentFromChunkName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChunkFromChunkName', () => { - const result = client.matchChunkFromChunkName(fakePath); - assert.strictEqual(result, "chunkValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('chunk', async () => { + const fakePath = '/rendered/path/chunk'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + chunk: 'chunkValue', + }; + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.chunkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.chunkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('chunkPath', () => { + const result = client.chunkPath( + 'corpusValue', + 'documentValue', + 'chunkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.chunkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromChunkName', () => { + const result = client.matchCorpusFromChunkName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromChunkName', () => { + const result = client.matchDocumentFromChunkName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChunkFromChunkName', () => { + const result = client.matchChunkFromChunkName(fakePath); + assert.strictEqual(result, 'chunkValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('corpus', async () => { - const fakePath = "/rendered/path/corpus"; - const expectedParameters = { - corpus: "corpusValue", - }; - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPath', () => { - const result = client.corpusPath("corpusValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusName', () => { - const result = client.matchCorpusFromCorpusName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpus', async () => { + const fakePath = '/rendered/path/corpus'; + const expectedParameters = { + corpus: 'corpusValue', + }; + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPath', () => { + const result = client.corpusPath('corpusValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.corpusPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusName', () => { + const result = client.matchCorpusFromCorpusName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.corpusPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('corpusPermissions', async () => { - const fakePath = "/rendered/path/corpusPermissions"; - const expectedParameters = { - corpus: "corpusValue", - permission: "permissionValue", - }; - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPermissionsPath', () => { - const result = client.corpusPermissionsPath("corpusValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusPermissionsName', () => { - const result = client.matchCorpusFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromCorpusPermissionsName', () => { - const result = client.matchPermissionFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpusPermissions', async () => { + const fakePath = '/rendered/path/corpusPermissions'; + const expectedParameters = { + corpus: 'corpusValue', + permission: 'permissionValue', + }; + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPermissionsPath', () => { + const result = client.corpusPermissionsPath( + 'corpusValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusPermissionsName', () => { + const result = client.matchCorpusFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromCorpusPermissionsName', () => { + const result = + client.matchPermissionFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('document', async () => { - const fakePath = "/rendered/path/document"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - }; - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.documentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.documentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('documentPath', () => { - const result = client.documentPath("corpusValue", "documentValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.documentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromDocumentName', () => { - const result = client.matchCorpusFromDocumentName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromDocumentName', () => { - const result = client.matchDocumentFromDocumentName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('document', async () => { + const fakePath = '/rendered/path/document'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + }; + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.documentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.documentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('documentPath', () => { + const result = client.documentPath('corpusValue', 'documentValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.documentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromDocumentName', () => { + const result = client.matchCorpusFromDocumentName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromDocumentName', () => { + const result = client.matchDocumentFromDocumentName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('file', async () => { - const fakePath = "/rendered/path/file"; - const expectedParameters = { - file: "fileValue", - }; - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.filePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.filePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('filePath', () => { - const result = client.filePath("fileValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.filePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFileFromFileName', () => { - const result = client.matchFileFromFileName(fakePath); - assert.strictEqual(result, "fileValue"); - assert((client.pathTemplates.filePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('file', async () => { + const fakePath = '/rendered/path/file'; + const expectedParameters = { + file: 'fileValue', + }; + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.filePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.filePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('filePath', () => { + const result = client.filePath('fileValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.filePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFileFromFileName', () => { + const result = client.matchFileFromFileName(fakePath); + assert.strictEqual(result, 'fileValue'); + assert( + (client.pathTemplates.filePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModel', async () => { - const fakePath = "/rendered/path/tunedModel"; - const expectedParameters = { - tuned_model: "tunedModelValue", - }; - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPath', () => { - const result = client.tunedModelPath("tunedModelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelName', () => { - const result = client.matchTunedModelFromTunedModelName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModel', async () => { + const fakePath = '/rendered/path/tunedModel'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + }; + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPath', () => { + const result = client.tunedModelPath('tunedModelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.tunedModelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelName', () => { + const result = client.matchTunedModelFromTunedModelName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.tunedModelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModelPermissions', async () => { - const fakePath = "/rendered/path/tunedModelPermissions"; - const expectedParameters = { - tuned_model: "tunedModelValue", - permission: "permissionValue", - }; - const client = new modelserviceModule.v1alpha.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPermissionsPath', () => { - const result = client.tunedModelPermissionsPath("tunedModelValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelPermissionsName', () => { - const result = client.matchTunedModelFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromTunedModelPermissionsName', () => { - const result = client.matchPermissionFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModelPermissions', async () => { + const fakePath = '/rendered/path/tunedModelPermissions'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + permission: 'permissionValue', + }; + const client = new modelserviceModule.v1alpha.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPermissionsPath', () => { + const result = client.tunedModelPermissionsPath( + 'tunedModelValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelPermissionsName', () => { + const result = + client.matchTunedModelFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromTunedModelPermissionsName', () => { + const result = + client.matchPermissionFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_model_service_v1beta.ts b/packages/google-ai-generativelanguage/test/gapic_model_service_v1beta.ts index 448f9da2e912..1d00e6a01f7d 100644 --- a/packages/google-ai-generativelanguage/test/gapic_model_service_v1beta.ts +++ b/packages/google-ai-generativelanguage/test/gapic_model_service_v1beta.ts @@ -19,1727 +19,2223 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as modelserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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('v1beta.ModelServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new modelserviceModule.v1beta.ModelServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new modelserviceModule.v1beta.ModelServiceClient(); - 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 = modelserviceModule.v1beta.ModelServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = modelserviceModule.v1beta.ModelServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 modelserviceModule.v1beta.ModelServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 modelserviceModule.v1beta.ModelServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 modelserviceModule.v1beta.ModelServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new modelserviceModule.v1beta.ModelServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + }); - it('has port', () => { - const port = modelserviceModule.v1beta.ModelServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('has universeDomain', () => { + const client = new modelserviceModule.v1beta.ModelServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('should create a client with no option', () => { - const client = new modelserviceModule.v1beta.ModelServiceClient(); - assert(client); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + modelserviceModule.v1beta.ModelServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + modelserviceModule.v1beta.ModelServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - fallback: true, - }); - assert(client); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.modelServiceStub, undefined); - await client.initialize(); - assert(client.modelServiceStub); + 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 modelserviceModule.v1beta.ModelServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.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 modelserviceModule.v1beta.ModelServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.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 modelserviceModule.v1beta.ModelServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has close method for the initialized client', done => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.modelServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = modelserviceModule.v1beta.ModelServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the non-initialized client', done => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.modelServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new modelserviceModule.v1beta.ModelServiceClient(); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new modelserviceModule.v1beta.ModelServiceClient({ - 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('should create a client with gRPC fallback', () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new modelserviceModule.v1beta.ModelServiceClient({ - 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('has initialize method and supports deferred initialization', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.modelServiceStub, undefined); + await client.initialize(); + assert(client.modelServiceStub); }); - describe('getModel', () => { - it('invokes getModel without error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.Model() - ); - client.innerApiCalls.getModel = stubSimpleCall(expectedResponse); - const [response] = await client.getModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel 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 modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.modelServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getModel without error using callback', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.Model() - ); - client.innerApiCalls.getModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getModel( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IModel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel 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 modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.modelServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getModel with error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getModel(request), expectedError); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel 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 modelserviceModule.v1beta.ModelServiceClient({ + 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 getModel with closed client', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getModel(request), expectedError); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new modelserviceModule.v1beta.ModelServiceClient({ + 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('getModel', () => { + it('invokes getModel without error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Model(), + ); + client.innerApiCalls.getModel = stubSimpleCall(expectedResponse); + const [response] = await client.getModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getTunedModel', () => { - it('invokes getTunedModel without error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.TunedModel() - ); - client.innerApiCalls.getTunedModel = stubSimpleCall(expectedResponse); - const [response] = await client.getTunedModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getModel without error using callback', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Model(), + ); + client.innerApiCalls.getModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getModel( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IModel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getTunedModel without error using callback', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.TunedModel() - ); - client.innerApiCalls.getTunedModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getTunedModel( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.ITunedModel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getModel with error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getModel = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getTunedModel with error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getTunedModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getTunedModel(request), expectedError); - const actualRequest = (client.innerApiCalls.getTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getModel with closed client', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getModel(request), expectedError); + }); + }); + + describe('getTunedModel', () => { + it('invokes getTunedModel without error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.TunedModel(), + ); + client.innerApiCalls.getTunedModel = stubSimpleCall(expectedResponse); + const [response] = await client.getTunedModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getTunedModel with closed client', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getTunedModel(request), expectedError); - }); + it('invokes getTunedModel without error using callback', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.TunedModel(), + ); + client.innerApiCalls.getTunedModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getTunedModel( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.ITunedModel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateTunedModel', () => { - it('invokes updateTunedModel without error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdateTunedModelRequest() - ); - request.tunedModel ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.UpdateTunedModelRequest', ['tunedModel', 'name']); - request.tunedModel.name = defaultValue1; - const expectedHeaderRequestParams = `tuned_model.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.TunedModel() - ); - client.innerApiCalls.updateTunedModel = stubSimpleCall(expectedResponse); - const [response] = await client.updateTunedModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getTunedModel with error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getTunedModel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getTunedModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateTunedModel without error using callback', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdateTunedModelRequest() - ); - request.tunedModel ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.UpdateTunedModelRequest', ['tunedModel', 'name']); - request.tunedModel.name = defaultValue1; - const expectedHeaderRequestParams = `tuned_model.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.TunedModel() - ); - client.innerApiCalls.updateTunedModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateTunedModel( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.ITunedModel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getTunedModel with closed client', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getTunedModel(request), expectedError); + }); + }); + + describe('updateTunedModel', () => { + it('invokes updateTunedModel without error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdateTunedModelRequest(), + ); + request.tunedModel ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.UpdateTunedModelRequest', + ['tunedModel', 'name'], + ); + request.tunedModel.name = defaultValue1; + const expectedHeaderRequestParams = `tuned_model.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.TunedModel(), + ); + client.innerApiCalls.updateTunedModel = stubSimpleCall(expectedResponse); + const [response] = await client.updateTunedModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateTunedModel with error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdateTunedModelRequest() - ); - request.tunedModel ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.UpdateTunedModelRequest', ['tunedModel', 'name']); - request.tunedModel.name = defaultValue1; - const expectedHeaderRequestParams = `tuned_model.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateTunedModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateTunedModel(request), expectedError); - const actualRequest = (client.innerApiCalls.updateTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateTunedModel without error using callback', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdateTunedModelRequest(), + ); + request.tunedModel ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.UpdateTunedModelRequest', + ['tunedModel', 'name'], + ); + request.tunedModel.name = defaultValue1; + const expectedHeaderRequestParams = `tuned_model.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.TunedModel(), + ); + client.innerApiCalls.updateTunedModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateTunedModel( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.ITunedModel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateTunedModel with closed client', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdateTunedModelRequest() - ); - request.tunedModel ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.UpdateTunedModelRequest', ['tunedModel', 'name']); - request.tunedModel.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateTunedModel(request), expectedError); - }); + it('invokes updateTunedModel with error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdateTunedModelRequest(), + ); + request.tunedModel ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.UpdateTunedModelRequest', + ['tunedModel', 'name'], + ); + request.tunedModel.name = defaultValue1; + const expectedHeaderRequestParams = `tuned_model.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateTunedModel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateTunedModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteTunedModel', () => { - it('invokes deleteTunedModel without error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeleteTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteTunedModel = stubSimpleCall(expectedResponse); - const [response] = await client.deleteTunedModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateTunedModel with closed client', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdateTunedModelRequest(), + ); + request.tunedModel ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.UpdateTunedModelRequest', + ['tunedModel', 'name'], + ); + request.tunedModel.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateTunedModel(request), expectedError); + }); + }); + + describe('deleteTunedModel', () => { + it('invokes deleteTunedModel without error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeleteTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteTunedModel = stubSimpleCall(expectedResponse); + const [response] = await client.deleteTunedModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTunedModel without error using callback', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeleteTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteTunedModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteTunedModel( - 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.deleteTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteTunedModel without error using callback', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeleteTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteTunedModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteTunedModel( + 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.deleteTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTunedModel with error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeleteTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteTunedModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteTunedModel(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteTunedModel with error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeleteTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteTunedModel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteTunedModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTunedModel with closed client', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeleteTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteTunedModel(request), expectedError); - }); + it('invokes deleteTunedModel with closed client', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeleteTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteTunedModel(request), expectedError); + }); + }); + + describe('createTunedModel', () => { + it('invokes createTunedModel without error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateTunedModelRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createTunedModel = + stubLongRunningCall(expectedResponse); + const [operation] = await client.createTunedModel(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); }); - describe('createTunedModel', () => { - it('invokes createTunedModel without error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateTunedModelRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createTunedModel = stubLongRunningCall(expectedResponse); - const [operation] = await client.createTunedModel(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes createTunedModel without error using callback', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateTunedModelRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createTunedModel = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createTunedModel( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.ai.generativelanguage.v1beta.ITunedModel, + protos.google.ai.generativelanguage.v1beta.ICreateTunedModelMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.ai.generativelanguage.v1beta.ITunedModel, + protos.google.ai.generativelanguage.v1beta.ICreateTunedModelMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createTunedModel without error using callback', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateTunedModelRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createTunedModel = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createTunedModel( - 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); - }); + it('invokes createTunedModel with call error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateTunedModelRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createTunedModel = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.createTunedModel(request), expectedError); + }); - it('invokes createTunedModel with call error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateTunedModelRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createTunedModel = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.createTunedModel(request), expectedError); - }); + it('invokes createTunedModel with LRO error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateTunedModelRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createTunedModel = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.createTunedModel(request); + await assert.rejects(operation.promise(), expectedError); + }); - it('invokes createTunedModel with LRO error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateTunedModelRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createTunedModel = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.createTunedModel(request); - await assert.rejects(operation.promise(), expectedError); - }); + it('invokes checkCreateTunedModelProgress without error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + 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.checkCreateTunedModelProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes checkCreateTunedModelProgress without error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - 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.checkCreateTunedModelProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes checkCreateTunedModelProgress with error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + 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.checkCreateTunedModelProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('listModels', () => { + it('invokes listModels without error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Model(), + ), + ]; + client.innerApiCalls.listModels = stubSimpleCall(expectedResponse); + const [response] = await client.listModels(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes checkCreateTunedModelProgress with error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - 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.checkCreateTunedModelProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes listModels without error using callback', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Model(), + ), + ]; + client.innerApiCalls.listModels = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listModels( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IModel[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('listModels', () => { - it('invokes listModels without error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListModelsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Model()), - ]; - client.innerApiCalls.listModels = stubSimpleCall(expectedResponse); - const [response] = await client.listModels(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listModels with error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListModelsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listModels = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listModels(request), expectedError); + }); - it('invokes listModels without error using callback', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListModelsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Model()), - ]; - client.innerApiCalls.listModels = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listModels( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IModel[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listModelsStream without error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Model(), + ), + ]; + client.descriptors.page.listModels.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1beta.Model[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1beta.Model) => { + 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.listModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listModels, request), + ); + }); - it('invokes listModels with error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListModelsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listModels = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listModels(request), expectedError); - }); + it('invokes listModelsStream with error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListModelsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listModels.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1beta.Model[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1beta.Model) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listModels, request), + ); + }); - it('invokes listModelsStream without error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListModelsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Model()), - ]; - client.descriptors.page.listModels.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1beta.Model[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta.Model) => { - 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.listModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listModels, request)); - }); + it('uses async iteration with listModels without error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Model(), + ), + ]; + client.descriptors.page.listModels.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ai.generativelanguage.v1beta.IModel[] = []; + const iterable = client.listModelsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listModels.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); - it('invokes listModelsStream with error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListModelsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listModels.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1beta.Model[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta.Model) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listModels, request)); - }); + it('uses async iteration with listModels with error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListModelsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listModelsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ai.generativelanguage.v1beta.IModel[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listModels.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); + }); + + describe('listTunedModels', () => { + it('invokes listTunedModels without error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListTunedModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.TunedModel(), + ), + ]; + client.innerApiCalls.listTunedModels = stubSimpleCall(expectedResponse); + const [response] = await client.listTunedModels(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('uses async iteration with listModels without error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListModelsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Model()), - ]; - client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ai.generativelanguage.v1beta.IModel[] = []; - const iterable = client.listModelsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listTunedModels without error using callback', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListTunedModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.TunedModel(), + ), + ]; + client.innerApiCalls.listTunedModels = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listTunedModels( + request, + ( + err?: Error | null, + result?: + | protos.google.ai.generativelanguage.v1beta.ITunedModel[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); - - it('uses async iteration with listModels with error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListModelsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listModelsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ai.generativelanguage.v1beta.IModel[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('listTunedModels', () => { - it('invokes listTunedModels without error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListTunedModelsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.TunedModel()), - ]; - client.innerApiCalls.listTunedModels = stubSimpleCall(expectedResponse); - const [response] = await client.listTunedModels(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes listTunedModels without error using callback', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListTunedModelsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.TunedModel()), - ]; - client.innerApiCalls.listTunedModels = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listTunedModels( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.ITunedModel[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes listTunedModels with error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListTunedModelsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listTunedModels = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listTunedModels(request), expectedError); - }); + it('invokes listTunedModels with error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListTunedModelsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listTunedModels = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listTunedModels(request), expectedError); + }); - it('invokes listTunedModelsStream without error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListTunedModelsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.TunedModel()), - ]; - client.descriptors.page.listTunedModels.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listTunedModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1beta.TunedModel[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta.TunedModel) => { - 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.listTunedModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTunedModels, request)); - }); + it('invokes listTunedModelsStream without error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListTunedModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.TunedModel(), + ), + ]; + client.descriptors.page.listTunedModels.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listTunedModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1beta.TunedModel[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1beta.TunedModel) => { + 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.listTunedModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTunedModels, request), + ); + }); - it('invokes listTunedModelsStream with error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListTunedModelsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listTunedModels.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listTunedModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1beta.TunedModel[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta.TunedModel) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listTunedModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTunedModels, request)); - }); + it('invokes listTunedModelsStream with error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListTunedModelsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listTunedModels.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listTunedModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1beta.TunedModel[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1beta.TunedModel) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listTunedModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTunedModels, request), + ); + }); - it('uses async iteration with listTunedModels without error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListTunedModelsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.TunedModel()), - ]; - client.descriptors.page.listTunedModels.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ai.generativelanguage.v1beta.ITunedModel[] = []; - const iterable = client.listTunedModelsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listTunedModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('uses async iteration with listTunedModels without error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListTunedModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.TunedModel(), + ), + ]; + client.descriptors.page.listTunedModels.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ai.generativelanguage.v1beta.ITunedModel[] = + []; + const iterable = client.listTunedModelsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listTunedModels.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); - it('uses async iteration with listTunedModels with error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListTunedModelsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listTunedModels.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listTunedModelsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ai.generativelanguage.v1beta.ITunedModel[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listTunedModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('uses async iteration with listTunedModels with error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListTunedModelsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listTunedModels.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listTunedModelsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ai.generativelanguage.v1beta.ITunedModel[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listTunedModels.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); }); - describe('getOperation', () => { - it('invokes getOperation without error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - 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 modelserviceModule.v1beta.ModelServiceClient({ - 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 modelserviceModule.v1beta.ModelServiceClient({ - 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('getOperation', () => { + it('invokes getOperation without error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + 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('cancelOperation', () => { - it('invokes cancelOperation without error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - 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 modelserviceModule.v1beta.ModelServiceClient({ - 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 modelserviceModule.v1beta.ModelServiceClient({ - 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)); - }); + it('invokes getOperation without error using callback', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + 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)); }); - describe('deleteOperation', () => { - it('invokes deleteOperation without error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - 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 modelserviceModule.v1beta.ModelServiceClient({ - 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 modelserviceModule.v1beta.ModelServiceClient({ - 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 getOperation with error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + 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('listOperationsAsync', () => { - it('uses async iteration with listOperations without error', async () => { - const client = new modelserviceModule.v1beta.ModelServiceClient({ - 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 modelserviceModule.v1beta.ModelServiceClient({ - 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('cancelOperation', () => { + it('invokes cancelOperation without error', async () => { + const client = new modelserviceModule.v1beta.ModelServiceClient({ + 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 modelserviceModule.v1beta.ModelServiceClient({ + 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 modelserviceModule.v1beta.ModelServiceClient({ + 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 modelserviceModule.v1beta.ModelServiceClient({ + 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 modelserviceModule.v1beta.ModelServiceClient({ + 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 modelserviceModule.v1beta.ModelServiceClient({ + 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 modelserviceModule.v1beta.ModelServiceClient({ + 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 modelserviceModule.v1beta.ModelServiceClient({ + 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('cachedContent', async () => { + const fakePath = '/rendered/path/cachedContent'; + const expectedParameters = { + id: 'idValue', + }; + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.cachedContentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.cachedContentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('cachedContentPath', () => { + const result = client.cachedContentPath('idValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.cachedContentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchIdFromCachedContentName', () => { + const result = client.matchIdFromCachedContentName(fakePath); + assert.strictEqual(result, 'idValue'); + assert( + (client.pathTemplates.cachedContentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); - describe('Path templates', () => { - - describe('cachedContent', async () => { - const fakePath = "/rendered/path/cachedContent"; - const expectedParameters = { - id: "idValue", - }; - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.cachedContentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.cachedContentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('cachedContentPath', () => { - const result = client.cachedContentPath("idValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.cachedContentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchIdFromCachedContentName', () => { - const result = client.matchIdFromCachedContentName(fakePath); - assert.strictEqual(result, "idValue"); - assert((client.pathTemplates.cachedContentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('chunk', async () => { - const fakePath = "/rendered/path/chunk"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - chunk: "chunkValue", - }; - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.chunkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.chunkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('chunkPath', () => { - const result = client.chunkPath("corpusValue", "documentValue", "chunkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.chunkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromChunkName', () => { - const result = client.matchCorpusFromChunkName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromChunkName', () => { - const result = client.matchDocumentFromChunkName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChunkFromChunkName', () => { - const result = client.matchChunkFromChunkName(fakePath); - assert.strictEqual(result, "chunkValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('chunk', async () => { + const fakePath = '/rendered/path/chunk'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + chunk: 'chunkValue', + }; + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.chunkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.chunkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('chunkPath', () => { + const result = client.chunkPath( + 'corpusValue', + 'documentValue', + 'chunkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.chunkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromChunkName', () => { + const result = client.matchCorpusFromChunkName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromChunkName', () => { + const result = client.matchDocumentFromChunkName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChunkFromChunkName', () => { + const result = client.matchChunkFromChunkName(fakePath); + assert.strictEqual(result, 'chunkValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('corpus', async () => { - const fakePath = "/rendered/path/corpus"; - const expectedParameters = { - corpus: "corpusValue", - }; - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPath', () => { - const result = client.corpusPath("corpusValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusName', () => { - const result = client.matchCorpusFromCorpusName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpus', async () => { + const fakePath = '/rendered/path/corpus'; + const expectedParameters = { + corpus: 'corpusValue', + }; + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPath', () => { + const result = client.corpusPath('corpusValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.corpusPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusName', () => { + const result = client.matchCorpusFromCorpusName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.corpusPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('corpusPermissions', async () => { - const fakePath = "/rendered/path/corpusPermissions"; - const expectedParameters = { - corpus: "corpusValue", - permission: "permissionValue", - }; - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPermissionsPath', () => { - const result = client.corpusPermissionsPath("corpusValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusPermissionsName', () => { - const result = client.matchCorpusFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromCorpusPermissionsName', () => { - const result = client.matchPermissionFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpusPermissions', async () => { + const fakePath = '/rendered/path/corpusPermissions'; + const expectedParameters = { + corpus: 'corpusValue', + permission: 'permissionValue', + }; + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPermissionsPath', () => { + const result = client.corpusPermissionsPath( + 'corpusValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusPermissionsName', () => { + const result = client.matchCorpusFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromCorpusPermissionsName', () => { + const result = + client.matchPermissionFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('document', async () => { - const fakePath = "/rendered/path/document"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - }; - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.documentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.documentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('documentPath', () => { - const result = client.documentPath("corpusValue", "documentValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.documentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromDocumentName', () => { - const result = client.matchCorpusFromDocumentName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromDocumentName', () => { - const result = client.matchDocumentFromDocumentName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('document', async () => { + const fakePath = '/rendered/path/document'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + }; + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.documentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.documentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('documentPath', () => { + const result = client.documentPath('corpusValue', 'documentValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.documentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromDocumentName', () => { + const result = client.matchCorpusFromDocumentName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromDocumentName', () => { + const result = client.matchDocumentFromDocumentName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('file', async () => { - const fakePath = "/rendered/path/file"; - const expectedParameters = { - file: "fileValue", - }; - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.filePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.filePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('filePath', () => { - const result = client.filePath("fileValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.filePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFileFromFileName', () => { - const result = client.matchFileFromFileName(fakePath); - assert.strictEqual(result, "fileValue"); - assert((client.pathTemplates.filePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('file', async () => { + const fakePath = '/rendered/path/file'; + const expectedParameters = { + file: 'fileValue', + }; + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.filePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.filePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('filePath', () => { + const result = client.filePath('fileValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.filePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFileFromFileName', () => { + const result = client.matchFileFromFileName(fakePath); + assert.strictEqual(result, 'fileValue'); + assert( + (client.pathTemplates.filePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModel', async () => { - const fakePath = "/rendered/path/tunedModel"; - const expectedParameters = { - tuned_model: "tunedModelValue", - }; - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPath', () => { - const result = client.tunedModelPath("tunedModelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelName', () => { - const result = client.matchTunedModelFromTunedModelName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModel', async () => { + const fakePath = '/rendered/path/tunedModel'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + }; + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPath', () => { + const result = client.tunedModelPath('tunedModelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.tunedModelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelName', () => { + const result = client.matchTunedModelFromTunedModelName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.tunedModelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModelPermissions', async () => { - const fakePath = "/rendered/path/tunedModelPermissions"; - const expectedParameters = { - tuned_model: "tunedModelValue", - permission: "permissionValue", - }; - const client = new modelserviceModule.v1beta.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPermissionsPath', () => { - const result = client.tunedModelPermissionsPath("tunedModelValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelPermissionsName', () => { - const result = client.matchTunedModelFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromTunedModelPermissionsName', () => { - const result = client.matchPermissionFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModelPermissions', async () => { + const fakePath = '/rendered/path/tunedModelPermissions'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + permission: 'permissionValue', + }; + const client = new modelserviceModule.v1beta.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPermissionsPath', () => { + const result = client.tunedModelPermissionsPath( + 'tunedModelValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelPermissionsName', () => { + const result = + client.matchTunedModelFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromTunedModelPermissionsName', () => { + const result = + client.matchPermissionFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_model_service_v1beta2.ts b/packages/google-ai-generativelanguage/test/gapic_model_service_v1beta2.ts index 1ca799120f63..6806e8400c1f 100644 --- a/packages/google-ai-generativelanguage/test/gapic_model_service_v1beta2.ts +++ b/packages/google-ai-generativelanguage/test/gapic_model_service_v1beta2.ts @@ -19,559 +19,714 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as modelserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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 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('v1beta2.ModelServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new modelserviceModule.v1beta2.ModelServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new modelserviceModule.v1beta2.ModelServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new modelserviceModule.v1beta2.ModelServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = new modelserviceModule.v1beta2.ModelServiceClient(); + 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 = modelserviceModule.v1beta2.ModelServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = modelserviceModule.v1beta2.ModelServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new modelserviceModule.v1beta2.ModelServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 = + modelserviceModule.v1beta2.ModelServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + modelserviceModule.v1beta2.ModelServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new modelserviceModule.v1beta2.ModelServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new modelserviceModule.v1beta2.ModelServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new modelserviceModule.v1beta2.ModelServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.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 modelserviceModule.v1beta2.ModelServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 modelserviceModule.v1beta2.ModelServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 modelserviceModule.v1beta2.ModelServiceClient({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 modelserviceModule.v1beta2.ModelServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = modelserviceModule.v1beta2.ModelServiceClient.port; - assert(port); - assert(typeof port === 'number'); + 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 modelserviceModule.v1beta2.ModelServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new modelserviceModule.v1beta2.ModelServiceClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new modelserviceModule.v1beta2.ModelServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new modelserviceModule.v1beta2.ModelServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = modelserviceModule.v1beta2.ModelServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new modelserviceModule.v1beta2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.modelServiceStub, undefined); - await client.initialize(); - assert(client.modelServiceStub); - }); + it('should create a client with no option', () => { + const client = new modelserviceModule.v1beta2.ModelServiceClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new modelserviceModule.v1beta2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.modelServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new modelserviceModule.v1beta2.ModelServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new modelserviceModule.v1beta2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.modelServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new modelserviceModule.v1beta2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.modelServiceStub, undefined); + await client.initialize(); + assert(client.modelServiceStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new modelserviceModule.v1beta2.ModelServiceClient({ - 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 close method for the initialized client', (done) => { + const client = new modelserviceModule.v1beta2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.modelServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new modelserviceModule.v1beta2.ModelServiceClient({ - 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('has close method for the non-initialized client', (done) => { + const client = new modelserviceModule.v1beta2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.modelServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('getModel', () => { - it('invokes getModel without error', async () => { - const client = new modelserviceModule.v1beta2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta2.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.Model() - ); - client.innerApiCalls.getModel = stubSimpleCall(expectedResponse); - const [response] = await client.getModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel 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 modelserviceModule.v1beta2.ModelServiceClient({ + 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 getModel without error using callback', async () => { - const client = new modelserviceModule.v1beta2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta2.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.Model() - ); - client.innerApiCalls.getModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getModel( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta2.IModel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel 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 modelserviceModule.v1beta2.ModelServiceClient({ + 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('getModel', () => { + it('invokes getModel without error', async () => { + const client = new modelserviceModule.v1beta2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta2.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.Model(), + ); + client.innerApiCalls.getModel = stubSimpleCall(expectedResponse); + const [response] = await client.getModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getModel with error', async () => { - const client = new modelserviceModule.v1beta2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta2.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getModel(request), expectedError); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getModel without error using callback', async () => { + const client = new modelserviceModule.v1beta2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta2.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.Model(), + ); + client.innerApiCalls.getModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getModel( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta2.IModel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getModel with closed client', async () => { - const client = new modelserviceModule.v1beta2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta2.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getModel(request), expectedError); - }); + it('invokes getModel with error', async () => { + const client = new modelserviceModule.v1beta2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta2.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getModel = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listModels', () => { - it('invokes listModels without error', async () => { - const client = new modelserviceModule.v1beta2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.ListModelsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta2.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta2.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta2.Model()), - ]; - client.innerApiCalls.listModels = stubSimpleCall(expectedResponse); - const [response] = await client.listModels(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes getModel with closed client', async () => { + const client = new modelserviceModule.v1beta2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta2.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getModel(request), expectedError); + }); + }); + + describe('listModels', () => { + it('invokes listModels without error', async () => { + const client = new modelserviceModule.v1beta2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.ListModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.Model(), + ), + ]; + client.innerApiCalls.listModels = stubSimpleCall(expectedResponse); + const [response] = await client.listModels(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes listModels without error using callback', async () => { - const client = new modelserviceModule.v1beta2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.ListModelsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta2.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta2.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta2.Model()), - ]; - client.innerApiCalls.listModels = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listModels( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta2.IModel[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listModels without error using callback', async () => { + const client = new modelserviceModule.v1beta2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.ListModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.Model(), + ), + ]; + client.innerApiCalls.listModels = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listModels( + request, + ( + err?: Error | null, + result?: + | protos.google.ai.generativelanguage.v1beta2.IModel[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes listModels with error', async () => { - const client = new modelserviceModule.v1beta2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.ListModelsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listModels = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listModels(request), expectedError); - }); + it('invokes listModels with error', async () => { + const client = new modelserviceModule.v1beta2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.ListModelsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listModels = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listModels(request), expectedError); + }); - it('invokes listModelsStream without error', async () => { - const client = new modelserviceModule.v1beta2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.ListModelsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta2.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta2.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta2.Model()), - ]; - client.descriptors.page.listModels.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1beta2.Model[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta2.Model) => { - 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.listModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listModels, request)); + it('invokes listModelsStream without error', async () => { + const client = new modelserviceModule.v1beta2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.ListModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.Model(), + ), + ]; + client.descriptors.page.listModels.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1beta2.Model[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1beta2.Model) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listModelsStream with error', async () => { - const client = new modelserviceModule.v1beta2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.ListModelsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listModels.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1beta2.Model[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta2.Model) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listModels, request)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listModels, request), + ); + }); - it('uses async iteration with listModels without error', async () => { - const client = new modelserviceModule.v1beta2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.ListModelsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta2.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta2.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta2.Model()), - ]; - client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ai.generativelanguage.v1beta2.IModel[] = []; - const iterable = client.listModelsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); + it('invokes listModelsStream with error', async () => { + const client = new modelserviceModule.v1beta2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.ListModelsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listModels.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1beta2.Model[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1beta2.Model) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with listModels with error', async () => { - const client = new modelserviceModule.v1beta2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.ListModelsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listModelsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ai.generativelanguage.v1beta2.IModel[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listModels, request), + ); }); - describe('Path templates', () => { - - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new modelserviceModule.v1beta2.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listModels without error', async () => { + const client = new modelserviceModule.v1beta2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.ListModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.Model(), + ), + ]; + client.descriptors.page.listModels.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ai.generativelanguage.v1beta2.IModel[] = + []; + const iterable = client.listModelsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listModels.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); + + it('uses async iteration with listModels with error', async () => { + const client = new modelserviceModule.v1beta2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.ListModelsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listModelsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ai.generativelanguage.v1beta2.IModel[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listModels.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); + }); + + describe('Path templates', () => { + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = new modelserviceModule.v1beta2.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_model_service_v1beta3.ts b/packages/google-ai-generativelanguage/test/gapic_model_service_v1beta3.ts index 9edcbf16ce9c..97f7324d6729 100644 --- a/packages/google-ai-generativelanguage/test/gapic_model_service_v1beta3.ts +++ b/packages/google-ai-generativelanguage/test/gapic_model_service_v1beta3.ts @@ -19,1515 +19,1930 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as modelserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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('v1beta3.ModelServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.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 = modelserviceModule.v1beta3.ModelServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = modelserviceModule.v1beta3.ModelServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); + it('has universeDomain', () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 = + modelserviceModule.v1beta3.ModelServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + modelserviceModule.v1beta3.ModelServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.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 modelserviceModule.v1beta3.ModelServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 modelserviceModule.v1beta3.ModelServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 modelserviceModule.v1beta3.ModelServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('has port', () => { - const port = modelserviceModule.v1beta3.ModelServiceClient.port; - assert(port); - assert(typeof port === 'number'); + 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 modelserviceModule.v1beta3.ModelServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with no option', () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient(); - assert(client); + 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 modelserviceModule.v1beta3.ModelServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with gRPC fallback', () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - fallback: true, - }); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new modelserviceModule.v1beta3.ModelServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.modelServiceStub, undefined); - await client.initialize(); - assert(client.modelServiceStub); - }); + it('has port', () => { + const port = modelserviceModule.v1beta3.ModelServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the initialized client', done => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.modelServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient(); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.modelServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - 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 initialize method and supports deferred initialization', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.modelServiceStub, undefined); + await client.initialize(); + assert(client.modelServiceStub); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - 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('has close method for the initialized client', (done) => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.modelServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('getModel', () => { - it('invokes getModel without error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.Model() - ); - client.innerApiCalls.getModel = stubSimpleCall(expectedResponse); - const [response] = await client.getModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel 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 modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.modelServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getModel without error using callback', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.Model() - ); - client.innerApiCalls.getModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getModel( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta3.IModel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel 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 modelserviceModule.v1beta3.ModelServiceClient({ + 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 getModel with error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getModel(request), expectedError); - const actualRequest = (client.innerApiCalls.getModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getModel 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 modelserviceModule.v1beta3.ModelServiceClient({ + 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('getModel', () => { + it('invokes getModel without error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Model(), + ); + client.innerApiCalls.getModel = stubSimpleCall(expectedResponse); + const [response] = await client.getModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getModel with closed client', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GetModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.GetModelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getModel(request), expectedError); - }); + it('invokes getModel without error using callback', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Model(), + ); + client.innerApiCalls.getModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getModel( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta3.IModel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getTunedModel', () => { - it('invokes getTunedModel without error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GetTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.GetTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.TunedModel() - ); - client.innerApiCalls.getTunedModel = stubSimpleCall(expectedResponse); - const [response] = await client.getTunedModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getModel with error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getModel = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getTunedModel without error using callback', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GetTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.GetTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.TunedModel() - ); - client.innerApiCalls.getTunedModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getTunedModel( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta3.ITunedModel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getModel with closed client', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GetModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.GetModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getModel(request), expectedError); + }); + }); + + describe('getTunedModel', () => { + it('invokes getTunedModel without error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GetTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.GetTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.TunedModel(), + ); + client.innerApiCalls.getTunedModel = stubSimpleCall(expectedResponse); + const [response] = await client.getTunedModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getTunedModel with error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GetTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.GetTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getTunedModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getTunedModel(request), expectedError); - const actualRequest = (client.innerApiCalls.getTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getTunedModel without error using callback', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GetTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.GetTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.TunedModel(), + ); + client.innerApiCalls.getTunedModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getTunedModel( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta3.ITunedModel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getTunedModel with closed client', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GetTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.GetTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getTunedModel(request), expectedError); - }); + it('invokes getTunedModel with error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GetTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.GetTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getTunedModel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getTunedModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateTunedModel', () => { - it('invokes updateTunedModel without error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.UpdateTunedModelRequest() - ); - request.tunedModel ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.UpdateTunedModelRequest', ['tunedModel', 'name']); - request.tunedModel.name = defaultValue1; - const expectedHeaderRequestParams = `tuned_model.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.TunedModel() - ); - client.innerApiCalls.updateTunedModel = stubSimpleCall(expectedResponse); - const [response] = await client.updateTunedModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getTunedModel with closed client', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GetTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.GetTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getTunedModel(request), expectedError); + }); + }); + + describe('updateTunedModel', () => { + it('invokes updateTunedModel without error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.UpdateTunedModelRequest(), + ); + request.tunedModel ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.UpdateTunedModelRequest', + ['tunedModel', 'name'], + ); + request.tunedModel.name = defaultValue1; + const expectedHeaderRequestParams = `tuned_model.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.TunedModel(), + ); + client.innerApiCalls.updateTunedModel = stubSimpleCall(expectedResponse); + const [response] = await client.updateTunedModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateTunedModel without error using callback', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.UpdateTunedModelRequest() - ); - request.tunedModel ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.UpdateTunedModelRequest', ['tunedModel', 'name']); - request.tunedModel.name = defaultValue1; - const expectedHeaderRequestParams = `tuned_model.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.TunedModel() - ); - client.innerApiCalls.updateTunedModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateTunedModel( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta3.ITunedModel|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateTunedModel without error using callback', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.UpdateTunedModelRequest(), + ); + request.tunedModel ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.UpdateTunedModelRequest', + ['tunedModel', 'name'], + ); + request.tunedModel.name = defaultValue1; + const expectedHeaderRequestParams = `tuned_model.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.TunedModel(), + ); + client.innerApiCalls.updateTunedModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateTunedModel( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta3.ITunedModel | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateTunedModel with error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.UpdateTunedModelRequest() - ); - request.tunedModel ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.UpdateTunedModelRequest', ['tunedModel', 'name']); - request.tunedModel.name = defaultValue1; - const expectedHeaderRequestParams = `tuned_model.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateTunedModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateTunedModel(request), expectedError); - const actualRequest = (client.innerApiCalls.updateTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateTunedModel with error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.UpdateTunedModelRequest(), + ); + request.tunedModel ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.UpdateTunedModelRequest', + ['tunedModel', 'name'], + ); + request.tunedModel.name = defaultValue1; + const expectedHeaderRequestParams = `tuned_model.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateTunedModel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateTunedModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateTunedModel with closed client', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.UpdateTunedModelRequest() - ); - request.tunedModel ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.UpdateTunedModelRequest', ['tunedModel', 'name']); - request.tunedModel.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateTunedModel(request), expectedError); - }); + it('invokes updateTunedModel with closed client', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.UpdateTunedModelRequest(), + ); + request.tunedModel ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.UpdateTunedModelRequest', + ['tunedModel', 'name'], + ); + request.tunedModel.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateTunedModel(request), expectedError); + }); + }); + + describe('deleteTunedModel', () => { + it('invokes deleteTunedModel without error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.DeleteTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.DeleteTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteTunedModel = stubSimpleCall(expectedResponse); + const [response] = await client.deleteTunedModel(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteTunedModel', () => { - it('invokes deleteTunedModel without error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.DeleteTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.DeleteTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteTunedModel = stubSimpleCall(expectedResponse); - const [response] = await client.deleteTunedModel(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteTunedModel without error using callback', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.DeleteTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.DeleteTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteTunedModel = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteTunedModel( + 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.deleteTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTunedModel without error using callback', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.DeleteTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.DeleteTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteTunedModel = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteTunedModel( - 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.deleteTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteTunedModel with error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.DeleteTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.DeleteTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteTunedModel = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteTunedModel(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteTunedModel as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteTunedModel as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteTunedModel with error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.DeleteTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.DeleteTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteTunedModel = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteTunedModel(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteTunedModel as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteTunedModel as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteTunedModel with closed client', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.DeleteTunedModelRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.DeleteTunedModelRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteTunedModel(request), expectedError); + }); + }); + + describe('createTunedModel', () => { + it('invokes createTunedModel without error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.CreateTunedModelRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createTunedModel = + stubLongRunningCall(expectedResponse); + const [operation] = await client.createTunedModel(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes deleteTunedModel with closed client', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.DeleteTunedModelRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.DeleteTunedModelRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteTunedModel(request), expectedError); - }); + it('invokes createTunedModel without error using callback', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.CreateTunedModelRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createTunedModel = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createTunedModel( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + protos.google.ai.generativelanguage.v1beta3.ICreateTunedModelMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.ai.generativelanguage.v1beta3.ITunedModel, + protos.google.ai.generativelanguage.v1beta3.ICreateTunedModelMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); }); - describe('createTunedModel', () => { - it('invokes createTunedModel without error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.CreateTunedModelRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createTunedModel = stubLongRunningCall(expectedResponse); - const [operation] = await client.createTunedModel(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes createTunedModel with call error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.CreateTunedModelRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createTunedModel = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.createTunedModel(request), expectedError); + }); - it('invokes createTunedModel without error using callback', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.CreateTunedModelRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createTunedModel = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createTunedModel( - 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); - }); + it('invokes createTunedModel with LRO error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.CreateTunedModelRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createTunedModel = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.createTunedModel(request); + await assert.rejects(operation.promise(), expectedError); + }); - it('invokes createTunedModel with call error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.CreateTunedModelRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createTunedModel = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.createTunedModel(request), expectedError); - }); + it('invokes checkCreateTunedModelProgress without error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + 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.checkCreateTunedModelProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes createTunedModel with LRO error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.CreateTunedModelRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createTunedModel = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.createTunedModel(request); - await assert.rejects(operation.promise(), expectedError); - }); + it('invokes checkCreateTunedModelProgress with error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + 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.checkCreateTunedModelProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('listModels', () => { + it('invokes listModels without error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.ListModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Model(), + ), + ]; + client.innerApiCalls.listModels = stubSimpleCall(expectedResponse); + const [response] = await client.listModels(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes checkCreateTunedModelProgress without error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - 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.checkCreateTunedModelProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes listModels without error using callback', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.ListModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Model(), + ), + ]; + client.innerApiCalls.listModels = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listModels( + request, + ( + err?: Error | null, + result?: + | protos.google.ai.generativelanguage.v1beta3.IModel[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes checkCreateTunedModelProgress with error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - 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.checkCreateTunedModelProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes listModels with error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.ListModelsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listModels = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listModels(request), expectedError); }); - describe('listModels', () => { - it('invokes listModels without error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.ListModelsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Model()), - ]; - client.innerApiCalls.listModels = stubSimpleCall(expectedResponse); - const [response] = await client.listModels(request); - assert.deepStrictEqual(response, expectedResponse); + it('invokes listModelsStream without error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.ListModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Model(), + ), + ]; + client.descriptors.page.listModels.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1beta3.Model[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1beta3.Model) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listModels without error using callback', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.ListModelsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Model()), - ]; - client.innerApiCalls.listModels = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listModels( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta3.IModel[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listModels, request), + ); + }); - it('invokes listModels with error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.ListModelsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listModels = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listModels(request), expectedError); + it('invokes listModelsStream with error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.ListModelsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listModels.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1beta3.Model[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1beta3.Model) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listModelsStream without error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.ListModelsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Model()), - ]; - client.descriptors.page.listModels.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1beta3.Model[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta3.Model) => { - 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.listModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listModels, request)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listModels, request), + ); + }); - it('invokes listModelsStream with error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.ListModelsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listModels.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1beta3.Model[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta3.Model) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listModels, request)); - }); + it('uses async iteration with listModels without error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.ListModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Model(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Model(), + ), + ]; + client.descriptors.page.listModels.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ai.generativelanguage.v1beta3.IModel[] = + []; + const iterable = client.listModelsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listModels.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); - it('uses async iteration with listModels without error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.ListModelsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Model()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Model()), - ]; - client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ai.generativelanguage.v1beta3.IModel[] = []; - const iterable = client.listModelsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('uses async iteration with listModels with error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.ListModelsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listModelsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ai.generativelanguage.v1beta3.IModel[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listModels.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); + }); + + describe('listTunedModels', () => { + it('invokes listTunedModels without error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.ListTunedModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.TunedModel(), + ), + ]; + client.innerApiCalls.listTunedModels = stubSimpleCall(expectedResponse); + const [response] = await client.listTunedModels(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('uses async iteration with listModels with error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.ListModelsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listModels.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listModelsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ai.generativelanguage.v1beta3.IModel[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('invokes listTunedModels without error using callback', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.ListTunedModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.TunedModel(), + ), + ]; + client.innerApiCalls.listTunedModels = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listTunedModels( + request, + ( + err?: Error | null, + result?: + | protos.google.ai.generativelanguage.v1beta3.ITunedModel[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); }); - describe('listTunedModels', () => { - it('invokes listTunedModels without error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.ListTunedModelsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.TunedModel()), - ]; - client.innerApiCalls.listTunedModels = stubSimpleCall(expectedResponse); - const [response] = await client.listTunedModels(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes listTunedModels with error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.ListTunedModelsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listTunedModels = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listTunedModels(request), expectedError); + }); - it('invokes listTunedModels without error using callback', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.ListTunedModelsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.TunedModel()), - ]; - client.innerApiCalls.listTunedModels = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listTunedModels( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta3.ITunedModel[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('invokes listTunedModelsStream without error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.ListTunedModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.TunedModel(), + ), + ]; + client.descriptors.page.listTunedModels.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listTunedModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1beta3.TunedModel[] = + []; + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1beta3.TunedModel, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listTunedModels with error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.ListTunedModelsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listTunedModels = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listTunedModels(request), expectedError); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listTunedModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTunedModels, request), + ); + }); - it('invokes listTunedModelsStream without error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.ListTunedModelsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.TunedModel()), - ]; - client.descriptors.page.listTunedModels.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listTunedModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1beta3.TunedModel[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta3.TunedModel) => { - 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.listTunedModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTunedModels, request)); + it('invokes listTunedModelsStream with error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.ListTunedModelsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listTunedModels.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listTunedModelsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1beta3.TunedModel[] = + []; + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1beta3.TunedModel, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listTunedModelsStream with error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.ListTunedModelsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listTunedModels.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listTunedModelsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1beta3.TunedModel[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta3.TunedModel) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listTunedModels.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listTunedModels, request)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listTunedModels.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listTunedModels, request), + ); + }); - it('uses async iteration with listTunedModels without error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.ListTunedModelsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.TunedModel()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.TunedModel()), - ]; - client.descriptors.page.listTunedModels.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ai.generativelanguage.v1beta3.ITunedModel[] = []; - const iterable = client.listTunedModelsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listTunedModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('uses async iteration with listTunedModels without error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.ListTunedModelsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.TunedModel(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.TunedModel(), + ), + ]; + client.descriptors.page.listTunedModels.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ai.generativelanguage.v1beta3.ITunedModel[] = + []; + const iterable = client.listTunedModelsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listTunedModels.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); - it('uses async iteration with listTunedModels with error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.ListTunedModelsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listTunedModels.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listTunedModelsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ai.generativelanguage.v1beta3.ITunedModel[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listTunedModels.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('uses async iteration with listTunedModels with error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.ListTunedModelsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listTunedModels.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listTunedModelsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ai.generativelanguage.v1beta3.ITunedModel[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listTunedModels.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); }); - describe('getOperation', () => { - it('invokes getOperation without error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - 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 modelserviceModule.v1beta3.ModelServiceClient({ - 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 modelserviceModule.v1beta3.ModelServiceClient({ - 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('getOperation', () => { + it('invokes getOperation without error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + 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('cancelOperation', () => { - it('invokes cancelOperation without error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - 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 modelserviceModule.v1beta3.ModelServiceClient({ - 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 modelserviceModule.v1beta3.ModelServiceClient({ - 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)); - }); + it('invokes getOperation without error using callback', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + 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)); }); - describe('deleteOperation', () => { - it('invokes deleteOperation without error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - 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 modelserviceModule.v1beta3.ModelServiceClient({ - 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 modelserviceModule.v1beta3.ModelServiceClient({ - 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 getOperation with error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + 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('listOperationsAsync', () => { - it('uses async iteration with listOperations without error', async () => { - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - 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 modelserviceModule.v1beta3.ModelServiceClient({ - 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('cancelOperation', () => { + it('invokes cancelOperation without error', async () => { + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + 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 modelserviceModule.v1beta3.ModelServiceClient({ + 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 modelserviceModule.v1beta3.ModelServiceClient({ + 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 modelserviceModule.v1beta3.ModelServiceClient({ + 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 modelserviceModule.v1beta3.ModelServiceClient({ + 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 modelserviceModule.v1beta3.ModelServiceClient({ + 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 modelserviceModule.v1beta3.ModelServiceClient({ + 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 modelserviceModule.v1beta3.ModelServiceClient({ + 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('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); - describe('Path templates', () => { - - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('permission', async () => { - const fakePath = "/rendered/path/permission"; - const expectedParameters = { - tuned_model: "tunedModelValue", - permission: "permissionValue", - }; - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.permissionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.permissionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('permissionPath', () => { - const result = client.permissionPath("tunedModelValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.permissionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromPermissionName', () => { - const result = client.matchTunedModelFromPermissionName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.permissionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromPermissionName', () => { - const result = client.matchPermissionFromPermissionName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.permissionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('permission', async () => { + const fakePath = '/rendered/path/permission'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + permission: 'permissionValue', + }; + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.permissionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.permissionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('permissionPath', () => { + const result = client.permissionPath( + 'tunedModelValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.permissionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromPermissionName', () => { + const result = client.matchTunedModelFromPermissionName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.permissionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromPermissionName', () => { + const result = client.matchPermissionFromPermissionName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + (client.pathTemplates.permissionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModel', async () => { - const fakePath = "/rendered/path/tunedModel"; - const expectedParameters = { - tuned_model: "tunedModelValue", - }; - const client = new modelserviceModule.v1beta3.ModelServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPath', () => { - const result = client.tunedModelPath("tunedModelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelName', () => { - const result = client.matchTunedModelFromTunedModelName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModel', async () => { + const fakePath = '/rendered/path/tunedModel'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + }; + const client = new modelserviceModule.v1beta3.ModelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPath', () => { + const result = client.tunedModelPath('tunedModelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.tunedModelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelName', () => { + const result = client.matchTunedModelFromTunedModelName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.tunedModelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_permission_service_v1alpha.ts b/packages/google-ai-generativelanguage/test/gapic_permission_service_v1alpha.ts index e32fb505d370..d15cf5ce6c3b 100644 --- a/packages/google-ai-generativelanguage/test/gapic_permission_service_v1alpha.ts +++ b/packages/google-ai-generativelanguage/test/gapic_permission_service_v1alpha.ts @@ -19,1345 +19,1782 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as permissionserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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 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('v1alpha.PermissionServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.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 = permissionserviceModule.v1alpha.PermissionServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + it('has universeDomain', () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = permissionserviceModule.v1alpha.PermissionServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 = + permissionserviceModule.v1alpha.PermissionServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + permissionserviceModule.v1alpha.PermissionServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + universeDomain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + universe_domain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.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 permissionserviceModule.v1alpha.PermissionServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 permissionserviceModule.v1alpha.PermissionServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 permissionserviceModule.v1alpha.PermissionServiceClient({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 permissionserviceModule.v1alpha.PermissionServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = permissionserviceModule.v1alpha.PermissionServiceClient.port; - assert(port); - assert(typeof port === 'number'); + 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 permissionserviceModule.v1alpha.PermissionServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new permissionserviceModule.v1alpha.PermissionServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = permissionserviceModule.v1alpha.PermissionServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.permissionServiceStub, undefined); - await client.initialize(); - assert(client.permissionServiceStub); - }); + it('should create a client with no option', () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.permissionServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('should create a client with gRPC fallback', () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + fallback: true, }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.permissionServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has initialize method and supports deferred initialization', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.permissionServiceStub, undefined); + await client.initialize(); + assert(client.permissionServiceStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - 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 close method for the initialized client', (done) => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - 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); + client.initialize().catch((err) => { + throw err; + }); + assert(client.permissionServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('createPermission', () => { - it('invokes createPermission without error', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreatePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CreatePermissionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.Permission() - ); - client.innerApiCalls.createPermission = stubSimpleCall(expectedResponse); - const [response] = await client.createPermission(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createPermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createPermission 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 permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes createPermission without error using callback', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreatePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CreatePermissionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.Permission() - ); - client.innerApiCalls.createPermission = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createPermission( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IPermission|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createPermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createPermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + assert.strictEqual(client.permissionServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes createPermission with error', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreatePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CreatePermissionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createPermission = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createPermission(request), expectedError); - const actualRequest = (client.innerApiCalls.createPermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createPermission 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 permissionserviceModule.v1alpha.PermissionServiceClient({ + 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 createPermission with closed client', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreatePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CreatePermissionRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createPermission(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + 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('getPermission', () => { - it('invokes getPermission without error', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetPermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetPermissionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.Permission() - ); - client.innerApiCalls.getPermission = stubSimpleCall(expectedResponse); - const [response] = await client.getPermission(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getPermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getPermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('createPermission', () => { + it('invokes createPermission without error', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreatePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CreatePermissionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Permission(), + ); + client.innerApiCalls.createPermission = stubSimpleCall(expectedResponse); + const [response] = await client.createPermission(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createPermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createPermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getPermission without error using callback', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetPermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetPermissionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.Permission() - ); - client.innerApiCalls.getPermission = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getPermission( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IPermission|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getPermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getPermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes createPermission without error using callback', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreatePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CreatePermissionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Permission(), + ); + client.innerApiCalls.createPermission = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createPermission( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.IPermission | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createPermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createPermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getPermission with error', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetPermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetPermissionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getPermission = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getPermission(request), expectedError); - const actualRequest = (client.innerApiCalls.getPermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getPermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes createPermission with error', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreatePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CreatePermissionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createPermission = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createPermission(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createPermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createPermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getPermission with closed client', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetPermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetPermissionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getPermission(request), expectedError); + it('invokes createPermission with closed client', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreatePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CreatePermissionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createPermission(request), expectedError); }); - - describe('updatePermission', () => { - it('invokes updatePermission without error', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdatePermissionRequest() - ); - request.permission ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.UpdatePermissionRequest', ['permission', 'name']); - request.permission.name = defaultValue1; - const expectedHeaderRequestParams = `permission.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.Permission() - ); - client.innerApiCalls.updatePermission = stubSimpleCall(expectedResponse); - const [response] = await client.updatePermission(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updatePermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updatePermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('getPermission', () => { + it('invokes getPermission without error', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetPermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetPermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Permission(), + ); + client.innerApiCalls.getPermission = stubSimpleCall(expectedResponse); + const [response] = await client.getPermission(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getPermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getPermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updatePermission without error using callback', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdatePermissionRequest() - ); - request.permission ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.UpdatePermissionRequest', ['permission', 'name']); - request.permission.name = defaultValue1; - const expectedHeaderRequestParams = `permission.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.Permission() - ); - client.innerApiCalls.updatePermission = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updatePermission( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IPermission|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updatePermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updatePermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getPermission without error using callback', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetPermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetPermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Permission(), + ); + client.innerApiCalls.getPermission = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getPermission( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.IPermission | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getPermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getPermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updatePermission with error', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdatePermissionRequest() - ); - request.permission ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.UpdatePermissionRequest', ['permission', 'name']); - request.permission.name = defaultValue1; - const expectedHeaderRequestParams = `permission.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updatePermission = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updatePermission(request), expectedError); - const actualRequest = (client.innerApiCalls.updatePermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updatePermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getPermission with error', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetPermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetPermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getPermission = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getPermission(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getPermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getPermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updatePermission with closed client', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdatePermissionRequest() - ); - request.permission ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.UpdatePermissionRequest', ['permission', 'name']); - request.permission.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updatePermission(request), expectedError); + it('invokes getPermission with closed client', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetPermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetPermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getPermission(request), expectedError); }); - - describe('deletePermission', () => { - it('invokes deletePermission without error', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeletePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeletePermissionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deletePermission = stubSimpleCall(expectedResponse); - const [response] = await client.deletePermission(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deletePermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deletePermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('updatePermission', () => { + it('invokes updatePermission without error', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdatePermissionRequest(), + ); + request.permission ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.UpdatePermissionRequest', + ['permission', 'name'], + ); + request.permission.name = defaultValue1; + const expectedHeaderRequestParams = `permission.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Permission(), + ); + client.innerApiCalls.updatePermission = stubSimpleCall(expectedResponse); + const [response] = await client.updatePermission(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updatePermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updatePermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deletePermission without error using callback', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeletePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeletePermissionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deletePermission = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deletePermission( - 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.deletePermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deletePermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes updatePermission without error using callback', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdatePermissionRequest(), + ); + request.permission ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.UpdatePermissionRequest', + ['permission', 'name'], + ); + request.permission.name = defaultValue1; + const expectedHeaderRequestParams = `permission.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Permission(), + ); + client.innerApiCalls.updatePermission = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updatePermission( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.IPermission | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updatePermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updatePermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deletePermission with error', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeletePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeletePermissionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deletePermission = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deletePermission(request), expectedError); - const actualRequest = (client.innerApiCalls.deletePermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deletePermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes updatePermission with error', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdatePermissionRequest(), + ); + request.permission ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.UpdatePermissionRequest', + ['permission', 'name'], + ); + request.permission.name = defaultValue1; + const expectedHeaderRequestParams = `permission.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updatePermission = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updatePermission(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updatePermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updatePermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deletePermission with closed client', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeletePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeletePermissionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deletePermission(request), expectedError); + it('invokes updatePermission with closed client', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdatePermissionRequest(), + ); + request.permission ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.UpdatePermissionRequest', + ['permission', 'name'], + ); + request.permission.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updatePermission(request), expectedError); }); - - describe('transferOwnership', () => { - it('invokes transferOwnership without error', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.TransferOwnershipRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.TransferOwnershipRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.TransferOwnershipResponse() - ); - client.innerApiCalls.transferOwnership = stubSimpleCall(expectedResponse); - const [response] = await client.transferOwnership(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.transferOwnership as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.transferOwnership as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('deletePermission', () => { + it('invokes deletePermission without error', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeletePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeletePermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deletePermission = stubSimpleCall(expectedResponse); + const [response] = await client.deletePermission(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deletePermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deletePermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes transferOwnership without error using callback', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.TransferOwnershipRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.TransferOwnershipRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.TransferOwnershipResponse() - ); - client.innerApiCalls.transferOwnership = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.transferOwnership( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.transferOwnership as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.transferOwnership as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes deletePermission without error using callback', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeletePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeletePermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deletePermission = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deletePermission( + 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.deletePermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deletePermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes transferOwnership with error', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.TransferOwnershipRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.TransferOwnershipRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.transferOwnership = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.transferOwnership(request), expectedError); - const actualRequest = (client.innerApiCalls.transferOwnership as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.transferOwnership as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes deletePermission with error', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeletePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeletePermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deletePermission = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deletePermission(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deletePermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deletePermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes transferOwnership with closed client', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.TransferOwnershipRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.TransferOwnershipRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.transferOwnership(request), expectedError); + it('invokes deletePermission with closed client', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeletePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeletePermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deletePermission(request), expectedError); }); - - describe('listPermissions', () => { - it('invokes listPermissions without error', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.ListPermissionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Permission()), - ]; - client.innerApiCalls.listPermissions = stubSimpleCall(expectedResponse); - const [response] = await client.listPermissions(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listPermissions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listPermissions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + describe('transferOwnership', () => { + it('invokes transferOwnership without error', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.TransferOwnershipRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.TransferOwnershipRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.TransferOwnershipResponse(), + ); + client.innerApiCalls.transferOwnership = stubSimpleCall(expectedResponse); + const [response] = await client.transferOwnership(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.transferOwnership as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.transferOwnership as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listPermissions without error using callback', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.ListPermissionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Permission()), - ]; - client.innerApiCalls.listPermissions = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listPermissions( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IPermission[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listPermissions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listPermissions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes transferOwnership without error using callback', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.TransferOwnershipRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.TransferOwnershipRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.TransferOwnershipResponse(), + ); + client.innerApiCalls.transferOwnership = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.transferOwnership( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.ITransferOwnershipResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.transferOwnership as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.transferOwnership as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listPermissions with error', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.ListPermissionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listPermissions = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listPermissions(request), expectedError); - const actualRequest = (client.innerApiCalls.listPermissions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listPermissions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes transferOwnership with error', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.TransferOwnershipRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.TransferOwnershipRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.transferOwnership = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.transferOwnership(request), expectedError); + const actualRequest = ( + client.innerApiCalls.transferOwnership as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.transferOwnership as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listPermissionsStream without error', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.ListPermissionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Permission()), - ]; - client.descriptors.page.listPermissions.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listPermissionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1alpha.Permission[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1alpha.Permission) => { - 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.listPermissions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listPermissions, request)); - assert( - (client.descriptors.page.listPermissions.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes transferOwnership with closed client', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes listPermissionsStream with error', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.ListPermissionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listPermissions.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listPermissionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1alpha.Permission[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1alpha.Permission) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listPermissions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listPermissions, request)); - assert( - (client.descriptors.page.listPermissions.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.TransferOwnershipRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.TransferOwnershipRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.transferOwnership(request), expectedError); + }); + }); + + describe('listPermissions', () => { + it('invokes listPermissions without error', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.ListPermissionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Permission(), + ), + ]; + client.innerApiCalls.listPermissions = stubSimpleCall(expectedResponse); + const [response] = await client.listPermissions(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listPermissions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listPermissions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listPermissions without error', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.ListPermissionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Permission()), - ]; - client.descriptors.page.listPermissions.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ai.generativelanguage.v1alpha.IPermission[] = []; - const iterable = client.listPermissionsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listPermissions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listPermissions.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listPermissions without error using callback', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.ListPermissionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Permission(), + ), + ]; + client.innerApiCalls.listPermissions = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listPermissions( + request, + ( + err?: Error | null, + result?: + | protos.google.ai.generativelanguage.v1alpha.IPermission[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listPermissions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listPermissions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listPermissions with error', async () => { - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.ListPermissionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listPermissions.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listPermissionsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ai.generativelanguage.v1alpha.IPermission[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listPermissions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listPermissions.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listPermissions with error', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.ListPermissionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listPermissions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listPermissions(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listPermissions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listPermissions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('cachedContent', async () => { - const fakePath = "/rendered/path/cachedContent"; - const expectedParameters = { - id: "idValue", - }; - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.cachedContentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.cachedContentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('cachedContentPath', () => { - const result = client.cachedContentPath("idValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.cachedContentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchIdFromCachedContentName', () => { - const result = client.matchIdFromCachedContentName(fakePath); - assert.strictEqual(result, "idValue"); - assert((client.pathTemplates.cachedContentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listPermissionsStream without error', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - describe('chunk', async () => { - const fakePath = "/rendered/path/chunk"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - chunk: "chunkValue", - }; - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.chunkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.chunkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('chunkPath', () => { - const result = client.chunkPath("corpusValue", "documentValue", "chunkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.chunkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromChunkName', () => { - const result = client.matchCorpusFromChunkName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromChunkName', () => { - const result = client.matchDocumentFromChunkName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChunkFromChunkName', () => { - const result = client.matchChunkFromChunkName(fakePath); - assert.strictEqual(result, "chunkValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.ListPermissionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Permission(), + ), + ]; + client.descriptors.page.listPermissions.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listPermissionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1alpha.Permission[] = + []; + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1alpha.Permission, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - describe('corpus', async () => { - const fakePath = "/rendered/path/corpus"; - const expectedParameters = { - corpus: "corpusValue", - }; - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPath', () => { - const result = client.corpusPath("corpusValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusName', () => { - const result = client.matchCorpusFromCorpusName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listPermissions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listPermissions, request), + ); + assert( + (client.descriptors.page.listPermissions.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('corpusPermissions', async () => { - const fakePath = "/rendered/path/corpusPermissions"; - const expectedParameters = { - corpus: "corpusValue", - permission: "permissionValue", - }; - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPermissionsPath', () => { - const result = client.corpusPermissionsPath("corpusValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusPermissionsName', () => { - const result = client.matchCorpusFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromCorpusPermissionsName', () => { - const result = client.matchPermissionFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listPermissionsStream with error', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.ListPermissionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listPermissions.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listPermissionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1alpha.Permission[] = + []; + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1alpha.Permission, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listPermissions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listPermissions, request), + ); + assert( + (client.descriptors.page.listPermissions.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('document', async () => { - const fakePath = "/rendered/path/document"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - }; - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.documentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.documentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('documentPath', () => { - const result = client.documentPath("corpusValue", "documentValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.documentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromDocumentName', () => { - const result = client.matchCorpusFromDocumentName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromDocumentName', () => { - const result = client.matchDocumentFromDocumentName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('uses async iteration with listPermissions without error', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.ListPermissionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Permission(), + ), + ]; + client.descriptors.page.listPermissions.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ai.generativelanguage.v1alpha.IPermission[] = + []; + const iterable = client.listPermissionsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listPermissions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listPermissions.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('file', async () => { - const fakePath = "/rendered/path/file"; - const expectedParameters = { - file: "fileValue", - }; - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.filePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.filePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('filePath', () => { - const result = client.filePath("fileValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.filePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('uses async iteration with listPermissions with error', async () => { + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.ListPermissionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listPermissions.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listPermissionsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ai.generativelanguage.v1alpha.IPermission[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listPermissions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listPermissions.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('cachedContent', async () => { + const fakePath = '/rendered/path/cachedContent'; + const expectedParameters = { + id: 'idValue', + }; + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.cachedContentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.cachedContentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('cachedContentPath', () => { + const result = client.cachedContentPath('idValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.cachedContentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchIdFromCachedContentName', () => { + const result = client.matchIdFromCachedContentName(fakePath); + assert.strictEqual(result, 'idValue'); + assert( + (client.pathTemplates.cachedContentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchFileFromFileName', () => { - const result = client.matchFileFromFileName(fakePath); - assert.strictEqual(result, "fileValue"); - assert((client.pathTemplates.filePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('chunk', async () => { + const fakePath = '/rendered/path/chunk'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + chunk: 'chunkValue', + }; + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.chunkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.chunkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('chunkPath', () => { + const result = client.chunkPath( + 'corpusValue', + 'documentValue', + 'chunkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.chunkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromChunkName', () => { + const result = client.matchCorpusFromChunkName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromChunkName', () => { + const result = client.matchDocumentFromChunkName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChunkFromChunkName', () => { + const result = client.matchChunkFromChunkName(fakePath); + assert.strictEqual(result, 'chunkValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('corpus', async () => { + const fakePath = '/rendered/path/corpus'; + const expectedParameters = { + corpus: 'corpusValue', + }; + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPath', () => { + const result = client.corpusPath('corpusValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.corpusPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusName', () => { + const result = client.matchCorpusFromCorpusName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.corpusPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('corpusPermissions', async () => { + const fakePath = '/rendered/path/corpusPermissions'; + const expectedParameters = { + corpus: 'corpusValue', + permission: 'permissionValue', + }; + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.corpusPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPermissionsPath', () => { + const result = client.corpusPermissionsPath( + 'corpusValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusPermissionsName', () => { + const result = client.matchCorpusFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromCorpusPermissionsName', () => { + const result = + client.matchPermissionFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModel', async () => { - const fakePath = "/rendered/path/tunedModel"; - const expectedParameters = { - tuned_model: "tunedModelValue", - }; - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPath', () => { - const result = client.tunedModelPath("tunedModelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('document', async () => { + const fakePath = '/rendered/path/document'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + }; + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.documentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.documentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('documentPath', () => { + const result = client.documentPath('corpusValue', 'documentValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.documentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromDocumentName', () => { + const result = client.matchCorpusFromDocumentName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromDocumentName', () => { + const result = client.matchDocumentFromDocumentName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchTunedModelFromTunedModelName', () => { - const result = client.matchTunedModelFromTunedModelName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('file', async () => { + const fakePath = '/rendered/path/file'; + const expectedParameters = { + file: 'fileValue', + }; + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.filePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.filePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('filePath', () => { + const result = client.filePath('fileValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.filePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFileFromFileName', () => { + const result = client.matchFileFromFileName(fakePath); + assert.strictEqual(result, 'fileValue'); + assert( + (client.pathTemplates.filePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModelPermissions', async () => { - const fakePath = "/rendered/path/tunedModelPermissions"; - const expectedParameters = { - tuned_model: "tunedModelValue", - permission: "permissionValue", - }; - const client = new permissionserviceModule.v1alpha.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPermissionsPath', () => { - const result = client.tunedModelPermissionsPath("tunedModelValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchTunedModelFromTunedModelPermissionsName', () => { - const result = client.matchTunedModelFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('tunedModel', async () => { + const fakePath = '/rendered/path/tunedModel'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + }; + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPath', () => { + const result = client.tunedModelPath('tunedModelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.tunedModelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelName', () => { + const result = client.matchTunedModelFromTunedModelName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.tunedModelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchPermissionFromTunedModelPermissionsName', () => { - const result = client.matchPermissionFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('tunedModelPermissions', async () => { + const fakePath = '/rendered/path/tunedModelPermissions'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + permission: 'permissionValue', + }; + const client = + new permissionserviceModule.v1alpha.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.tunedModelPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPermissionsPath', () => { + const result = client.tunedModelPermissionsPath( + 'tunedModelValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelPermissionsName', () => { + const result = + client.matchTunedModelFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromTunedModelPermissionsName', () => { + const result = + client.matchPermissionFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_permission_service_v1beta.ts b/packages/google-ai-generativelanguage/test/gapic_permission_service_v1beta.ts index 4765d906db17..b84122e47f6f 100644 --- a/packages/google-ai-generativelanguage/test/gapic_permission_service_v1beta.ts +++ b/packages/google-ai-generativelanguage/test/gapic_permission_service_v1beta.ts @@ -19,1345 +19,1818 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as permissionserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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 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('v1beta.PermissionServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient(); - 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 = permissionserviceModule.v1beta.PermissionServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = permissionserviceModule.v1beta.PermissionServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 permissionserviceModule.v1beta.PermissionServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 permissionserviceModule.v1beta.PermissionServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 permissionserviceModule.v1beta.PermissionServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = permissionserviceModule.v1beta.PermissionServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new permissionserviceModule.v1beta.PermissionServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + }); - it('should create a client with no option', () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient(); - assert(client); - }); + it('has universeDomain', () => { + const client = + new permissionserviceModule.v1beta.PermissionServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - fallback: true, - }); - assert(client); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + permissionserviceModule.v1beta.PermissionServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + permissionserviceModule.v1beta.PermissionServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { universeDomain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.permissionServiceStub, undefined); - await client.initialize(); - assert(client.permissionServiceStub); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { universe_domain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('has close method for the initialized client', done => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.permissionServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + 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 permissionserviceModule.v1beta.PermissionServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has close method for the non-initialized client', done => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.permissionServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + 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 permissionserviceModule.v1beta.PermissionServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - 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 permissionserviceModule.v1beta.PermissionServiceClient({ - 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('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new permissionserviceModule.v1beta.PermissionServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('createPermission', () => { - it('invokes createPermission without error', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreatePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CreatePermissionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.Permission() - ); - client.innerApiCalls.createPermission = stubSimpleCall(expectedResponse); - const [response] = await client.createPermission(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createPermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createPermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createPermission without error using callback', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreatePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CreatePermissionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.Permission() - ); - client.innerApiCalls.createPermission = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createPermission( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IPermission|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createPermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createPermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = permissionserviceModule.v1beta.PermissionServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes createPermission with error', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreatePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CreatePermissionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createPermission = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createPermission(request), expectedError); - const actualRequest = (client.innerApiCalls.createPermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createPermission 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 permissionserviceModule.v1beta.PermissionServiceClient(); + assert(client); + }); - it('invokes createPermission with closed client', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreatePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CreatePermissionRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createPermission(request), expectedError); - }); + it('should create a client with gRPC fallback', () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + fallback: true, + }, + ); + assert(client); }); - describe('getPermission', () => { - it('invokes getPermission without error', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetPermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetPermissionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.Permission() - ); - client.innerApiCalls.getPermission = stubSimpleCall(expectedResponse); - const [response] = await client.getPermission(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getPermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getPermission 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 permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.permissionServiceStub, undefined); + await client.initialize(); + assert(client.permissionServiceStub); + }); - it('invokes getPermission without error using callback', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetPermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetPermissionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.Permission() - ); - client.innerApiCalls.getPermission = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getPermission( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IPermission|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getPermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getPermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getPermission with error', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetPermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetPermissionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getPermission = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getPermission(request), expectedError); - const actualRequest = (client.innerApiCalls.getPermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getPermission 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 permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + assert(client.permissionServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getPermission with closed client', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetPermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetPermissionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getPermission(request), expectedError); + it('has close method for the non-initialized client', (done) => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.permissionServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('updatePermission', () => { - it('invokes updatePermission without error', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdatePermissionRequest() - ); - request.permission ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.UpdatePermissionRequest', ['permission', 'name']); - request.permission.name = defaultValue1; - const expectedHeaderRequestParams = `permission.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.Permission() - ); - client.innerApiCalls.updatePermission = stubSimpleCall(expectedResponse); - const [response] = await client.updatePermission(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updatePermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updatePermission 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 permissionserviceModule.v1beta.PermissionServiceClient( + { + 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 updatePermission without error using callback', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdatePermissionRequest() - ); - request.permission ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.UpdatePermissionRequest', ['permission', 'name']); - request.permission.name = defaultValue1; - const expectedHeaderRequestParams = `permission.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.Permission() - ); - client.innerApiCalls.updatePermission = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updatePermission( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IPermission|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updatePermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updatePermission 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 permissionserviceModule.v1beta.PermissionServiceClient( + { + 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('createPermission', () => { + it('invokes createPermission without error', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreatePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CreatePermissionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Permission(), + ); + client.innerApiCalls.createPermission = stubSimpleCall(expectedResponse); + const [response] = await client.createPermission(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createPermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createPermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updatePermission with error', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdatePermissionRequest() - ); - request.permission ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.UpdatePermissionRequest', ['permission', 'name']); - request.permission.name = defaultValue1; - const expectedHeaderRequestParams = `permission.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updatePermission = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updatePermission(request), expectedError); - const actualRequest = (client.innerApiCalls.updatePermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updatePermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createPermission without error using callback', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreatePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CreatePermissionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Permission(), + ); + client.innerApiCalls.createPermission = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createPermission( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IPermission | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createPermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createPermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updatePermission with closed client', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdatePermissionRequest() - ); - request.permission ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.UpdatePermissionRequest', ['permission', 'name']); - request.permission.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updatePermission(request), expectedError); - }); + it('invokes createPermission with error', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreatePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CreatePermissionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createPermission = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createPermission(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createPermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createPermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deletePermission', () => { - it('invokes deletePermission without error', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeletePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeletePermissionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deletePermission = stubSimpleCall(expectedResponse); - const [response] = await client.deletePermission(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deletePermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deletePermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createPermission with closed client', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreatePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CreatePermissionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createPermission(request), expectedError); + }); + }); + + describe('getPermission', () => { + it('invokes getPermission without error', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetPermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetPermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Permission(), + ); + client.innerApiCalls.getPermission = stubSimpleCall(expectedResponse); + const [response] = await client.getPermission(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getPermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getPermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deletePermission without error using callback', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeletePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeletePermissionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deletePermission = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deletePermission( - 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.deletePermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deletePermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getPermission without error using callback', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetPermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetPermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Permission(), + ); + client.innerApiCalls.getPermission = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getPermission( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IPermission | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getPermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getPermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deletePermission with error', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeletePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeletePermissionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deletePermission = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deletePermission(request), expectedError); - const actualRequest = (client.innerApiCalls.deletePermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deletePermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getPermission with error', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetPermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetPermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getPermission = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getPermission(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getPermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getPermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deletePermission with closed client', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeletePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeletePermissionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deletePermission(request), expectedError); - }); + it('invokes getPermission with closed client', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetPermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetPermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getPermission(request), expectedError); + }); + }); + + describe('updatePermission', () => { + it('invokes updatePermission without error', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdatePermissionRequest(), + ); + request.permission ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.UpdatePermissionRequest', + ['permission', 'name'], + ); + request.permission.name = defaultValue1; + const expectedHeaderRequestParams = `permission.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Permission(), + ); + client.innerApiCalls.updatePermission = stubSimpleCall(expectedResponse); + const [response] = await client.updatePermission(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updatePermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updatePermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('transferOwnership', () => { - it('invokes transferOwnership without error', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.TransferOwnershipRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.TransferOwnershipRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.TransferOwnershipResponse() - ); - client.innerApiCalls.transferOwnership = stubSimpleCall(expectedResponse); - const [response] = await client.transferOwnership(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.transferOwnership as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.transferOwnership as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updatePermission without error using callback', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdatePermissionRequest(), + ); + request.permission ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.UpdatePermissionRequest', + ['permission', 'name'], + ); + request.permission.name = defaultValue1; + const expectedHeaderRequestParams = `permission.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Permission(), + ); + client.innerApiCalls.updatePermission = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updatePermission( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IPermission | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updatePermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updatePermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes transferOwnership without error using callback', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.TransferOwnershipRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.TransferOwnershipRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.TransferOwnershipResponse() - ); - client.innerApiCalls.transferOwnership = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.transferOwnership( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.ITransferOwnershipResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.transferOwnership as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.transferOwnership as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updatePermission with error', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdatePermissionRequest(), + ); + request.permission ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.UpdatePermissionRequest', + ['permission', 'name'], + ); + request.permission.name = defaultValue1; + const expectedHeaderRequestParams = `permission.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updatePermission = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updatePermission(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updatePermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updatePermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes transferOwnership with error', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.TransferOwnershipRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.TransferOwnershipRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.transferOwnership = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.transferOwnership(request), expectedError); - const actualRequest = (client.innerApiCalls.transferOwnership as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.transferOwnership as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updatePermission with closed client', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdatePermissionRequest(), + ); + request.permission ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.UpdatePermissionRequest', + ['permission', 'name'], + ); + request.permission.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updatePermission(request), expectedError); + }); + }); + + describe('deletePermission', () => { + it('invokes deletePermission without error', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeletePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeletePermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deletePermission = stubSimpleCall(expectedResponse); + const [response] = await client.deletePermission(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deletePermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deletePermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes transferOwnership with closed client', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.TransferOwnershipRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.TransferOwnershipRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.transferOwnership(request), expectedError); - }); + it('invokes deletePermission without error using callback', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeletePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeletePermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deletePermission = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deletePermission( + 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.deletePermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deletePermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listPermissions', () => { - it('invokes listPermissions without error', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.ListPermissionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Permission()), - ]; - client.innerApiCalls.listPermissions = stubSimpleCall(expectedResponse); - const [response] = await client.listPermissions(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listPermissions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listPermissions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deletePermission with error', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeletePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeletePermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deletePermission = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deletePermission(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deletePermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deletePermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listPermissions without error using callback', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.ListPermissionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Permission()), - ]; - client.innerApiCalls.listPermissions = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listPermissions( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IPermission[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listPermissions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listPermissions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deletePermission with closed client', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeletePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeletePermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deletePermission(request), expectedError); + }); + }); + + describe('transferOwnership', () => { + it('invokes transferOwnership without error', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.TransferOwnershipRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.TransferOwnershipRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.TransferOwnershipResponse(), + ); + client.innerApiCalls.transferOwnership = stubSimpleCall(expectedResponse); + const [response] = await client.transferOwnership(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.transferOwnership as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.transferOwnership as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listPermissions with error', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.ListPermissionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listPermissions = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listPermissions(request), expectedError); - const actualRequest = (client.innerApiCalls.listPermissions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listPermissions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes transferOwnership without error using callback', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.TransferOwnershipRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.TransferOwnershipRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.TransferOwnershipResponse(), + ); + client.innerApiCalls.transferOwnership = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.transferOwnership( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.ITransferOwnershipResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.transferOwnership as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.transferOwnership as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listPermissionsStream without error', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.ListPermissionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Permission()), - ]; - client.descriptors.page.listPermissions.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listPermissionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1beta.Permission[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta.Permission) => { - 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.listPermissions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listPermissions, request)); - assert( - (client.descriptors.page.listPermissions.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes transferOwnership with error', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.TransferOwnershipRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.TransferOwnershipRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.transferOwnership = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.transferOwnership(request), expectedError); + const actualRequest = ( + client.innerApiCalls.transferOwnership as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.transferOwnership as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listPermissionsStream with error', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.ListPermissionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listPermissions.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listPermissionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1beta.Permission[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta.Permission) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listPermissions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listPermissions, request)); - assert( - (client.descriptors.page.listPermissions.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes transferOwnership with closed client', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.TransferOwnershipRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.TransferOwnershipRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.transferOwnership(request), expectedError); + }); + }); + + describe('listPermissions', () => { + it('invokes listPermissions without error', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.ListPermissionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Permission(), + ), + ]; + client.innerApiCalls.listPermissions = stubSimpleCall(expectedResponse); + const [response] = await client.listPermissions(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listPermissions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listPermissions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listPermissions without error', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.ListPermissionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Permission()), - ]; - client.descriptors.page.listPermissions.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ai.generativelanguage.v1beta.IPermission[] = []; - const iterable = client.listPermissionsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listPermissions without error using callback', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.ListPermissionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Permission(), + ), + ]; + client.innerApiCalls.listPermissions = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listPermissions( + request, + ( + err?: Error | null, + result?: + | protos.google.ai.generativelanguage.v1beta.IPermission[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listPermissions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listPermissions.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listPermissions with error', async () => { - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.ListPermissionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listPermissions.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listPermissionsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ai.generativelanguage.v1beta.IPermission[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listPermissions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listPermissions.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.listPermissions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listPermissions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('cachedContent', async () => { - const fakePath = "/rendered/path/cachedContent"; - const expectedParameters = { - id: "idValue", - }; - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.cachedContentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.cachedContentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('cachedContentPath', () => { - const result = client.cachedContentPath("idValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.cachedContentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes listPermissions with error', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.ListPermissionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listPermissions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listPermissions(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listPermissions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listPermissions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchIdFromCachedContentName', () => { - const result = client.matchIdFromCachedContentName(fakePath); - assert.strictEqual(result, "idValue"); - assert((client.pathTemplates.cachedContentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listPermissionsStream without error', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.ListPermissionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Permission(), + ), + ]; + client.descriptors.page.listPermissions.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listPermissionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1beta.Permission[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1beta.Permission) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - describe('chunk', async () => { - const fakePath = "/rendered/path/chunk"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - chunk: "chunkValue", - }; - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.chunkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.chunkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('chunkPath', () => { - const result = client.chunkPath("corpusValue", "documentValue", "chunkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.chunkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromChunkName', () => { - const result = client.matchCorpusFromChunkName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromChunkName', () => { - const result = client.matchDocumentFromChunkName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChunkFromChunkName', () => { - const result = client.matchChunkFromChunkName(fakePath); - assert.strictEqual(result, "chunkValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listPermissions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listPermissions, request), + ); + assert( + (client.descriptors.page.listPermissions.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('corpus', async () => { - const fakePath = "/rendered/path/corpus"; - const expectedParameters = { - corpus: "corpusValue", - }; - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPath', () => { - const result = client.corpusPath("corpusValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusName', () => { - const result = client.matchCorpusFromCorpusName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listPermissionsStream with error', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.ListPermissionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listPermissions.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listPermissionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1beta.Permission[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1beta.Permission) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - describe('corpusPermissions', async () => { - const fakePath = "/rendered/path/corpusPermissions"; - const expectedParameters = { - corpus: "corpusValue", - permission: "permissionValue", - }; - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPermissionsPath', () => { - const result = client.corpusPermissionsPath("corpusValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusPermissionsName', () => { - const result = client.matchCorpusFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromCorpusPermissionsName', () => { - const result = client.matchPermissionFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listPermissions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listPermissions, request), + ); + assert( + (client.descriptors.page.listPermissions.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('document', async () => { - const fakePath = "/rendered/path/document"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - }; - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.documentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.documentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('documentPath', () => { - const result = client.documentPath("corpusValue", "documentValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.documentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromDocumentName', () => { - const result = client.matchCorpusFromDocumentName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromDocumentName', () => { - const result = client.matchDocumentFromDocumentName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listPermissions without error', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.ListPermissionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Permission(), + ), + ]; + client.descriptors.page.listPermissions.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ai.generativelanguage.v1beta.IPermission[] = + []; + const iterable = client.listPermissionsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listPermissions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listPermissions.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('file', async () => { - const fakePath = "/rendered/path/file"; - const expectedParameters = { - file: "fileValue", - }; - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.filePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.filePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('filePath', () => { - const result = client.filePath("fileValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.filePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('uses async iteration with listPermissions with error', async () => { + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.ListPermissionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listPermissions.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listPermissionsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ai.generativelanguage.v1beta.IPermission[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listPermissions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listPermissions.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('cachedContent', async () => { + const fakePath = '/rendered/path/cachedContent'; + const expectedParameters = { + id: 'idValue', + }; + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.cachedContentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.cachedContentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('cachedContentPath', () => { + const result = client.cachedContentPath('idValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.cachedContentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchIdFromCachedContentName', () => { + const result = client.matchIdFromCachedContentName(fakePath); + assert.strictEqual(result, 'idValue'); + assert( + (client.pathTemplates.cachedContentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchFileFromFileName', () => { - const result = client.matchFileFromFileName(fakePath); - assert.strictEqual(result, "fileValue"); - assert((client.pathTemplates.filePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('chunk', async () => { + const fakePath = '/rendered/path/chunk'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + chunk: 'chunkValue', + }; + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.chunkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.chunkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('chunkPath', () => { + const result = client.chunkPath( + 'corpusValue', + 'documentValue', + 'chunkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.chunkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromChunkName', () => { + const result = client.matchCorpusFromChunkName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromChunkName', () => { + const result = client.matchDocumentFromChunkName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChunkFromChunkName', () => { + const result = client.matchChunkFromChunkName(fakePath); + assert.strictEqual(result, 'chunkValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('corpus', async () => { + const fakePath = '/rendered/path/corpus'; + const expectedParameters = { + corpus: 'corpusValue', + }; + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.corpusPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPath', () => { + const result = client.corpusPath('corpusValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.corpusPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusName', () => { + const result = client.matchCorpusFromCorpusName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.corpusPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpusPermissions', async () => { + const fakePath = '/rendered/path/corpusPermissions'; + const expectedParameters = { + corpus: 'corpusValue', + permission: 'permissionValue', + }; + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.corpusPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPermissionsPath', () => { + const result = client.corpusPermissionsPath( + 'corpusValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusPermissionsName', () => { + const result = client.matchCorpusFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromCorpusPermissionsName', () => { + const result = + client.matchPermissionFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModel', async () => { - const fakePath = "/rendered/path/tunedModel"; - const expectedParameters = { - tuned_model: "tunedModelValue", - }; - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPath', () => { - const result = client.tunedModelPath("tunedModelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('document', async () => { + const fakePath = '/rendered/path/document'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + }; + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.documentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.documentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('documentPath', () => { + const result = client.documentPath('corpusValue', 'documentValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.documentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromDocumentName', () => { + const result = client.matchCorpusFromDocumentName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromDocumentName', () => { + const result = client.matchDocumentFromDocumentName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchTunedModelFromTunedModelName', () => { - const result = client.matchTunedModelFromTunedModelName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('file', async () => { + const fakePath = '/rendered/path/file'; + const expectedParameters = { + file: 'fileValue', + }; + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.filePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.filePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('filePath', () => { + const result = client.filePath('fileValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.filePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFileFromFileName', () => { + const result = client.matchFileFromFileName(fakePath); + assert.strictEqual(result, 'fileValue'); + assert( + (client.pathTemplates.filePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModelPermissions', async () => { - const fakePath = "/rendered/path/tunedModelPermissions"; - const expectedParameters = { - tuned_model: "tunedModelValue", - permission: "permissionValue", - }; - const client = new permissionserviceModule.v1beta.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPermissionsPath', () => { - const result = client.tunedModelPermissionsPath("tunedModelValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchTunedModelFromTunedModelPermissionsName', () => { - const result = client.matchTunedModelFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('tunedModel', async () => { + const fakePath = '/rendered/path/tunedModel'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + }; + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.tunedModelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPath', () => { + const result = client.tunedModelPath('tunedModelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.tunedModelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelName', () => { + const result = client.matchTunedModelFromTunedModelName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.tunedModelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchPermissionFromTunedModelPermissionsName', () => { - const result = client.matchPermissionFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModelPermissions', async () => { + const fakePath = '/rendered/path/tunedModelPermissions'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + permission: 'permissionValue', + }; + const client = new permissionserviceModule.v1beta.PermissionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.tunedModelPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPermissionsPath', () => { + const result = client.tunedModelPermissionsPath( + 'tunedModelValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelPermissionsName', () => { + const result = + client.matchTunedModelFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromTunedModelPermissionsName', () => { + const result = + client.matchPermissionFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_permission_service_v1beta3.ts b/packages/google-ai-generativelanguage/test/gapic_permission_service_v1beta3.ts index f6e1bf35fdf2..2e1f10833738 100644 --- a/packages/google-ai-generativelanguage/test/gapic_permission_service_v1beta3.ts +++ b/packages/google-ai-generativelanguage/test/gapic_permission_service_v1beta3.ts @@ -19,1133 +19,1476 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as permissionserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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 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('v1beta3.PermissionServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + it('has universeDomain', () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient(); + 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 = permissionserviceModule.v1beta3.PermissionServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + permissionserviceModule.v1beta3.PermissionServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = permissionserviceModule.v1beta3.PermissionServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + permissionserviceModule.v1beta3.PermissionServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + universeDomain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + universe_domain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.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 permissionserviceModule.v1beta3.PermissionServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); + 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 permissionserviceModule.v1beta3.PermissionServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.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 permissionserviceModule.v1beta3.PermissionServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.configured.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 permissionserviceModule.v1beta3.PermissionServiceClient({ + universeDomain: 'configured.example.com', }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new permissionserviceModule.v1beta3.PermissionServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('has port', () => { - const port = permissionserviceModule.v1beta3.PermissionServiceClient.port; - assert(port); - assert(typeof port === 'number'); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new permissionserviceModule.v1beta3.PermissionServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with no option', () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient(); - assert(client); - }); + it('has port', () => { + const port = permissionserviceModule.v1beta3.PermissionServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('should create a client with gRPC fallback', () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - fallback: true, - }); - assert(client); + it('should create a client with no option', () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + fallback: true, }); + assert(client); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.permissionServiceStub, undefined); - await client.initialize(); - assert(client.permissionServiceStub); + it('has initialize method and supports deferred initialization', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.permissionServiceStub, undefined); + await client.initialize(); + assert(client.permissionServiceStub); + }); - it('has close method for the initialized client', done => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.permissionServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has close method for the initialized client', (done) => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.permissionServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; + }); + }); - it('has close method for the non-initialized client', done => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.permissionServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has close method for the non-initialized client', (done) => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.permissionServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - 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 permissionserviceModule.v1beta3.PermissionServiceClient({ + 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 permissionserviceModule.v1beta3.PermissionServiceClient({ - 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('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + 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('createPermission', () => { - it('invokes createPermission without error', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.CreatePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.CreatePermissionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.Permission() - ); - client.innerApiCalls.createPermission = stubSimpleCall(expectedResponse); - const [response] = await client.createPermission(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createPermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createPermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + describe('createPermission', () => { + it('invokes createPermission without error', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.CreatePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.CreatePermissionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Permission(), + ); + client.innerApiCalls.createPermission = stubSimpleCall(expectedResponse); + const [response] = await client.createPermission(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createPermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createPermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createPermission without error using callback', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.CreatePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.CreatePermissionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.Permission() - ); - client.innerApiCalls.createPermission = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createPermission( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta3.IPermission|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createPermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createPermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes createPermission without error using callback', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.CreatePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.CreatePermissionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Permission(), + ); + client.innerApiCalls.createPermission = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createPermission( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta3.IPermission | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createPermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createPermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createPermission with error', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.CreatePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.CreatePermissionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createPermission = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createPermission(request), expectedError); - const actualRequest = (client.innerApiCalls.createPermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createPermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes createPermission with error', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.CreatePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.CreatePermissionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createPermission = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createPermission(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createPermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createPermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createPermission with closed client', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.CreatePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.CreatePermissionRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createPermission(request), expectedError); + it('invokes createPermission with closed client', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.CreatePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.CreatePermissionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createPermission(request), expectedError); }); + }); - describe('getPermission', () => { - it('invokes getPermission without error', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GetPermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.GetPermissionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.Permission() - ); - client.innerApiCalls.getPermission = stubSimpleCall(expectedResponse); - const [response] = await client.getPermission(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getPermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getPermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + describe('getPermission', () => { + it('invokes getPermission without error', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GetPermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.GetPermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Permission(), + ); + client.innerApiCalls.getPermission = stubSimpleCall(expectedResponse); + const [response] = await client.getPermission(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getPermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getPermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getPermission without error using callback', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GetPermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.GetPermissionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.Permission() - ); - client.innerApiCalls.getPermission = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getPermission( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta3.IPermission|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getPermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getPermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getPermission without error using callback', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GetPermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.GetPermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Permission(), + ); + client.innerApiCalls.getPermission = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getPermission( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta3.IPermission | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getPermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getPermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getPermission with error', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GetPermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.GetPermissionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getPermission = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getPermission(request), expectedError); - const actualRequest = (client.innerApiCalls.getPermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getPermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getPermission with error', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GetPermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.GetPermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getPermission = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getPermission(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getPermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getPermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getPermission with closed client', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GetPermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.GetPermissionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getPermission(request), expectedError); + it('invokes getPermission with closed client', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GetPermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.GetPermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getPermission(request), expectedError); }); + }); - describe('updatePermission', () => { - it('invokes updatePermission without error', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.UpdatePermissionRequest() - ); - request.permission ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.UpdatePermissionRequest', ['permission', 'name']); - request.permission.name = defaultValue1; - const expectedHeaderRequestParams = `permission.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.Permission() - ); - client.innerApiCalls.updatePermission = stubSimpleCall(expectedResponse); - const [response] = await client.updatePermission(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updatePermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updatePermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + describe('updatePermission', () => { + it('invokes updatePermission without error', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.UpdatePermissionRequest(), + ); + request.permission ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.UpdatePermissionRequest', + ['permission', 'name'], + ); + request.permission.name = defaultValue1; + const expectedHeaderRequestParams = `permission.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Permission(), + ); + client.innerApiCalls.updatePermission = stubSimpleCall(expectedResponse); + const [response] = await client.updatePermission(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updatePermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updatePermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updatePermission without error using callback', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.UpdatePermissionRequest() - ); - request.permission ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.UpdatePermissionRequest', ['permission', 'name']); - request.permission.name = defaultValue1; - const expectedHeaderRequestParams = `permission.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.Permission() - ); - client.innerApiCalls.updatePermission = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updatePermission( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta3.IPermission|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updatePermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updatePermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes updatePermission without error using callback', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.UpdatePermissionRequest(), + ); + request.permission ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.UpdatePermissionRequest', + ['permission', 'name'], + ); + request.permission.name = defaultValue1; + const expectedHeaderRequestParams = `permission.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Permission(), + ); + client.innerApiCalls.updatePermission = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updatePermission( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta3.IPermission | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updatePermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updatePermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updatePermission with error', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.UpdatePermissionRequest() - ); - request.permission ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.UpdatePermissionRequest', ['permission', 'name']); - request.permission.name = defaultValue1; - const expectedHeaderRequestParams = `permission.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updatePermission = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updatePermission(request), expectedError); - const actualRequest = (client.innerApiCalls.updatePermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updatePermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes updatePermission with error', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.UpdatePermissionRequest(), + ); + request.permission ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.UpdatePermissionRequest', + ['permission', 'name'], + ); + request.permission.name = defaultValue1; + const expectedHeaderRequestParams = `permission.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updatePermission = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updatePermission(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updatePermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updatePermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updatePermission with closed client', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.UpdatePermissionRequest() - ); - request.permission ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.UpdatePermissionRequest', ['permission', 'name']); - request.permission.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updatePermission(request), expectedError); + it('invokes updatePermission with closed client', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.UpdatePermissionRequest(), + ); + request.permission ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.UpdatePermissionRequest', + ['permission', 'name'], + ); + request.permission.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updatePermission(request), expectedError); }); + }); - describe('deletePermission', () => { - it('invokes deletePermission without error', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.DeletePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.DeletePermissionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deletePermission = stubSimpleCall(expectedResponse); - const [response] = await client.deletePermission(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deletePermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deletePermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + describe('deletePermission', () => { + it('invokes deletePermission without error', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.DeletePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.DeletePermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deletePermission = stubSimpleCall(expectedResponse); + const [response] = await client.deletePermission(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deletePermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deletePermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deletePermission without error using callback', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.DeletePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.DeletePermissionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deletePermission = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deletePermission( - 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.deletePermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deletePermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes deletePermission without error using callback', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.DeletePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.DeletePermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deletePermission = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deletePermission( + 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.deletePermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deletePermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deletePermission with error', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.DeletePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.DeletePermissionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deletePermission = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deletePermission(request), expectedError); - const actualRequest = (client.innerApiCalls.deletePermission as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deletePermission as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes deletePermission with error', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.DeletePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.DeletePermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deletePermission = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deletePermission(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deletePermission as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deletePermission as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deletePermission with closed client', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.DeletePermissionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.DeletePermissionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deletePermission(request), expectedError); + it('invokes deletePermission with closed client', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.DeletePermissionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.DeletePermissionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deletePermission(request), expectedError); }); + }); - describe('transferOwnership', () => { - it('invokes transferOwnership without error', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.TransferOwnershipRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.TransferOwnershipRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.TransferOwnershipResponse() - ); - client.innerApiCalls.transferOwnership = stubSimpleCall(expectedResponse); - const [response] = await client.transferOwnership(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.transferOwnership as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.transferOwnership as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + describe('transferOwnership', () => { + it('invokes transferOwnership without error', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.TransferOwnershipRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.TransferOwnershipRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.TransferOwnershipResponse(), + ); + client.innerApiCalls.transferOwnership = stubSimpleCall(expectedResponse); + const [response] = await client.transferOwnership(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.transferOwnership as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.transferOwnership as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes transferOwnership without error using callback', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.TransferOwnershipRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.TransferOwnershipRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.TransferOwnershipResponse() - ); - client.innerApiCalls.transferOwnership = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.transferOwnership( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.transferOwnership as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.transferOwnership as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes transferOwnership without error using callback', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.TransferOwnershipRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.TransferOwnershipRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.TransferOwnershipResponse(), + ); + client.innerApiCalls.transferOwnership = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.transferOwnership( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta3.ITransferOwnershipResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.transferOwnership as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.transferOwnership as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes transferOwnership with error', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.TransferOwnershipRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.TransferOwnershipRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.transferOwnership = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.transferOwnership(request), expectedError); - const actualRequest = (client.innerApiCalls.transferOwnership as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.transferOwnership as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes transferOwnership with error', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.TransferOwnershipRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.TransferOwnershipRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.transferOwnership = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.transferOwnership(request), expectedError); + const actualRequest = ( + client.innerApiCalls.transferOwnership as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.transferOwnership as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes transferOwnership with closed client', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.TransferOwnershipRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.TransferOwnershipRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.transferOwnership(request), expectedError); + it('invokes transferOwnership with closed client', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.TransferOwnershipRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.TransferOwnershipRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.transferOwnership(request), expectedError); }); + }); - describe('listPermissions', () => { - it('invokes listPermissions without error', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.ListPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.ListPermissionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Permission()), - ]; - client.innerApiCalls.listPermissions = stubSimpleCall(expectedResponse); - const [response] = await client.listPermissions(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listPermissions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listPermissions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + describe('listPermissions', () => { + it('invokes listPermissions without error', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.ListPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.ListPermissionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Permission(), + ), + ]; + client.innerApiCalls.listPermissions = stubSimpleCall(expectedResponse); + const [response] = await client.listPermissions(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listPermissions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listPermissions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listPermissions without error using callback', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.ListPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.ListPermissionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Permission()), - ]; - client.innerApiCalls.listPermissions = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listPermissions( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta3.IPermission[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listPermissions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listPermissions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listPermissions without error using callback', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.ListPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.ListPermissionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Permission(), + ), + ]; + client.innerApiCalls.listPermissions = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listPermissions( + request, + ( + err?: Error | null, + result?: + | protos.google.ai.generativelanguage.v1beta3.IPermission[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listPermissions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listPermissions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listPermissions with error', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.ListPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.ListPermissionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listPermissions = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listPermissions(request), expectedError); - const actualRequest = (client.innerApiCalls.listPermissions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listPermissions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listPermissions with error', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.ListPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.ListPermissionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listPermissions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listPermissions(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listPermissions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listPermissions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listPermissionsStream without error', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.ListPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.ListPermissionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Permission()), - ]; - client.descriptors.page.listPermissions.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listPermissionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1beta3.Permission[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta3.Permission) => { - 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.listPermissions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listPermissions, request)); - assert( - (client.descriptors.page.listPermissions.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listPermissionsStream without error', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.ListPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.ListPermissionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Permission(), + ), + ]; + client.descriptors.page.listPermissions.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listPermissionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1beta3.Permission[] = + []; + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1beta3.Permission, + ) => { + 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.listPermissions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listPermissions, request), + ); + assert( + (client.descriptors.page.listPermissions.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listPermissionsStream with error', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.ListPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.ListPermissionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listPermissions.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listPermissionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1beta3.Permission[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta3.Permission) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listPermissions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listPermissions, request)); - assert( - (client.descriptors.page.listPermissions.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listPermissionsStream with error', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.ListPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.ListPermissionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listPermissions.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listPermissionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1beta3.Permission[] = + []; + stream.on( + 'data', + ( + response: protos.google.ai.generativelanguage.v1beta3.Permission, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listPermissions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listPermissions, request), + ); + assert( + (client.descriptors.page.listPermissions.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listPermissions without error', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.ListPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.ListPermissionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Permission()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta3.Permission()), - ]; - client.descriptors.page.listPermissions.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ai.generativelanguage.v1beta3.IPermission[] = []; - const iterable = client.listPermissionsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listPermissions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listPermissions.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('uses async iteration with listPermissions without error', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.ListPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.ListPermissionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Permission(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.Permission(), + ), + ]; + client.descriptors.page.listPermissions.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ai.generativelanguage.v1beta3.IPermission[] = + []; + const iterable = client.listPermissionsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listPermissions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listPermissions.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listPermissions with error', async () => { - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.ListPermissionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.ListPermissionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listPermissions.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listPermissionsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ai.generativelanguage.v1beta3.IPermission[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listPermissions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listPermissions.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('uses async iteration with listPermissions with error', async () => { + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.ListPermissionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.ListPermissionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listPermissions.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listPermissionsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ai.generativelanguage.v1beta3.IPermission[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listPermissions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listPermissions.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); + }); - describe('Path templates', () => { + describe('Path templates', () => { + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('permission', async () => { + const fakePath = '/rendered/path/permission'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + permission: 'permissionValue', + }; + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.permissionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.permissionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); - describe('permission', async () => { - const fakePath = "/rendered/path/permission"; - const expectedParameters = { - tuned_model: "tunedModelValue", - permission: "permissionValue", - }; - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.permissionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.permissionPathTemplate.match = - sinon.stub().returns(expectedParameters); + it('permissionPath', () => { + const result = client.permissionPath( + 'tunedModelValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.permissionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); - it('permissionPath', () => { - const result = client.permissionPath("tunedModelValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.permissionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('matchTunedModelFromPermissionName', () => { + const result = client.matchTunedModelFromPermissionName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.permissionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); - it('matchTunedModelFromPermissionName', () => { - const result = client.matchTunedModelFromPermissionName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.permissionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('matchPermissionFromPermissionName', () => { + const result = client.matchPermissionFromPermissionName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + (client.pathTemplates.permissionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchPermissionFromPermissionName', () => { - const result = client.matchPermissionFromPermissionName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.permissionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('tunedModel', async () => { + const fakePath = '/rendered/path/tunedModel'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + }; + const client = + new permissionserviceModule.v1beta3.PermissionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.tunedModelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); - describe('tunedModel', async () => { - const fakePath = "/rendered/path/tunedModel"; - const expectedParameters = { - tuned_model: "tunedModelValue", - }; - const client = new permissionserviceModule.v1beta3.PermissionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPathTemplate.match = - sinon.stub().returns(expectedParameters); + it('tunedModelPath', () => { + const result = client.tunedModelPath('tunedModelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.tunedModelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); - it('tunedModelPath', () => { - const result = client.tunedModelPath("tunedModelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelName', () => { - const result = client.matchTunedModelFromTunedModelName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('matchTunedModelFromTunedModelName', () => { + const result = client.matchTunedModelFromTunedModelName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.tunedModelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_prediction_service_v1alpha.ts b/packages/google-ai-generativelanguage/test/gapic_prediction_service_v1alpha.ts index 31ca9d2b883d..54b3bd7fa42a 100644 --- a/packages/google-ai-generativelanguage/test/gapic_prediction_service_v1alpha.ts +++ b/packages/google-ai-generativelanguage/test/gapic_prediction_service_v1alpha.ts @@ -19,617 +19,826 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as predictionserviceModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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); } describe('v1alpha.PredictionServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new predictionserviceModule.v1alpha.PredictionServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new predictionserviceModule.v1alpha.PredictionServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new predictionserviceModule.v1alpha.PredictionServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.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 = predictionserviceModule.v1alpha.PredictionServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + it('has universeDomain', () => { + const client = + new predictionserviceModule.v1alpha.PredictionServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = predictionserviceModule.v1alpha.PredictionServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new predictionserviceModule.v1alpha.PredictionServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 = + predictionserviceModule.v1alpha.PredictionServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + predictionserviceModule.v1alpha.PredictionServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new predictionserviceModule.v1alpha.PredictionServiceClient({ + universeDomain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new predictionserviceModule.v1alpha.PredictionServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new predictionserviceModule.v1alpha.PredictionServiceClient({ + universe_domain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.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 predictionserviceModule.v1alpha.PredictionServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 predictionserviceModule.v1alpha.PredictionServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 predictionserviceModule.v1alpha.PredictionServiceClient({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 predictionserviceModule.v1alpha.PredictionServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = predictionserviceModule.v1alpha.PredictionServiceClient.port; - assert(port); - assert(typeof port === 'number'); + 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 predictionserviceModule.v1alpha.PredictionServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new predictionserviceModule.v1alpha.PredictionServiceClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new predictionserviceModule.v1alpha.PredictionServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new predictionserviceModule.v1alpha.PredictionServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = predictionserviceModule.v1alpha.PredictionServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new predictionserviceModule.v1alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.predictionServiceStub, undefined); - await client.initialize(); - assert(client.predictionServiceStub); - }); + it('should create a client with no option', () => { + const client = + new predictionserviceModule.v1alpha.PredictionServiceClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new predictionserviceModule.v1alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.predictionServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('should create a client with gRPC fallback', () => { + const client = + new predictionserviceModule.v1alpha.PredictionServiceClient({ + fallback: true, }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new predictionserviceModule.v1alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.predictionServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has initialize method and supports deferred initialization', async () => { + const client = + new predictionserviceModule.v1alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.predictionServiceStub, undefined); + await client.initialize(); + assert(client.predictionServiceStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new predictionserviceModule.v1alpha.PredictionServiceClient({ - 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 close method for the initialized client', (done) => { + const client = + new predictionserviceModule.v1alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new predictionserviceModule.v1alpha.PredictionServiceClient({ - 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); + client.initialize().catch((err) => { + throw err; + }); + assert(client.predictionServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('predict', () => { - it('invokes predict without error', async () => { - const client = new predictionserviceModule.v1alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.PredictRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.PredictRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.PredictResponse() - ); - client.innerApiCalls.predict = stubSimpleCall(expectedResponse); - const [response] = await client.predict(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.predict as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.predict 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 predictionserviceModule.v1alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - it('invokes predict without error using callback', async () => { - const client = new predictionserviceModule.v1alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.PredictRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.PredictRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.PredictResponse() - ); - client.innerApiCalls.predict = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.predict( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IPredictResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.predict as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.predict as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + assert.strictEqual(client.predictionServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes predict with error', async () => { - const client = new predictionserviceModule.v1alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.PredictRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.PredictRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.predict = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.predict(request), expectedError); - const actualRequest = (client.innerApiCalls.predict as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.predict 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 predictionserviceModule.v1alpha.PredictionServiceClient({ + 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 predict with closed client', async () => { - const client = new predictionserviceModule.v1alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.PredictRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.PredictRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.predict(request), expectedError); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new predictionserviceModule.v1alpha.PredictionServiceClient({ + 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('Path templates', () => { - - describe('cachedContent', async () => { - const fakePath = "/rendered/path/cachedContent"; - const expectedParameters = { - id: "idValue", - }; - const client = new predictionserviceModule.v1alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.cachedContentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.cachedContentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('cachedContentPath', () => { - const result = client.cachedContentPath("idValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.cachedContentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchIdFromCachedContentName', () => { - const result = client.matchIdFromCachedContentName(fakePath); - assert.strictEqual(result, "idValue"); - assert((client.pathTemplates.cachedContentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + }); + + describe('predict', () => { + it('invokes predict without error', async () => { + const client = + new predictionserviceModule.v1alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.PredictRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.PredictRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.PredictResponse(), + ); + client.innerApiCalls.predict = stubSimpleCall(expectedResponse); + const [response] = await client.predict(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.predict as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.predict as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('chunk', async () => { - const fakePath = "/rendered/path/chunk"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - chunk: "chunkValue", - }; - const client = new predictionserviceModule.v1alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.chunkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.chunkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('chunkPath', () => { - const result = client.chunkPath("corpusValue", "documentValue", "chunkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.chunkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromChunkName', () => { - const result = client.matchCorpusFromChunkName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromChunkName', () => { - const result = client.matchDocumentFromChunkName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChunkFromChunkName', () => { - const result = client.matchChunkFromChunkName(fakePath); - assert.strictEqual(result, "chunkValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes predict without error using callback', async () => { + const client = + new predictionserviceModule.v1alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.PredictRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.PredictRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.PredictResponse(), + ); + client.innerApiCalls.predict = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.predict( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.IPredictResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.predict as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.predict as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('corpus', async () => { - const fakePath = "/rendered/path/corpus"; - const expectedParameters = { - corpus: "corpusValue", - }; - const client = new predictionserviceModule.v1alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPath', () => { - const result = client.corpusPath("corpusValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusName', () => { - const result = client.matchCorpusFromCorpusName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes predict with error', async () => { + const client = + new predictionserviceModule.v1alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.PredictRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.PredictRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.predict = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.predict(request), expectedError); + const actualRequest = (client.innerApiCalls.predict as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.predict as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('corpusPermissions', async () => { - const fakePath = "/rendered/path/corpusPermissions"; - const expectedParameters = { - corpus: "corpusValue", - permission: "permissionValue", - }; - const client = new predictionserviceModule.v1alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPermissionsPath', () => { - const result = client.corpusPermissionsPath("corpusValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusPermissionsName', () => { - const result = client.matchCorpusFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromCorpusPermissionsName', () => { - const result = client.matchPermissionFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes predict with closed client', async () => { + const client = + new predictionserviceModule.v1alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - - describe('document', async () => { - const fakePath = "/rendered/path/document"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - }; - const client = new predictionserviceModule.v1alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.documentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.documentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('documentPath', () => { - const result = client.documentPath("corpusValue", "documentValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.documentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromDocumentName', () => { - const result = client.matchCorpusFromDocumentName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromDocumentName', () => { - const result = client.matchDocumentFromDocumentName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.PredictRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.PredictRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.predict(request), expectedError); + }); + }); + + describe('Path templates', () => { + describe('cachedContent', async () => { + const fakePath = '/rendered/path/cachedContent'; + const expectedParameters = { + id: 'idValue', + }; + const client = + new predictionserviceModule.v1alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.cachedContentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.cachedContentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('cachedContentPath', () => { + const result = client.cachedContentPath('idValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.cachedContentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchIdFromCachedContentName', () => { + const result = client.matchIdFromCachedContentName(fakePath); + assert.strictEqual(result, 'idValue'); + assert( + (client.pathTemplates.cachedContentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('file', async () => { - const fakePath = "/rendered/path/file"; - const expectedParameters = { - file: "fileValue", - }; - const client = new predictionserviceModule.v1alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.filePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.filePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('filePath', () => { - const result = client.filePath("fileValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.filePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFileFromFileName', () => { - const result = client.matchFileFromFileName(fakePath); - assert.strictEqual(result, "fileValue"); - assert((client.pathTemplates.filePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('chunk', async () => { + const fakePath = '/rendered/path/chunk'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + chunk: 'chunkValue', + }; + const client = + new predictionserviceModule.v1alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.chunkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.chunkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('chunkPath', () => { + const result = client.chunkPath( + 'corpusValue', + 'documentValue', + 'chunkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.chunkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromChunkName', () => { + const result = client.matchCorpusFromChunkName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromChunkName', () => { + const result = client.matchDocumentFromChunkName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChunkFromChunkName', () => { + const result = client.matchChunkFromChunkName(fakePath); + assert.strictEqual(result, 'chunkValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new predictionserviceModule.v1alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('corpus', async () => { + const fakePath = '/rendered/path/corpus'; + const expectedParameters = { + corpus: 'corpusValue', + }; + const client = + new predictionserviceModule.v1alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPath', () => { + const result = client.corpusPath('corpusValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.corpusPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusName', () => { + const result = client.matchCorpusFromCorpusName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.corpusPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('corpusPermissions', async () => { + const fakePath = '/rendered/path/corpusPermissions'; + const expectedParameters = { + corpus: 'corpusValue', + permission: 'permissionValue', + }; + const client = + new predictionserviceModule.v1alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.corpusPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPermissionsPath', () => { + const result = client.corpusPermissionsPath( + 'corpusValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusPermissionsName', () => { + const result = client.matchCorpusFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromCorpusPermissionsName', () => { + const result = + client.matchPermissionFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModel', async () => { - const fakePath = "/rendered/path/tunedModel"; - const expectedParameters = { - tuned_model: "tunedModelValue", - }; - const client = new predictionserviceModule.v1alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPath', () => { - const result = client.tunedModelPath("tunedModelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('document', async () => { + const fakePath = '/rendered/path/document'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + }; + const client = + new predictionserviceModule.v1alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.documentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.documentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('documentPath', () => { + const result = client.documentPath('corpusValue', 'documentValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.documentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromDocumentName', () => { + const result = client.matchCorpusFromDocumentName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromDocumentName', () => { + const result = client.matchDocumentFromDocumentName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchTunedModelFromTunedModelName', () => { - const result = client.matchTunedModelFromTunedModelName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('file', async () => { + const fakePath = '/rendered/path/file'; + const expectedParameters = { + file: 'fileValue', + }; + const client = + new predictionserviceModule.v1alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.filePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.filePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('filePath', () => { + const result = client.filePath('fileValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.filePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFileFromFileName', () => { + const result = client.matchFileFromFileName(fakePath); + assert.strictEqual(result, 'fileValue'); + assert( + (client.pathTemplates.filePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModelPermissions', async () => { - const fakePath = "/rendered/path/tunedModelPermissions"; - const expectedParameters = { - tuned_model: "tunedModelValue", - permission: "permissionValue", - }; - const client = new predictionserviceModule.v1alpha.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPermissionsPath', () => { - const result = client.tunedModelPermissionsPath("tunedModelValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = + new predictionserviceModule.v1alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchTunedModelFromTunedModelPermissionsName', () => { - const result = client.matchTunedModelFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('tunedModel', async () => { + const fakePath = '/rendered/path/tunedModel'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + }; + const client = + new predictionserviceModule.v1alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPath', () => { + const result = client.tunedModelPath('tunedModelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.tunedModelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelName', () => { + const result = client.matchTunedModelFromTunedModelName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.tunedModelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchPermissionFromTunedModelPermissionsName', () => { - const result = client.matchPermissionFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('tunedModelPermissions', async () => { + const fakePath = '/rendered/path/tunedModelPermissions'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + permission: 'permissionValue', + }; + const client = + new predictionserviceModule.v1alpha.PredictionServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + await client.initialize(); + client.pathTemplates.tunedModelPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPermissionsPath', () => { + const result = client.tunedModelPermissionsPath( + 'tunedModelValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelPermissionsName', () => { + const result = + client.matchTunedModelFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromTunedModelPermissionsName', () => { + const result = + client.matchPermissionFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_prediction_service_v1beta.ts b/packages/google-ai-generativelanguage/test/gapic_prediction_service_v1beta.ts index 680ae21d1a74..082d08d67568 100644 --- a/packages/google-ai-generativelanguage/test/gapic_prediction_service_v1beta.ts +++ b/packages/google-ai-generativelanguage/test/gapic_prediction_service_v1beta.ts @@ -19,1062 +19,1441 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as predictionserviceModule from '../src'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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 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('v1beta.PredictionServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new predictionserviceModule.v1beta.PredictionServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new predictionserviceModule.v1beta.PredictionServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new predictionserviceModule.v1beta.PredictionServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.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 = predictionserviceModule.v1beta.PredictionServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + it('has universeDomain', () => { + const client = + new predictionserviceModule.v1beta.PredictionServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = predictionserviceModule.v1beta.PredictionServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new predictionserviceModule.v1beta.PredictionServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 = + predictionserviceModule.v1beta.PredictionServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + predictionserviceModule.v1beta.PredictionServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { universeDomain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new predictionserviceModule.v1beta.PredictionServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { universe_domain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.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 predictionserviceModule.v1beta.PredictionServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 predictionserviceModule.v1beta.PredictionServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 predictionserviceModule.v1beta.PredictionServiceClient({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 predictionserviceModule.v1beta.PredictionServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = predictionserviceModule.v1beta.PredictionServiceClient.port; - assert(port); - assert(typeof port === 'number'); + 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 predictionserviceModule.v1beta.PredictionServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new predictionserviceModule.v1beta.PredictionServiceClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new predictionserviceModule.v1beta.PredictionServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = predictionserviceModule.v1beta.PredictionServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.predictionServiceStub, undefined); - await client.initialize(); - assert(client.predictionServiceStub); - }); + it('should create a client with no option', () => { + const client = + new predictionserviceModule.v1beta.PredictionServiceClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.predictionServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + fallback: true, + }, + ); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.predictionServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.predictionServiceStub, undefined); + await client.initialize(); + assert(client.predictionServiceStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - 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 close method for the initialized client', (done) => { + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + assert(client.predictionServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - 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('has close method for the non-initialized client', (done) => { + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.predictionServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('predict', () => { - it('invokes predict without error', async () => { - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.PredictRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.PredictRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.PredictResponse() - ); - client.innerApiCalls.predict = stubSimpleCall(expectedResponse); - const [response] = await client.predict(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.predict as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.predict 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 predictionserviceModule.v1beta.PredictionServiceClient( + { + 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 predict without error using callback', async () => { - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.PredictRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.PredictRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.PredictResponse() - ); - client.innerApiCalls.predict = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.predict( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IPredictResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.predict as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.predict as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes predict with error', async () => { - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.PredictRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.PredictRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.predict = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.predict(request), expectedError); - const actualRequest = (client.innerApiCalls.predict as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.predict 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 predictionserviceModule.v1beta.PredictionServiceClient( + { + 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('predict', () => { + it('invokes predict without error', async () => { + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.PredictRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.PredictRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.PredictResponse(), + ); + client.innerApiCalls.predict = stubSimpleCall(expectedResponse); + const [response] = await client.predict(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.predict as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.predict as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes predict with closed client', async () => { - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.PredictRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.PredictRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.predict(request), expectedError); - }); + it('invokes predict without error using callback', async () => { + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.PredictRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.PredictRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.PredictResponse(), + ); + client.innerApiCalls.predict = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.predict( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IPredictResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.predict as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.predict as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('predictLongRunning', () => { - it('invokes predictLongRunning without error', async () => { - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.PredictLongRunningRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.PredictLongRunningRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.predictLongRunning = stubLongRunningCall(expectedResponse); - const [operation] = await client.predictLongRunning(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.predictLongRunning as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.predictLongRunning as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes predict with error', async () => { + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.PredictRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.PredictRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.predict = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.predict(request), expectedError); + const actualRequest = (client.innerApiCalls.predict as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.predict as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes predictLongRunning without error using callback', async () => { - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.PredictLongRunningRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.PredictLongRunningRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.predictLongRunning = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.predictLongRunning( - 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.predictLongRunning as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.predictLongRunning as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes predict with closed client', async () => { + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.PredictRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.PredictRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.predict(request), expectedError); + }); + }); + + describe('predictLongRunning', () => { + it('invokes predictLongRunning without error', async () => { + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.PredictLongRunningRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.PredictLongRunningRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.predictLongRunning = + stubLongRunningCall(expectedResponse); + const [operation] = await client.predictLongRunning(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.predictLongRunning as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.predictLongRunning as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes predictLongRunning with call error', async () => { - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.PredictLongRunningRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.PredictLongRunningRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.predictLongRunning = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.predictLongRunning(request), expectedError); - const actualRequest = (client.innerApiCalls.predictLongRunning as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.predictLongRunning as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes predictLongRunning without error using callback', async () => { + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.PredictLongRunningRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.PredictLongRunningRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.predictLongRunning = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.predictLongRunning( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.ai.generativelanguage.v1beta.IPredictLongRunningResponse, + protos.google.ai.generativelanguage.v1beta.IPredictLongRunningMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.ai.generativelanguage.v1beta.IPredictLongRunningResponse, + protos.google.ai.generativelanguage.v1beta.IPredictLongRunningMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.predictLongRunning as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.predictLongRunning as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes predictLongRunning with LRO error', async () => { - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.PredictLongRunningRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.PredictLongRunningRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.predictLongRunning = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.predictLongRunning(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.predictLongRunning as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.predictLongRunning as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes predictLongRunning with call error', async () => { + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.PredictLongRunningRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.PredictLongRunningRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.predictLongRunning = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.predictLongRunning(request), expectedError); + const actualRequest = ( + client.innerApiCalls.predictLongRunning as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.predictLongRunning as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkPredictLongRunningProgress without error', async () => { - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - 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.checkPredictLongRunningProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes predictLongRunning with LRO error', async () => { + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.PredictLongRunningRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.PredictLongRunningRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.predictLongRunning = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.predictLongRunning(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.predictLongRunning as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.predictLongRunning as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkPredictLongRunningProgress with error', async () => { - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); + it('invokes checkPredictLongRunningProgress without error', async () => { + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + 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.checkPredictLongRunningProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkPredictLongRunningProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes checkPredictLongRunningProgress with error', async () => { + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + 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.checkPredictLongRunningProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); }); - describe('getOperation', () => { - it('invokes getOperation without error', async () => { - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - 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 predictionserviceModule.v1beta.PredictionServiceClient({ - 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 predictionserviceModule.v1beta.PredictionServiceClient({ - 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('getOperation', () => { + it('invokes getOperation without error', async () => { + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + 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('cancelOperation', () => { - it('invokes cancelOperation without error', async () => { - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - 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 predictionserviceModule.v1beta.PredictionServiceClient({ - 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 predictionserviceModule.v1beta.PredictionServiceClient({ - 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)); - }); + it('invokes getOperation without error using callback', async () => { + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + 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)); }); - describe('deleteOperation', () => { - it('invokes deleteOperation without error', async () => { - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - 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 predictionserviceModule.v1beta.PredictionServiceClient({ - 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 predictionserviceModule.v1beta.PredictionServiceClient({ - 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 getOperation with error', async () => { + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + 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('listOperationsAsync', () => { - it('uses async iteration with listOperations without error', async () => { - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - 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 predictionserviceModule.v1beta.PredictionServiceClient({ - 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('cancelOperation', () => { + it('invokes cancelOperation without error', async () => { + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + 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 predictionserviceModule.v1beta.PredictionServiceClient( + { + 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 predictionserviceModule.v1beta.PredictionServiceClient( + { + 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 predictionserviceModule.v1beta.PredictionServiceClient( + { + 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 predictionserviceModule.v1beta.PredictionServiceClient( + { + 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 predictionserviceModule.v1beta.PredictionServiceClient( + { + 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 predictionserviceModule.v1beta.PredictionServiceClient( + { + 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 predictionserviceModule.v1beta.PredictionServiceClient( + { + 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('cachedContent', async () => { + const fakePath = '/rendered/path/cachedContent'; + const expectedParameters = { + id: 'idValue', + }; + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.cachedContentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.cachedContentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('cachedContentPath', () => { + const result = client.cachedContentPath('idValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.cachedContentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchIdFromCachedContentName', () => { + const result = client.matchIdFromCachedContentName(fakePath); + assert.strictEqual(result, 'idValue'); + assert( + (client.pathTemplates.cachedContentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); - describe('Path templates', () => { - - describe('cachedContent', async () => { - const fakePath = "/rendered/path/cachedContent"; - const expectedParameters = { - id: "idValue", - }; - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.cachedContentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.cachedContentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('cachedContentPath', () => { - const result = client.cachedContentPath("idValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.cachedContentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchIdFromCachedContentName', () => { - const result = client.matchIdFromCachedContentName(fakePath); - assert.strictEqual(result, "idValue"); - assert((client.pathTemplates.cachedContentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('chunk', async () => { - const fakePath = "/rendered/path/chunk"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - chunk: "chunkValue", - }; - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.chunkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.chunkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('chunkPath', () => { - const result = client.chunkPath("corpusValue", "documentValue", "chunkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.chunkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromChunkName', () => { - const result = client.matchCorpusFromChunkName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromChunkName', () => { - const result = client.matchDocumentFromChunkName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChunkFromChunkName', () => { - const result = client.matchChunkFromChunkName(fakePath); - assert.strictEqual(result, "chunkValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('corpus', async () => { - const fakePath = "/rendered/path/corpus"; - const expectedParameters = { - corpus: "corpusValue", - }; - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPath', () => { - const result = client.corpusPath("corpusValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusName', () => { - const result = client.matchCorpusFromCorpusName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('corpusPermissions', async () => { - const fakePath = "/rendered/path/corpusPermissions"; - const expectedParameters = { - corpus: "corpusValue", - permission: "permissionValue", - }; - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPermissionsPath', () => { - const result = client.corpusPermissionsPath("corpusValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusPermissionsName', () => { - const result = client.matchCorpusFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromCorpusPermissionsName', () => { - const result = client.matchPermissionFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('document', async () => { - const fakePath = "/rendered/path/document"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - }; - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.documentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.documentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('documentPath', () => { - const result = client.documentPath("corpusValue", "documentValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.documentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromDocumentName', () => { - const result = client.matchCorpusFromDocumentName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromDocumentName', () => { - const result = client.matchDocumentFromDocumentName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('file', async () => { - const fakePath = "/rendered/path/file"; - const expectedParameters = { - file: "fileValue", - }; - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.filePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.filePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('filePath', () => { - const result = client.filePath("fileValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.filePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFileFromFileName', () => { - const result = client.matchFileFromFileName(fakePath); - assert.strictEqual(result, "fileValue"); - assert((client.pathTemplates.filePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('chunk', async () => { + const fakePath = '/rendered/path/chunk'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + chunk: 'chunkValue', + }; + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.chunkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.chunkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('chunkPath', () => { + const result = client.chunkPath( + 'corpusValue', + 'documentValue', + 'chunkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.chunkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromChunkName', () => { + const result = client.matchCorpusFromChunkName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromChunkName', () => { + const result = client.matchDocumentFromChunkName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChunkFromChunkName', () => { + const result = client.matchChunkFromChunkName(fakePath); + assert.strictEqual(result, 'chunkValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('corpus', async () => { + const fakePath = '/rendered/path/corpus'; + const expectedParameters = { + corpus: 'corpusValue', + }; + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.corpusPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPath', () => { + const result = client.corpusPath('corpusValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.corpusPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusName', () => { + const result = client.matchCorpusFromCorpusName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.corpusPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpusPermissions', async () => { + const fakePath = '/rendered/path/corpusPermissions'; + const expectedParameters = { + corpus: 'corpusValue', + permission: 'permissionValue', + }; + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.corpusPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPermissionsPath', () => { + const result = client.corpusPermissionsPath( + 'corpusValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusPermissionsName', () => { + const result = client.matchCorpusFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromCorpusPermissionsName', () => { + const result = + client.matchPermissionFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModel', async () => { - const fakePath = "/rendered/path/tunedModel"; - const expectedParameters = { - tuned_model: "tunedModelValue", - }; - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPath', () => { - const result = client.tunedModelPath("tunedModelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('document', async () => { + const fakePath = '/rendered/path/document'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + }; + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.documentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.documentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('documentPath', () => { + const result = client.documentPath('corpusValue', 'documentValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.documentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromDocumentName', () => { + const result = client.matchCorpusFromDocumentName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromDocumentName', () => { + const result = client.matchDocumentFromDocumentName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchTunedModelFromTunedModelName', () => { - const result = client.matchTunedModelFromTunedModelName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('file', async () => { + const fakePath = '/rendered/path/file'; + const expectedParameters = { + file: 'fileValue', + }; + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.filePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.filePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('filePath', () => { + const result = client.filePath('fileValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.filePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFileFromFileName', () => { + const result = client.matchFileFromFileName(fakePath); + assert.strictEqual(result, 'fileValue'); + assert( + (client.pathTemplates.filePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModelPermissions', async () => { - const fakePath = "/rendered/path/tunedModelPermissions"; - const expectedParameters = { - tuned_model: "tunedModelValue", - permission: "permissionValue", - }; - const client = new predictionserviceModule.v1beta.PredictionServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPermissionsPath', () => { - const result = client.tunedModelPermissionsPath("tunedModelValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchTunedModelFromTunedModelPermissionsName', () => { - const result = client.matchTunedModelFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('tunedModel', async () => { + const fakePath = '/rendered/path/tunedModel'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + }; + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.tunedModelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPath', () => { + const result = client.tunedModelPath('tunedModelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.tunedModelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelName', () => { + const result = client.matchTunedModelFromTunedModelName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.tunedModelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchPermissionFromTunedModelPermissionsName', () => { - const result = client.matchPermissionFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModelPermissions', async () => { + const fakePath = '/rendered/path/tunedModelPermissions'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + permission: 'permissionValue', + }; + const client = new predictionserviceModule.v1beta.PredictionServiceClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.tunedModelPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPermissionsPath', () => { + const result = client.tunedModelPermissionsPath( + 'tunedModelValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelPermissionsName', () => { + const result = + client.matchTunedModelFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromTunedModelPermissionsName', () => { + const result = + client.matchPermissionFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_retriever_service_v1alpha.ts b/packages/google-ai-generativelanguage/test/gapic_retriever_service_v1alpha.ts index 9573c55d0ac5..3d37b4727c77 100644 --- a/packages/google-ai-generativelanguage/test/gapic_retriever_service_v1alpha.ts +++ b/packages/google-ai-generativelanguage/test/gapic_retriever_service_v1alpha.ts @@ -19,3036 +19,3849 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as retrieverserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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 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('v1alpha.RetrieverServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient(); - 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 = retrieverserviceModule.v1alpha.RetrieverServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = retrieverserviceModule.v1alpha.RetrieverServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 retrieverserviceModule.v1alpha.RetrieverServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 retrieverserviceModule.v1alpha.RetrieverServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 retrieverserviceModule.v1alpha.RetrieverServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = retrieverserviceModule.v1alpha.RetrieverServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.retrieverServiceStub, undefined); - await client.initialize(); - assert(client.retrieverServiceStub); - }); - - it('has close method for the initialized client', done => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.retrieverServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.retrieverServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - 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 retrieverserviceModule.v1alpha.RetrieverServiceClient({ - 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 retrieverserviceModule.v1alpha.RetrieverServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); }); - describe('createCorpus', () => { - it('invokes createCorpus without error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateCorpusRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.Corpus() - ); - client.innerApiCalls.createCorpus = stubSimpleCall(expectedResponse); - const [response] = await client.createCorpus(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes createCorpus without error using callback', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateCorpusRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.Corpus() - ); - client.innerApiCalls.createCorpus = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createCorpus( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.ICorpus|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes createCorpus with error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateCorpusRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createCorpus = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createCorpus(request), expectedError); - }); - - it('invokes createCorpus with closed client', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateCorpusRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createCorpus(request), expectedError); - }); + it('has universeDomain', () => { + const client = + new retrieverserviceModule.v1alpha.RetrieverServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); }); - describe('getCorpus', () => { - it('invokes getCorpus without error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.Corpus() - ); - client.innerApiCalls.getCorpus = stubSimpleCall(expectedResponse); - const [response] = await client.getCorpus(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCorpus without error using callback', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.Corpus() - ); - client.innerApiCalls.getCorpus = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getCorpus( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.ICorpus|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCorpus with error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getCorpus = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getCorpus(request), expectedError); - const actualRequest = (client.innerApiCalls.getCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCorpus with closed client', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getCorpus(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 = + retrieverserviceModule.v1alpha.RetrieverServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + retrieverserviceModule.v1alpha.RetrieverServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); }); - describe('updateCorpus', () => { - it('invokes updateCorpus without error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdateCorpusRequest() - ); - request.corpus ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.UpdateCorpusRequest', ['corpus', 'name']); - request.corpus.name = defaultValue1; - const expectedHeaderRequestParams = `corpus.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.Corpus() - ); - client.innerApiCalls.updateCorpus = stubSimpleCall(expectedResponse); - const [response] = await client.updateCorpus(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCorpus without error using callback', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdateCorpusRequest() - ); - request.corpus ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.UpdateCorpusRequest', ['corpus', 'name']); - request.corpus.name = defaultValue1; - const expectedHeaderRequestParams = `corpus.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.Corpus() - ); - client.innerApiCalls.updateCorpus = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateCorpus( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.ICorpus|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCorpus with error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdateCorpusRequest() - ); - request.corpus ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.UpdateCorpusRequest', ['corpus', 'name']); - request.corpus.name = defaultValue1; - const expectedHeaderRequestParams = `corpus.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateCorpus = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateCorpus(request), expectedError); - const actualRequest = (client.innerApiCalls.updateCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCorpus with closed client', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdateCorpusRequest() - ); - request.corpus ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.UpdateCorpusRequest', ['corpus', 'name']); - request.corpus.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateCorpus(request), expectedError); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); }); - describe('deleteCorpus', () => { - it('invokes deleteCorpus without error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeleteCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteCorpus = stubSimpleCall(expectedResponse); - const [response] = await client.deleteCorpus(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteCorpus without error using callback', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeleteCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteCorpus = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteCorpus( - 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.deleteCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteCorpus with error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeleteCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteCorpus = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteCorpus(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteCorpus with closed client', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeleteCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteCorpus(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 retrieverserviceModule.v1alpha.RetrieverServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.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 retrieverserviceModule.v1alpha.RetrieverServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.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 retrieverserviceModule.v1alpha.RetrieverServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('queryCorpus', () => { - it('invokes queryCorpus without error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.QueryCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.QueryCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.QueryCorpusResponse() - ); - client.innerApiCalls.queryCorpus = stubSimpleCall(expectedResponse); - const [response] = await client.queryCorpus(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.queryCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.queryCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes queryCorpus without error using callback', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.QueryCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.QueryCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.QueryCorpusResponse() - ); - client.innerApiCalls.queryCorpus = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.queryCorpus( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IQueryCorpusResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.queryCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.queryCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes queryCorpus with error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.QueryCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.QueryCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.queryCorpus = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.queryCorpus(request), expectedError); - const actualRequest = (client.innerApiCalls.queryCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.queryCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes queryCorpus with closed client', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.QueryCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.QueryCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.queryCorpus(request), expectedError); - }); + it('has port', () => { + const port = retrieverserviceModule.v1alpha.RetrieverServiceClient.port; + assert(port); + assert(typeof port === 'number'); }); - describe('createDocument', () => { - it('invokes createDocument without error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CreateDocumentRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.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 createDocument without error using callback', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CreateDocumentRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.Document() - ); - client.innerApiCalls.createDocument = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createDocument( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.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 createDocument with error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CreateDocumentRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - 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 createDocument with closed client', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CreateDocumentRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createDocument(request), expectedError); - }); + it('should create a client with no option', () => { + const client = + new retrieverserviceModule.v1alpha.RetrieverServiceClient(); + assert(client); }); - describe('getDocument', () => { - it('invokes getDocument without error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetDocumentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.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 retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetDocumentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.Document() - ); - client.innerApiCalls.getDocument = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getDocument( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.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 error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.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 with closed client', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.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('should create a client with gRPC fallback', () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + fallback: true, + }); + assert(client); }); - describe('updateDocument', () => { - it('invokes updateDocument without error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdateDocumentRequest() - ); - request.document ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.UpdateDocumentRequest', ['document', 'name']); - request.document.name = defaultValue1; - const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.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 without error using callback', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdateDocumentRequest() - ); - request.document ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.UpdateDocumentRequest', ['document', 'name']); - request.document.name = defaultValue1; - const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.Document() - ); - client.innerApiCalls.updateDocument = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateDocument( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.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 initialize method and supports deferred initialization', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.retrieverServiceStub, undefined); + await client.initialize(); + assert(client.retrieverServiceStub); + }); - it('invokes updateDocument with error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdateDocumentRequest() - ); - request.document ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.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('has close method for the initialized client', (done) => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.retrieverServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes updateDocument with closed client', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdateDocumentRequest() - ); - request.document ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.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('has close method for the non-initialized client', (done) => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.retrieverServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('deleteDocument', () => { - it('invokes deleteDocument without error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.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 getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + 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 deleteDocument without error using callback', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.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 getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + 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('createCorpus', () => { + it('invokes createCorpus without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateCorpusRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Corpus(), + ); + client.innerApiCalls.createCorpus = stubSimpleCall(expectedResponse); + const [response] = await client.createCorpus(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes deleteDocument with error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.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 createCorpus without error using callback', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateCorpusRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Corpus(), + ); + client.innerApiCalls.createCorpus = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createCorpus( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.ICorpus | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes deleteDocument with closed client', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.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 createCorpus with error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateCorpusRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createCorpus = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createCorpus(request), expectedError); }); - describe('queryDocument', () => { - it('invokes queryDocument without error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.QueryDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.QueryDocumentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.QueryDocumentResponse() - ); - client.innerApiCalls.queryDocument = stubSimpleCall(expectedResponse); - const [response] = await client.queryDocument(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.queryDocument as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.queryDocument as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createCorpus with closed client', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateCorpusRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createCorpus(request), expectedError); + }); + }); + + describe('getCorpus', () => { + it('invokes getCorpus without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Corpus(), + ); + client.innerApiCalls.getCorpus = stubSimpleCall(expectedResponse); + const [response] = await client.getCorpus(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes queryDocument without error using callback', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.QueryDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.QueryDocumentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.QueryDocumentResponse() - ); - client.innerApiCalls.queryDocument = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.queryDocument( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IQueryDocumentResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.queryDocument as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.queryDocument as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getCorpus without error using callback', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Corpus(), + ); + client.innerApiCalls.getCorpus = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getCorpus( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.ICorpus | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes queryDocument with error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.QueryDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.QueryDocumentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.queryDocument = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.queryDocument(request), expectedError); - const actualRequest = (client.innerApiCalls.queryDocument as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.queryDocument as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getCorpus with error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getCorpus = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getCorpus(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes queryDocument with closed client', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.QueryDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.QueryDocumentRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.queryDocument(request), expectedError); - }); + it('invokes getCorpus with closed client', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getCorpus(request), expectedError); + }); + }); + + describe('updateCorpus', () => { + it('invokes updateCorpus without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdateCorpusRequest(), + ); + request.corpus ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.UpdateCorpusRequest', + ['corpus', 'name'], + ); + request.corpus.name = defaultValue1; + const expectedHeaderRequestParams = `corpus.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Corpus(), + ); + client.innerApiCalls.updateCorpus = stubSimpleCall(expectedResponse); + const [response] = await client.updateCorpus(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createChunk', () => { - it('invokes createChunk without error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CreateChunkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.Chunk() - ); - client.innerApiCalls.createChunk = stubSimpleCall(expectedResponse); - const [response] = await client.createChunk(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createChunk as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateCorpus without error using callback', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdateCorpusRequest(), + ); + request.corpus ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.UpdateCorpusRequest', + ['corpus', 'name'], + ); + request.corpus.name = defaultValue1; + const expectedHeaderRequestParams = `corpus.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Corpus(), + ); + client.innerApiCalls.updateCorpus = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateCorpus( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.ICorpus | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createChunk without error using callback', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CreateChunkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.Chunk() - ); - client.innerApiCalls.createChunk = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createChunk( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IChunk|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createChunk as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateCorpus with error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdateCorpusRequest(), + ); + request.corpus ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.UpdateCorpusRequest', + ['corpus', 'name'], + ); + request.corpus.name = defaultValue1; + const expectedHeaderRequestParams = `corpus.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateCorpus = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateCorpus(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createChunk with error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CreateChunkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createChunk = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createChunk(request), expectedError); - const actualRequest = (client.innerApiCalls.createChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createChunk as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateCorpus with closed client', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdateCorpusRequest(), + ); + request.corpus ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.UpdateCorpusRequest', + ['corpus', 'name'], + ); + request.corpus.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateCorpus(request), expectedError); + }); + }); + + describe('deleteCorpus', () => { + it('invokes deleteCorpus without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeleteCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteCorpus = stubSimpleCall(expectedResponse); + const [response] = await client.deleteCorpus(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createChunk with closed client', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CreateChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CreateChunkRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createChunk(request), expectedError); - }); + it('invokes deleteCorpus without error using callback', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeleteCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteCorpus = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteCorpus( + 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.deleteCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('batchCreateChunks', () => { - it('invokes batchCreateChunks without error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchCreateChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.BatchCreateChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchCreateChunksResponse() - ); - client.innerApiCalls.batchCreateChunks = stubSimpleCall(expectedResponse); - const [response] = await client.batchCreateChunks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchCreateChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchCreateChunks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteCorpus with error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeleteCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteCorpus = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteCorpus(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchCreateChunks without error using callback', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchCreateChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.BatchCreateChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchCreateChunksResponse() - ); - client.innerApiCalls.batchCreateChunks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchCreateChunks( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchCreateChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchCreateChunks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteCorpus with closed client', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeleteCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteCorpus(request), expectedError); + }); + }); + + describe('queryCorpus', () => { + it('invokes queryCorpus without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.QueryCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.QueryCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.QueryCorpusResponse(), + ); + client.innerApiCalls.queryCorpus = stubSimpleCall(expectedResponse); + const [response] = await client.queryCorpus(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.queryCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.queryCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchCreateChunks with error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchCreateChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.BatchCreateChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchCreateChunks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchCreateChunks(request), expectedError); - const actualRequest = (client.innerApiCalls.batchCreateChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchCreateChunks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes queryCorpus without error using callback', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.QueryCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.QueryCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.QueryCorpusResponse(), + ); + client.innerApiCalls.queryCorpus = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.queryCorpus( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.IQueryCorpusResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.queryCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.queryCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchCreateChunks with closed client', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchCreateChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.BatchCreateChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchCreateChunks(request), expectedError); - }); + it('invokes queryCorpus with error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.QueryCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.QueryCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.queryCorpus = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.queryCorpus(request), expectedError); + const actualRequest = ( + client.innerApiCalls.queryCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.queryCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getChunk', () => { - it('invokes getChunk without error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetChunkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.Chunk() - ); - client.innerApiCalls.getChunk = stubSimpleCall(expectedResponse); - const [response] = await client.getChunk(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getChunk as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes queryCorpus with closed client', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.QueryCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.QueryCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.queryCorpus(request), expectedError); + }); + }); + + describe('createDocument', () => { + it('invokes createDocument without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CreateDocumentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.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 getChunk without error using callback', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetChunkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.Chunk() - ); - client.innerApiCalls.getChunk = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getChunk( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IChunk|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getChunk 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 retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CreateDocumentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Document(), + ); + client.innerApiCalls.createDocument = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createDocument( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.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 getChunk with error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetChunkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getChunk = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getChunk(request), expectedError); - const actualRequest = (client.innerApiCalls.getChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getChunk 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 retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CreateDocumentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + 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 getChunk with closed client', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GetChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GetChunkRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getChunk(request), expectedError); - }); + it('invokes createDocument with closed client', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CreateDocumentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createDocument(request), expectedError); + }); + }); + + describe('getDocument', () => { + it('invokes getDocument without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.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)); }); - describe('updateChunk', () => { - it('invokes updateChunk without error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdateChunkRequest() - ); - request.chunk ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.UpdateChunkRequest', ['chunk', 'name']); - request.chunk.name = defaultValue1; - const expectedHeaderRequestParams = `chunk.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.Chunk() - ); - client.innerApiCalls.updateChunk = stubSimpleCall(expectedResponse); - const [response] = await client.updateChunk(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateChunk 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 retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Document(), + ); + client.innerApiCalls.getDocument = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDocument( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.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 updateChunk without error using callback', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdateChunkRequest() - ); - request.chunk ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.UpdateChunkRequest', ['chunk', 'name']); - request.chunk.name = defaultValue1; - const expectedHeaderRequestParams = `chunk.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.Chunk() - ); - client.innerApiCalls.updateChunk = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateChunk( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IChunk|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateChunk 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 retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.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 updateChunk with error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdateChunkRequest() - ); - request.chunk ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.UpdateChunkRequest', ['chunk', 'name']); - request.chunk.name = defaultValue1; - const expectedHeaderRequestParams = `chunk.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateChunk = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateChunk(request), expectedError); - const actualRequest = (client.innerApiCalls.updateChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateChunk 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 retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.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 retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdateDocumentRequest(), + ); + request.document ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.UpdateDocumentRequest', + ['document', 'name'], + ); + request.document.name = defaultValue1; + const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.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 updateChunk with closed client', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.UpdateChunkRequest() - ); - request.chunk ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.UpdateChunkRequest', ['chunk', 'name']); - request.chunk.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateChunk(request), expectedError); - }); + it('invokes updateDocument without error using callback', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdateDocumentRequest(), + ); + request.document ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.UpdateDocumentRequest', + ['document', 'name'], + ); + request.document.name = defaultValue1; + const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Document(), + ); + client.innerApiCalls.updateDocument = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateDocument( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.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)); }); - describe('batchUpdateChunks', () => { - it('invokes batchUpdateChunks without error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchUpdateChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.BatchUpdateChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchUpdateChunksResponse() - ); - client.innerApiCalls.batchUpdateChunks = stubSimpleCall(expectedResponse); - const [response] = await client.batchUpdateChunks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchUpdateChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchUpdateChunks 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 retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdateDocumentRequest(), + ); + request.document ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.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 batchUpdateChunks without error using callback', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchUpdateChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.BatchUpdateChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchUpdateChunksResponse() - ); - client.innerApiCalls.batchUpdateChunks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchUpdateChunks( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchUpdateChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchUpdateChunks 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 retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdateDocumentRequest(), + ); + request.document ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.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 retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.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 batchUpdateChunks with error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchUpdateChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.BatchUpdateChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchUpdateChunks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchUpdateChunks(request), expectedError); - const actualRequest = (client.innerApiCalls.batchUpdateChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchUpdateChunks 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 retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.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 batchUpdateChunks with closed client', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchUpdateChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.BatchUpdateChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchUpdateChunks(request), expectedError); - }); + it('invokes deleteDocument with error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.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)); }); - describe('deleteChunk', () => { - it('invokes deleteChunk without error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeleteChunkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteChunk = stubSimpleCall(expectedResponse); - const [response] = await client.deleteChunk(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteChunk 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 retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.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('queryDocument', () => { + it('invokes queryDocument without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.QueryDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.QueryDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.QueryDocumentResponse(), + ); + client.innerApiCalls.queryDocument = stubSimpleCall(expectedResponse); + const [response] = await client.queryDocument(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.queryDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.queryDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteChunk without error using callback', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeleteChunkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteChunk = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteChunk( - 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.deleteChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteChunk as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes queryDocument without error using callback', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.QueryDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.QueryDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.QueryDocumentResponse(), + ); + client.innerApiCalls.queryDocument = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.queryDocument( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.IQueryDocumentResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.queryDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.queryDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteChunk with error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeleteChunkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteChunk = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteChunk(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteChunk as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes queryDocument with error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.QueryDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.QueryDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.queryDocument = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.queryDocument(request), expectedError); + const actualRequest = ( + client.innerApiCalls.queryDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.queryDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteChunk with closed client', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.DeleteChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.DeleteChunkRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteChunk(request), expectedError); - }); + it('invokes queryDocument with closed client', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.QueryDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.QueryDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.queryDocument(request), expectedError); + }); + }); + + describe('createChunk', () => { + it('invokes createChunk without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CreateChunkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Chunk(), + ); + client.innerApiCalls.createChunk = stubSimpleCall(expectedResponse); + const [response] = await client.createChunk(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createChunk as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('batchDeleteChunks', () => { - it('invokes batchDeleteChunks without error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchDeleteChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.BatchDeleteChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.batchDeleteChunks = stubSimpleCall(expectedResponse); - const [response] = await client.batchDeleteChunks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchDeleteChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchDeleteChunks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createChunk without error using callback', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CreateChunkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Chunk(), + ); + client.innerApiCalls.createChunk = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createChunk( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.IChunk | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createChunk as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchDeleteChunks without error using callback', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchDeleteChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.BatchDeleteChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.batchDeleteChunks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchDeleteChunks( - 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.batchDeleteChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchDeleteChunks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createChunk with error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CreateChunkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createChunk = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createChunk(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createChunk as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchDeleteChunks with error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchDeleteChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.BatchDeleteChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchDeleteChunks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchDeleteChunks(request), expectedError); - const actualRequest = (client.innerApiCalls.batchDeleteChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchDeleteChunks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createChunk with closed client', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CreateChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CreateChunkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createChunk(request), expectedError); + }); + }); + + describe('batchCreateChunks', () => { + it('invokes batchCreateChunks without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchCreateChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.BatchCreateChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchCreateChunksResponse(), + ); + client.innerApiCalls.batchCreateChunks = stubSimpleCall(expectedResponse); + const [response] = await client.batchCreateChunks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchCreateChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchCreateChunks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchDeleteChunks with closed client', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchDeleteChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.BatchDeleteChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchDeleteChunks(request), expectedError); - }); + it('invokes batchCreateChunks without error using callback', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchCreateChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.BatchCreateChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchCreateChunksResponse(), + ); + client.innerApiCalls.batchCreateChunks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchCreateChunks( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.IBatchCreateChunksResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchCreateChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchCreateChunks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listCorpora', () => { - it('invokes listCorpora without error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListCorporaRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Corpus()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Corpus()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Corpus()), - ]; - client.innerApiCalls.listCorpora = stubSimpleCall(expectedResponse); - const [response] = await client.listCorpora(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes batchCreateChunks with error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchCreateChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.BatchCreateChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchCreateChunks = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.batchCreateChunks(request), expectedError); + const actualRequest = ( + client.innerApiCalls.batchCreateChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchCreateChunks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listCorpora without error using callback', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListCorporaRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Corpus()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Corpus()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Corpus()), - ]; - client.innerApiCalls.listCorpora = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listCorpora( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.ICorpus[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes batchCreateChunks with closed client', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchCreateChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.BatchCreateChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.batchCreateChunks(request), expectedError); + }); + }); + + describe('getChunk', () => { + it('invokes getChunk without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetChunkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Chunk(), + ); + client.innerApiCalls.getChunk = stubSimpleCall(expectedResponse); + const [response] = await client.getChunk(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getChunk as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listCorpora with error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListCorporaRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listCorpora = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listCorpora(request), expectedError); - }); + it('invokes getChunk without error using callback', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetChunkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Chunk(), + ); + client.innerApiCalls.getChunk = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getChunk( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.IChunk | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getChunk as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listCorporaStream without error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListCorporaRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Corpus()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Corpus()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Corpus()), - ]; - client.descriptors.page.listCorpora.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listCorporaStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1alpha.Corpus[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1alpha.Corpus) => { - 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.listCorpora.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCorpora, request)); - }); + it('invokes getChunk with error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetChunkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getChunk = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getChunk(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getChunk as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listCorporaStream with error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListCorporaRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listCorpora.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listCorporaStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1alpha.Corpus[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1alpha.Corpus) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listCorpora.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCorpora, request)); - }); + it('invokes getChunk with closed client', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GetChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GetChunkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getChunk(request), expectedError); + }); + }); + + describe('updateChunk', () => { + it('invokes updateChunk without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdateChunkRequest(), + ); + request.chunk ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.UpdateChunkRequest', + ['chunk', 'name'], + ); + request.chunk.name = defaultValue1; + const expectedHeaderRequestParams = `chunk.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Chunk(), + ); + client.innerApiCalls.updateChunk = stubSimpleCall(expectedResponse); + const [response] = await client.updateChunk(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateChunk as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listCorpora without error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListCorporaRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Corpus()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Corpus()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Corpus()), - ]; - client.descriptors.page.listCorpora.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ai.generativelanguage.v1alpha.ICorpus[] = []; - const iterable = client.listCorporaAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes updateChunk without error using callback', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdateChunkRequest(), + ); + request.chunk ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.UpdateChunkRequest', + ['chunk', 'name'], + ); + request.chunk.name = defaultValue1; + const expectedHeaderRequestParams = `chunk.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Chunk(), + ); + client.innerApiCalls.updateChunk = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateChunk( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.IChunk | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listCorpora.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); - - it('uses async iteration with listCorpora with error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListCorporaRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listCorpora.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listCorporaAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ai.generativelanguage.v1alpha.ICorpus[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listCorpora.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateChunk 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 retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.ListDocumentsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Document()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Document()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.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 updateChunk with error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdateChunkRequest(), + ); + request.chunk ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.UpdateChunkRequest', + ['chunk', 'name'], + ); + request.chunk.name = defaultValue1; + const expectedHeaderRequestParams = `chunk.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateChunk = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateChunk(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateChunk 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 retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.ListDocumentsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Document()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Document()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Document()), - ]; - client.innerApiCalls.listDocuments = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listDocuments( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.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 updateChunk with closed client', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.UpdateChunkRequest(), + ); + request.chunk ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.UpdateChunkRequest', + ['chunk', 'name'], + ); + request.chunk.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateChunk(request), expectedError); + }); + }); + + describe('batchUpdateChunks', () => { + it('invokes batchUpdateChunks without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchUpdateChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.BatchUpdateChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchUpdateChunksResponse(), + ); + client.innerApiCalls.batchUpdateChunks = stubSimpleCall(expectedResponse); + const [response] = await client.batchUpdateChunks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchUpdateChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchUpdateChunks 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 retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.ListDocumentsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - 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 batchUpdateChunks without error using callback', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchUpdateChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.BatchUpdateChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchUpdateChunksResponse(), + ); + client.innerApiCalls.batchUpdateChunks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchUpdateChunks( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.IBatchUpdateChunksResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchUpdateChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchUpdateChunks 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 retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.ListDocumentsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Document()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Document()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Document()), - ]; - client.descriptors.page.listDocuments.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listDocumentsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1alpha.Document[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1alpha.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 batchUpdateChunks with error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchUpdateChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.BatchUpdateChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchUpdateChunks = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.batchUpdateChunks(request), expectedError); + const actualRequest = ( + client.innerApiCalls.batchUpdateChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchUpdateChunks 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 retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.ListDocumentsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - 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.ai.generativelanguage.v1alpha.Document[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1alpha.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 batchUpdateChunks with closed client', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchUpdateChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.BatchUpdateChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.batchUpdateChunks(request), expectedError); + }); + }); + + describe('deleteChunk', () => { + it('invokes deleteChunk without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeleteChunkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteChunk = stubSimpleCall(expectedResponse); + const [response] = await client.deleteChunk(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteChunk 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 retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.ListDocumentsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Document()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Document()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Document()), - ]; - client.descriptors.page.listDocuments.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ai.generativelanguage.v1alpha.IDocument[] = []; - const iterable = client.listDocumentsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes deleteChunk without error using callback', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeleteChunkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteChunk = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteChunk( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | 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 retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.ListDocumentsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - 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.ai.generativelanguage.v1alpha.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.deleteChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteChunk as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listChunks', () => { - it('invokes listChunks without error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.ListChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Chunk()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Chunk()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Chunk()), - ]; - client.innerApiCalls.listChunks = stubSimpleCall(expectedResponse); - const [response] = await client.listChunks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listChunks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteChunk with error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeleteChunkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteChunk = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteChunk(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteChunk as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listChunks without error using callback', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.ListChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Chunk()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Chunk()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Chunk()), - ]; - client.innerApiCalls.listChunks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listChunks( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IChunk[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listChunks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteChunk with closed client', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.DeleteChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.DeleteChunkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteChunk(request), expectedError); + }); + }); + + describe('batchDeleteChunks', () => { + it('invokes batchDeleteChunks without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchDeleteChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.BatchDeleteChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.batchDeleteChunks = stubSimpleCall(expectedResponse); + const [response] = await client.batchDeleteChunks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchDeleteChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchDeleteChunks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listChunks with error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.ListChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listChunks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listChunks(request), expectedError); - const actualRequest = (client.innerApiCalls.listChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listChunks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchDeleteChunks without error using callback', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchDeleteChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.BatchDeleteChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.batchDeleteChunks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchDeleteChunks( + 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.batchDeleteChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchDeleteChunks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listChunksStream without error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.ListChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Chunk()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Chunk()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Chunk()), - ]; - client.descriptors.page.listChunks.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listChunksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1alpha.Chunk[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1alpha.Chunk) => { - 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.listChunks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listChunks, request)); - assert( - (client.descriptors.page.listChunks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes batchDeleteChunks with error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchDeleteChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.BatchDeleteChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchDeleteChunks = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.batchDeleteChunks(request), expectedError); + const actualRequest = ( + client.innerApiCalls.batchDeleteChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchDeleteChunks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listChunksStream with error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.ListChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listChunks.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listChunksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1alpha.Chunk[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1alpha.Chunk) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listChunks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listChunks, request)); - assert( - (client.descriptors.page.listChunks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes batchDeleteChunks with closed client', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchDeleteChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.BatchDeleteChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.batchDeleteChunks(request), expectedError); + }); + }); + + describe('listCorpora', () => { + it('invokes listCorpora without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListCorporaRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Corpus(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Corpus(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Corpus(), + ), + ]; + client.innerApiCalls.listCorpora = stubSimpleCall(expectedResponse); + const [response] = await client.listCorpora(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('uses async iteration with listChunks without error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.ListChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Chunk()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Chunk()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1alpha.Chunk()), - ]; - client.descriptors.page.listChunks.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ai.generativelanguage.v1alpha.IChunk[] = []; - const iterable = client.listChunksAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listCorpora without error using callback', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListCorporaRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Corpus(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Corpus(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Corpus(), + ), + ]; + client.innerApiCalls.listCorpora = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listCorpora( + request, + ( + err?: Error | null, + result?: + | protos.google.ai.generativelanguage.v1alpha.ICorpus[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listChunks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listChunks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('uses async iteration with listChunks with error', async () => { - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.ListChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.ListChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listChunks.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listChunksAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ai.generativelanguage.v1alpha.IChunk[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listChunks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listChunks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listCorpora with error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListCorporaRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listCorpora = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listCorpora(request), expectedError); }); - describe('Path templates', () => { + it('invokes listCorporaStream without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListCorporaRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Corpus(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Corpus(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Corpus(), + ), + ]; + client.descriptors.page.listCorpora.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listCorporaStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1alpha.Corpus[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1alpha.Corpus) => { + 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.listCorpora.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCorpora, request), + ); + }); - describe('cachedContent', async () => { - const fakePath = "/rendered/path/cachedContent"; - const expectedParameters = { - id: "idValue", - }; - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.cachedContentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.cachedContentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('cachedContentPath', () => { - const result = client.cachedContentPath("idValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.cachedContentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes listCorporaStream with error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListCorporaRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listCorpora.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listCorporaStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1alpha.Corpus[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1alpha.Corpus) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listCorpora.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCorpora, request), + ); + }); - it('matchIdFromCachedContentName', () => { - const result = client.matchIdFromCachedContentName(fakePath); - assert.strictEqual(result, "idValue"); - assert((client.pathTemplates.cachedContentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listCorpora without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListCorporaRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Corpus(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Corpus(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Corpus(), + ), + ]; + client.descriptors.page.listCorpora.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ai.generativelanguage.v1alpha.ICorpus[] = + []; + const iterable = client.listCorporaAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listCorpora.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); - describe('chunk', async () => { - const fakePath = "/rendered/path/chunk"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - chunk: "chunkValue", - }; - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.chunkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.chunkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('chunkPath', () => { - const result = client.chunkPath("corpusValue", "documentValue", "chunkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.chunkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('uses async iteration with listCorpora with error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListCorporaRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listCorpora.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listCorporaAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ai.generativelanguage.v1alpha.ICorpus[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listCorpora.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); + }); + + describe('listDocuments', () => { + it('invokes listDocuments without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Document(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Document(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.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('matchCorpusFromChunkName', () => { - const result = client.matchCorpusFromChunkName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listDocuments without error using callback', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Document(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Document(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Document(), + ), + ]; + client.innerApiCalls.listDocuments = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listDocuments( + request, + ( + err?: Error | null, + result?: + | protos.google.ai.generativelanguage.v1alpha.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('matchDocumentFromChunkName', () => { - const result = client.matchDocumentFromChunkName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listDocuments with error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + 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('matchChunkFromChunkName', () => { - const result = client.matchChunkFromChunkName(fakePath); - assert.strictEqual(result, "chunkValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes listDocumentsStream without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Document(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Document(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Document(), + ), + ]; + client.descriptors.page.listDocuments.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listDocumentsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1alpha.Document[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1alpha.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), + ); + }); - describe('corpus', async () => { - const fakePath = "/rendered/path/corpus"; - const expectedParameters = { - corpus: "corpusValue", - }; - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPath', () => { - const result = client.corpusPath("corpusValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes listDocumentsStream with error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + 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.ai.generativelanguage.v1alpha.Document[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1alpha.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('matchCorpusFromCorpusName', () => { - const result = client.matchCorpusFromCorpusName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listDocuments without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Document(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Document(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Document(), + ), + ]; + client.descriptors.page.listDocuments.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ai.generativelanguage.v1alpha.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('corpusPermissions', async () => { - const fakePath = "/rendered/path/corpusPermissions"; - const expectedParameters = { - corpus: "corpusValue", - permission: "permissionValue", - }; - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPermissionsPath', () => { - const result = client.corpusPermissionsPath("corpusValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('uses async iteration with listDocuments with error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + 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.ai.generativelanguage.v1alpha.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('listChunks', () => { + it('invokes listChunks without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.ListChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Chunk(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Chunk(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Chunk(), + ), + ]; + client.innerApiCalls.listChunks = stubSimpleCall(expectedResponse); + const [response] = await client.listChunks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listChunks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchCorpusFromCorpusPermissionsName', () => { - const result = client.matchCorpusFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listChunks without error using callback', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.ListChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Chunk(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Chunk(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Chunk(), + ), + ]; + client.innerApiCalls.listChunks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listChunks( + request, + ( + err?: Error | null, + result?: + | protos.google.ai.generativelanguage.v1alpha.IChunk[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listChunks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchPermissionFromCorpusPermissionsName', () => { - const result = client.matchPermissionFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes listChunks with error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.ListChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listChunks = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listChunks(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listChunks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('document', async () => { - const fakePath = "/rendered/path/document"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - }; - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.documentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.documentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('documentPath', () => { - const result = client.documentPath("corpusValue", "documentValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.documentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes listChunksStream without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.ListChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Chunk(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Chunk(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Chunk(), + ), + ]; + client.descriptors.page.listChunks.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listChunksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1alpha.Chunk[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1alpha.Chunk) => { + 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.listChunks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listChunks, request), + ); + assert( + (client.descriptors.page.listChunks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('matchCorpusFromDocumentName', () => { - const result = client.matchCorpusFromDocumentName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listChunksStream with error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.ListChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listChunks.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listChunksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1alpha.Chunk[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1alpha.Chunk) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listChunks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listChunks, request), + ); + assert( + (client.descriptors.page.listChunks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('matchDocumentFromDocumentName', () => { - const result = client.matchDocumentFromDocumentName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listChunks without error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.ListChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Chunk(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Chunk(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.Chunk(), + ), + ]; + client.descriptors.page.listChunks.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ai.generativelanguage.v1alpha.IChunk[] = + []; + const iterable = client.listChunksAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listChunks.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listChunks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('file', async () => { - const fakePath = "/rendered/path/file"; - const expectedParameters = { - file: "fileValue", - }; - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.filePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.filePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('filePath', () => { - const result = client.filePath("fileValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.filePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('uses async iteration with listChunks with error', async () => { + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.ListChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.ListChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listChunks.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listChunksAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ai.generativelanguage.v1alpha.IChunk[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listChunks.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listChunks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('cachedContent', async () => { + const fakePath = '/rendered/path/cachedContent'; + const expectedParameters = { + id: 'idValue', + }; + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.cachedContentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.cachedContentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('cachedContentPath', () => { + const result = client.cachedContentPath('idValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.cachedContentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchIdFromCachedContentName', () => { + const result = client.matchIdFromCachedContentName(fakePath); + assert.strictEqual(result, 'idValue'); + assert( + (client.pathTemplates.cachedContentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchFileFromFileName', () => { - const result = client.matchFileFromFileName(fakePath); - assert.strictEqual(result, "fileValue"); - assert((client.pathTemplates.filePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('chunk', async () => { + const fakePath = '/rendered/path/chunk'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + chunk: 'chunkValue', + }; + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.chunkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.chunkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('chunkPath', () => { + const result = client.chunkPath( + 'corpusValue', + 'documentValue', + 'chunkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.chunkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromChunkName', () => { + const result = client.matchCorpusFromChunkName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromChunkName', () => { + const result = client.matchDocumentFromChunkName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChunkFromChunkName', () => { + const result = client.matchChunkFromChunkName(fakePath); + assert.strictEqual(result, 'chunkValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('corpus', async () => { + const fakePath = '/rendered/path/corpus'; + const expectedParameters = { + corpus: 'corpusValue', + }; + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPath', () => { + const result = client.corpusPath('corpusValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.corpusPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusName', () => { + const result = client.matchCorpusFromCorpusName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.corpusPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpusPermissions', async () => { + const fakePath = '/rendered/path/corpusPermissions'; + const expectedParameters = { + corpus: 'corpusValue', + permission: 'permissionValue', + }; + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPermissionsPath', () => { + const result = client.corpusPermissionsPath( + 'corpusValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusPermissionsName', () => { + const result = client.matchCorpusFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromCorpusPermissionsName', () => { + const result = + client.matchPermissionFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModel', async () => { - const fakePath = "/rendered/path/tunedModel"; - const expectedParameters = { - tuned_model: "tunedModelValue", - }; - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPath', () => { - const result = client.tunedModelPath("tunedModelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('document', async () => { + const fakePath = '/rendered/path/document'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + }; + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.documentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.documentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('documentPath', () => { + const result = client.documentPath('corpusValue', 'documentValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.documentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromDocumentName', () => { + const result = client.matchCorpusFromDocumentName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromDocumentName', () => { + const result = client.matchDocumentFromDocumentName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchTunedModelFromTunedModelName', () => { - const result = client.matchTunedModelFromTunedModelName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('file', async () => { + const fakePath = '/rendered/path/file'; + const expectedParameters = { + file: 'fileValue', + }; + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.filePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.filePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('filePath', () => { + const result = client.filePath('fileValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.filePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFileFromFileName', () => { + const result = client.matchFileFromFileName(fakePath); + assert.strictEqual(result, 'fileValue'); + assert( + (client.pathTemplates.filePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModelPermissions', async () => { - const fakePath = "/rendered/path/tunedModelPermissions"; - const expectedParameters = { - tuned_model: "tunedModelValue", - permission: "permissionValue", - }; - const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPermissionsPath', () => { - const result = client.tunedModelPermissionsPath("tunedModelValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchTunedModelFromTunedModelPermissionsName', () => { - const result = client.matchTunedModelFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('tunedModel', async () => { + const fakePath = '/rendered/path/tunedModel'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + }; + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPath', () => { + const result = client.tunedModelPath('tunedModelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.tunedModelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelName', () => { + const result = client.matchTunedModelFromTunedModelName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.tunedModelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchPermissionFromTunedModelPermissionsName', () => { - const result = client.matchPermissionFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModelPermissions', async () => { + const fakePath = '/rendered/path/tunedModelPermissions'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + permission: 'permissionValue', + }; + const client = new retrieverserviceModule.v1alpha.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPermissionsPath', () => { + const result = client.tunedModelPermissionsPath( + 'tunedModelValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelPermissionsName', () => { + const result = + client.matchTunedModelFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromTunedModelPermissionsName', () => { + const result = + client.matchPermissionFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_retriever_service_v1beta.ts b/packages/google-ai-generativelanguage/test/gapic_retriever_service_v1beta.ts index 3cdfce142f57..7ca642db0788 100644 --- a/packages/google-ai-generativelanguage/test/gapic_retriever_service_v1beta.ts +++ b/packages/google-ai-generativelanguage/test/gapic_retriever_service_v1beta.ts @@ -19,3036 +19,3843 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as retrieverserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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 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('v1beta.RetrieverServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient(); - 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 = retrieverserviceModule.v1beta.RetrieverServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = retrieverserviceModule.v1beta.RetrieverServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 retrieverserviceModule.v1beta.RetrieverServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 retrieverserviceModule.v1beta.RetrieverServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 retrieverserviceModule.v1beta.RetrieverServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = retrieverserviceModule.v1beta.RetrieverServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.retrieverServiceStub, undefined); - await client.initialize(); - assert(client.retrieverServiceStub); - }); - - it('has close method for the initialized client', done => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.retrieverServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.retrieverServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - 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 retrieverserviceModule.v1beta.RetrieverServiceClient({ - 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 retrieverserviceModule.v1beta.RetrieverServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); }); - describe('createCorpus', () => { - it('invokes createCorpus without error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateCorpusRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.Corpus() - ); - client.innerApiCalls.createCorpus = stubSimpleCall(expectedResponse); - const [response] = await client.createCorpus(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes createCorpus without error using callback', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateCorpusRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.Corpus() - ); - client.innerApiCalls.createCorpus = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createCorpus( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.ICorpus|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes createCorpus with error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateCorpusRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createCorpus = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createCorpus(request), expectedError); - }); - - it('invokes createCorpus with closed client', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateCorpusRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createCorpus(request), expectedError); - }); + it('has universeDomain', () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); }); - describe('getCorpus', () => { - it('invokes getCorpus without error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.Corpus() - ); - client.innerApiCalls.getCorpus = stubSimpleCall(expectedResponse); - const [response] = await client.getCorpus(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCorpus without error using callback', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.Corpus() - ); - client.innerApiCalls.getCorpus = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getCorpus( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.ICorpus|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCorpus with error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getCorpus = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getCorpus(request), expectedError); - const actualRequest = (client.innerApiCalls.getCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCorpus with closed client', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getCorpus(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 = + retrieverserviceModule.v1beta.RetrieverServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + retrieverserviceModule.v1beta.RetrieverServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); }); - describe('updateCorpus', () => { - it('invokes updateCorpus without error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdateCorpusRequest() - ); - request.corpus ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.UpdateCorpusRequest', ['corpus', 'name']); - request.corpus.name = defaultValue1; - const expectedHeaderRequestParams = `corpus.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.Corpus() - ); - client.innerApiCalls.updateCorpus = stubSimpleCall(expectedResponse); - const [response] = await client.updateCorpus(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCorpus without error using callback', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdateCorpusRequest() - ); - request.corpus ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.UpdateCorpusRequest', ['corpus', 'name']); - request.corpus.name = defaultValue1; - const expectedHeaderRequestParams = `corpus.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.Corpus() - ); - client.innerApiCalls.updateCorpus = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateCorpus( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.ICorpus|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCorpus with error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdateCorpusRequest() - ); - request.corpus ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.UpdateCorpusRequest', ['corpus', 'name']); - request.corpus.name = defaultValue1; - const expectedHeaderRequestParams = `corpus.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateCorpus = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateCorpus(request), expectedError); - const actualRequest = (client.innerApiCalls.updateCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCorpus with closed client', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdateCorpusRequest() - ); - request.corpus ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.UpdateCorpusRequest', ['corpus', 'name']); - request.corpus.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateCorpus(request), expectedError); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); }); - describe('deleteCorpus', () => { - it('invokes deleteCorpus without error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeleteCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteCorpus = stubSimpleCall(expectedResponse); - const [response] = await client.deleteCorpus(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteCorpus without error using callback', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeleteCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteCorpus = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteCorpus( - 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.deleteCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteCorpus with error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeleteCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteCorpus = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteCorpus(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteCorpus with closed client', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeleteCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteCorpus(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 retrieverserviceModule.v1beta.RetrieverServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.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 retrieverserviceModule.v1beta.RetrieverServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.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 retrieverserviceModule.v1beta.RetrieverServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('queryCorpus', () => { - it('invokes queryCorpus without error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.QueryCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.QueryCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.QueryCorpusResponse() - ); - client.innerApiCalls.queryCorpus = stubSimpleCall(expectedResponse); - const [response] = await client.queryCorpus(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.queryCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.queryCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes queryCorpus without error using callback', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.QueryCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.QueryCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.QueryCorpusResponse() - ); - client.innerApiCalls.queryCorpus = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.queryCorpus( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IQueryCorpusResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.queryCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.queryCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes queryCorpus with error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.QueryCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.QueryCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.queryCorpus = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.queryCorpus(request), expectedError); - const actualRequest = (client.innerApiCalls.queryCorpus as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.queryCorpus as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes queryCorpus with closed client', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.QueryCorpusRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.QueryCorpusRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.queryCorpus(request), expectedError); - }); + it('has port', () => { + const port = retrieverserviceModule.v1beta.RetrieverServiceClient.port; + assert(port); + assert(typeof port === 'number'); }); - describe('createDocument', () => { - it('invokes createDocument without error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CreateDocumentRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.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 createDocument without error using callback', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CreateDocumentRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.Document() - ); - client.innerApiCalls.createDocument = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createDocument( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.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 createDocument with error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CreateDocumentRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - 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 createDocument with closed client', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CreateDocumentRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createDocument(request), expectedError); - }); + it('should create a client with no option', () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient(); + assert(client); }); - describe('getDocument', () => { - it('invokes getDocument without error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetDocumentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.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 retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetDocumentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.Document() - ); - client.innerApiCalls.getDocument = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getDocument( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.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 error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.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 with closed client', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.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('should create a client with gRPC fallback', () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + fallback: true, + }); + assert(client); }); - describe('updateDocument', () => { - it('invokes updateDocument without error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdateDocumentRequest() - ); - request.document ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.UpdateDocumentRequest', ['document', 'name']); - request.document.name = defaultValue1; - const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.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 without error using callback', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdateDocumentRequest() - ); - request.document ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.UpdateDocumentRequest', ['document', 'name']); - request.document.name = defaultValue1; - const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.Document() - ); - client.innerApiCalls.updateDocument = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateDocument( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.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 initialize method and supports deferred initialization', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.retrieverServiceStub, undefined); + await client.initialize(); + assert(client.retrieverServiceStub); + }); - it('invokes updateDocument with error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdateDocumentRequest() - ); - request.document ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.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('has close method for the initialized client', (done) => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.retrieverServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes updateDocument with closed client', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdateDocumentRequest() - ); - request.document ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.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('has close method for the non-initialized client', (done) => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.retrieverServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('deleteDocument', () => { - it('invokes deleteDocument without error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.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 getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + 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 deleteDocument without error using callback', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.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 getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + 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('createCorpus', () => { + it('invokes createCorpus without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateCorpusRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Corpus(), + ); + client.innerApiCalls.createCorpus = stubSimpleCall(expectedResponse); + const [response] = await client.createCorpus(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes deleteDocument with error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.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 createCorpus without error using callback', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateCorpusRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Corpus(), + ); + client.innerApiCalls.createCorpus = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createCorpus( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.ICorpus | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes deleteDocument with closed client', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.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 createCorpus with error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateCorpusRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createCorpus = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createCorpus(request), expectedError); }); - describe('queryDocument', () => { - it('invokes queryDocument without error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.QueryDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.QueryDocumentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.QueryDocumentResponse() - ); - client.innerApiCalls.queryDocument = stubSimpleCall(expectedResponse); - const [response] = await client.queryDocument(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.queryDocument as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.queryDocument as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createCorpus with closed client', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateCorpusRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createCorpus(request), expectedError); + }); + }); + + describe('getCorpus', () => { + it('invokes getCorpus without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Corpus(), + ); + client.innerApiCalls.getCorpus = stubSimpleCall(expectedResponse); + const [response] = await client.getCorpus(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes queryDocument without error using callback', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.QueryDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.QueryDocumentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.QueryDocumentResponse() - ); - client.innerApiCalls.queryDocument = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.queryDocument( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IQueryDocumentResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.queryDocument as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.queryDocument as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getCorpus without error using callback', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Corpus(), + ); + client.innerApiCalls.getCorpus = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getCorpus( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.ICorpus | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes queryDocument with error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.QueryDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.QueryDocumentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.queryDocument = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.queryDocument(request), expectedError); - const actualRequest = (client.innerApiCalls.queryDocument as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.queryDocument as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getCorpus with error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getCorpus = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getCorpus(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes queryDocument with closed client', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.QueryDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.QueryDocumentRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.queryDocument(request), expectedError); - }); + it('invokes getCorpus with closed client', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getCorpus(request), expectedError); + }); + }); + + describe('updateCorpus', () => { + it('invokes updateCorpus without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdateCorpusRequest(), + ); + request.corpus ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.UpdateCorpusRequest', + ['corpus', 'name'], + ); + request.corpus.name = defaultValue1; + const expectedHeaderRequestParams = `corpus.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Corpus(), + ); + client.innerApiCalls.updateCorpus = stubSimpleCall(expectedResponse); + const [response] = await client.updateCorpus(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createChunk', () => { - it('invokes createChunk without error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CreateChunkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.Chunk() - ); - client.innerApiCalls.createChunk = stubSimpleCall(expectedResponse); - const [response] = await client.createChunk(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createChunk as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateCorpus without error using callback', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdateCorpusRequest(), + ); + request.corpus ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.UpdateCorpusRequest', + ['corpus', 'name'], + ); + request.corpus.name = defaultValue1; + const expectedHeaderRequestParams = `corpus.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Corpus(), + ); + client.innerApiCalls.updateCorpus = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateCorpus( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.ICorpus | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createChunk without error using callback', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CreateChunkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.Chunk() - ); - client.innerApiCalls.createChunk = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createChunk( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IChunk|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createChunk as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateCorpus with error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdateCorpusRequest(), + ); + request.corpus ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.UpdateCorpusRequest', + ['corpus', 'name'], + ); + request.corpus.name = defaultValue1; + const expectedHeaderRequestParams = `corpus.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateCorpus = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateCorpus(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createChunk with error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CreateChunkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createChunk = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createChunk(request), expectedError); - const actualRequest = (client.innerApiCalls.createChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createChunk as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateCorpus with closed client', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdateCorpusRequest(), + ); + request.corpus ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.UpdateCorpusRequest', + ['corpus', 'name'], + ); + request.corpus.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateCorpus(request), expectedError); + }); + }); + + describe('deleteCorpus', () => { + it('invokes deleteCorpus without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeleteCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteCorpus = stubSimpleCall(expectedResponse); + const [response] = await client.deleteCorpus(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createChunk with closed client', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CreateChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CreateChunkRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createChunk(request), expectedError); - }); + it('invokes deleteCorpus without error using callback', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeleteCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteCorpus = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteCorpus( + 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.deleteCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('batchCreateChunks', () => { - it('invokes batchCreateChunks without error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchCreateChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.BatchCreateChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchCreateChunksResponse() - ); - client.innerApiCalls.batchCreateChunks = stubSimpleCall(expectedResponse); - const [response] = await client.batchCreateChunks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchCreateChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchCreateChunks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteCorpus with error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeleteCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteCorpus = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteCorpus(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchCreateChunks without error using callback', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchCreateChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.BatchCreateChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchCreateChunksResponse() - ); - client.innerApiCalls.batchCreateChunks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchCreateChunks( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchCreateChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchCreateChunks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteCorpus with closed client', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeleteCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteCorpus(request), expectedError); + }); + }); + + describe('queryCorpus', () => { + it('invokes queryCorpus without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.QueryCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.QueryCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.QueryCorpusResponse(), + ); + client.innerApiCalls.queryCorpus = stubSimpleCall(expectedResponse); + const [response] = await client.queryCorpus(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.queryCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.queryCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchCreateChunks with error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchCreateChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.BatchCreateChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchCreateChunks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchCreateChunks(request), expectedError); - const actualRequest = (client.innerApiCalls.batchCreateChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchCreateChunks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes queryCorpus without error using callback', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.QueryCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.QueryCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.QueryCorpusResponse(), + ); + client.innerApiCalls.queryCorpus = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.queryCorpus( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IQueryCorpusResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.queryCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.queryCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchCreateChunks with closed client', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchCreateChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.BatchCreateChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchCreateChunks(request), expectedError); - }); + it('invokes queryCorpus with error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.QueryCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.QueryCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.queryCorpus = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.queryCorpus(request), expectedError); + const actualRequest = ( + client.innerApiCalls.queryCorpus as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.queryCorpus as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getChunk', () => { - it('invokes getChunk without error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetChunkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.Chunk() - ); - client.innerApiCalls.getChunk = stubSimpleCall(expectedResponse); - const [response] = await client.getChunk(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getChunk as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes queryCorpus with closed client', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.QueryCorpusRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.QueryCorpusRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.queryCorpus(request), expectedError); + }); + }); + + describe('createDocument', () => { + it('invokes createDocument without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CreateDocumentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.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 getChunk without error using callback', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetChunkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.Chunk() - ); - client.innerApiCalls.getChunk = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getChunk( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IChunk|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getChunk 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 retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CreateDocumentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Document(), + ); + client.innerApiCalls.createDocument = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createDocument( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.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 getChunk with error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetChunkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getChunk = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getChunk(request), expectedError); - const actualRequest = (client.innerApiCalls.getChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getChunk 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 retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CreateDocumentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + 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 getChunk with closed client', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GetChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GetChunkRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getChunk(request), expectedError); - }); + it('invokes createDocument with closed client', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CreateDocumentRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createDocument(request), expectedError); + }); + }); + + describe('getDocument', () => { + it('invokes getDocument without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.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)); }); - describe('updateChunk', () => { - it('invokes updateChunk without error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdateChunkRequest() - ); - request.chunk ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.UpdateChunkRequest', ['chunk', 'name']); - request.chunk.name = defaultValue1; - const expectedHeaderRequestParams = `chunk.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.Chunk() - ); - client.innerApiCalls.updateChunk = stubSimpleCall(expectedResponse); - const [response] = await client.updateChunk(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateChunk 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 retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Document(), + ); + client.innerApiCalls.getDocument = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDocument( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.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 updateChunk without error using callback', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdateChunkRequest() - ); - request.chunk ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.UpdateChunkRequest', ['chunk', 'name']); - request.chunk.name = defaultValue1; - const expectedHeaderRequestParams = `chunk.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.Chunk() - ); - client.innerApiCalls.updateChunk = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateChunk( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IChunk|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateChunk 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 retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.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 updateChunk with error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdateChunkRequest() - ); - request.chunk ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.UpdateChunkRequest', ['chunk', 'name']); - request.chunk.name = defaultValue1; - const expectedHeaderRequestParams = `chunk.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateChunk = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateChunk(request), expectedError); - const actualRequest = (client.innerApiCalls.updateChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateChunk 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 retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.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 retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdateDocumentRequest(), + ); + request.document ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.UpdateDocumentRequest', + ['document', 'name'], + ); + request.document.name = defaultValue1; + const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.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 updateChunk with closed client', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.UpdateChunkRequest() - ); - request.chunk ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.UpdateChunkRequest', ['chunk', 'name']); - request.chunk.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateChunk(request), expectedError); - }); + it('invokes updateDocument without error using callback', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdateDocumentRequest(), + ); + request.document ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.UpdateDocumentRequest', + ['document', 'name'], + ); + request.document.name = defaultValue1; + const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Document(), + ); + client.innerApiCalls.updateDocument = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateDocument( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.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)); }); - describe('batchUpdateChunks', () => { - it('invokes batchUpdateChunks without error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchUpdateChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.BatchUpdateChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchUpdateChunksResponse() - ); - client.innerApiCalls.batchUpdateChunks = stubSimpleCall(expectedResponse); - const [response] = await client.batchUpdateChunks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchUpdateChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchUpdateChunks 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 retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdateDocumentRequest(), + ); + request.document ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.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 batchUpdateChunks without error using callback', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchUpdateChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.BatchUpdateChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchUpdateChunksResponse() - ); - client.innerApiCalls.batchUpdateChunks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchUpdateChunks( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchUpdateChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchUpdateChunks 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 retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdateDocumentRequest(), + ); + request.document ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.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 retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.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 batchUpdateChunks with error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchUpdateChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.BatchUpdateChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchUpdateChunks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchUpdateChunks(request), expectedError); - const actualRequest = (client.innerApiCalls.batchUpdateChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchUpdateChunks 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 retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.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 batchUpdateChunks with closed client', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchUpdateChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.BatchUpdateChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchUpdateChunks(request), expectedError); - }); + it('invokes deleteDocument with error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.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)); }); - describe('deleteChunk', () => { - it('invokes deleteChunk without error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeleteChunkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteChunk = stubSimpleCall(expectedResponse); - const [response] = await client.deleteChunk(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteChunk 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 retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.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('queryDocument', () => { + it('invokes queryDocument without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.QueryDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.QueryDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.QueryDocumentResponse(), + ); + client.innerApiCalls.queryDocument = stubSimpleCall(expectedResponse); + const [response] = await client.queryDocument(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.queryDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.queryDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteChunk without error using callback', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeleteChunkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteChunk = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteChunk( - 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.deleteChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteChunk as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes queryDocument without error using callback', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.QueryDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.QueryDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.QueryDocumentResponse(), + ); + client.innerApiCalls.queryDocument = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.queryDocument( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IQueryDocumentResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.queryDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.queryDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteChunk with error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeleteChunkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteChunk = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteChunk(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteChunk as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteChunk as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes queryDocument with error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.QueryDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.QueryDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.queryDocument = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.queryDocument(request), expectedError); + const actualRequest = ( + client.innerApiCalls.queryDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.queryDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteChunk with closed client', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.DeleteChunkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.DeleteChunkRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteChunk(request), expectedError); - }); + it('invokes queryDocument with closed client', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.QueryDocumentRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.QueryDocumentRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.queryDocument(request), expectedError); + }); + }); + + describe('createChunk', () => { + it('invokes createChunk without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CreateChunkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Chunk(), + ); + client.innerApiCalls.createChunk = stubSimpleCall(expectedResponse); + const [response] = await client.createChunk(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createChunk as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('batchDeleteChunks', () => { - it('invokes batchDeleteChunks without error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchDeleteChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.BatchDeleteChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.batchDeleteChunks = stubSimpleCall(expectedResponse); - const [response] = await client.batchDeleteChunks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchDeleteChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchDeleteChunks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createChunk without error using callback', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CreateChunkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Chunk(), + ); + client.innerApiCalls.createChunk = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createChunk( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IChunk | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createChunk as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchDeleteChunks without error using callback', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchDeleteChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.BatchDeleteChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.batchDeleteChunks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchDeleteChunks( - 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.batchDeleteChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchDeleteChunks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createChunk with error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CreateChunkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createChunk = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createChunk(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createChunk as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchDeleteChunks with error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchDeleteChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.BatchDeleteChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchDeleteChunks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchDeleteChunks(request), expectedError); - const actualRequest = (client.innerApiCalls.batchDeleteChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchDeleteChunks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createChunk with closed client', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CreateChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CreateChunkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createChunk(request), expectedError); + }); + }); + + describe('batchCreateChunks', () => { + it('invokes batchCreateChunks without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchCreateChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.BatchCreateChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchCreateChunksResponse(), + ); + client.innerApiCalls.batchCreateChunks = stubSimpleCall(expectedResponse); + const [response] = await client.batchCreateChunks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchCreateChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchCreateChunks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchDeleteChunks with closed client', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchDeleteChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.BatchDeleteChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchDeleteChunks(request), expectedError); - }); + it('invokes batchCreateChunks without error using callback', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchCreateChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.BatchCreateChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchCreateChunksResponse(), + ); + client.innerApiCalls.batchCreateChunks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchCreateChunks( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IBatchCreateChunksResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchCreateChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchCreateChunks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listCorpora', () => { - it('invokes listCorpora without error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListCorporaRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Corpus()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Corpus()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Corpus()), - ]; - client.innerApiCalls.listCorpora = stubSimpleCall(expectedResponse); - const [response] = await client.listCorpora(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes batchCreateChunks with error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchCreateChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.BatchCreateChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchCreateChunks = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.batchCreateChunks(request), expectedError); + const actualRequest = ( + client.innerApiCalls.batchCreateChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchCreateChunks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listCorpora without error using callback', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListCorporaRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Corpus()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Corpus()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Corpus()), - ]; - client.innerApiCalls.listCorpora = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listCorpora( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.ICorpus[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes batchCreateChunks with closed client', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchCreateChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.BatchCreateChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.batchCreateChunks(request), expectedError); + }); + }); + + describe('getChunk', () => { + it('invokes getChunk without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetChunkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Chunk(), + ); + client.innerApiCalls.getChunk = stubSimpleCall(expectedResponse); + const [response] = await client.getChunk(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getChunk as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listCorpora with error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListCorporaRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listCorpora = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listCorpora(request), expectedError); - }); + it('invokes getChunk without error using callback', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetChunkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Chunk(), + ); + client.innerApiCalls.getChunk = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getChunk( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IChunk | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getChunk as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listCorporaStream without error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListCorporaRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Corpus()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Corpus()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Corpus()), - ]; - client.descriptors.page.listCorpora.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listCorporaStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1beta.Corpus[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta.Corpus) => { - 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.listCorpora.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCorpora, request)); - }); + it('invokes getChunk with error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetChunkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getChunk = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getChunk(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getChunk as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listCorporaStream with error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListCorporaRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listCorpora.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listCorporaStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1beta.Corpus[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta.Corpus) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listCorpora.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCorpora, request)); - }); + it('invokes getChunk with closed client', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GetChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GetChunkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getChunk(request), expectedError); + }); + }); + + describe('updateChunk', () => { + it('invokes updateChunk without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdateChunkRequest(), + ); + request.chunk ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.UpdateChunkRequest', + ['chunk', 'name'], + ); + request.chunk.name = defaultValue1; + const expectedHeaderRequestParams = `chunk.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Chunk(), + ); + client.innerApiCalls.updateChunk = stubSimpleCall(expectedResponse); + const [response] = await client.updateChunk(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateChunk as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listCorpora without error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListCorporaRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Corpus()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Corpus()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Corpus()), - ]; - client.descriptors.page.listCorpora.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ai.generativelanguage.v1beta.ICorpus[] = []; - const iterable = client.listCorporaAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes updateChunk without error using callback', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdateChunkRequest(), + ); + request.chunk ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.UpdateChunkRequest', + ['chunk', 'name'], + ); + request.chunk.name = defaultValue1; + const expectedHeaderRequestParams = `chunk.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Chunk(), + ); + client.innerApiCalls.updateChunk = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateChunk( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IChunk | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listCorpora.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); - - it('uses async iteration with listCorpora with error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListCorporaRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listCorpora.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listCorporaAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ai.generativelanguage.v1beta.ICorpus[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listCorpora.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateChunk 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 retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.ListDocumentsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Document()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Document()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.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 updateChunk with error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdateChunkRequest(), + ); + request.chunk ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.UpdateChunkRequest', + ['chunk', 'name'], + ); + request.chunk.name = defaultValue1; + const expectedHeaderRequestParams = `chunk.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateChunk = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateChunk(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateChunk 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 retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.ListDocumentsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Document()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Document()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Document()), - ]; - client.innerApiCalls.listDocuments = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listDocuments( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.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 updateChunk with closed client', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.UpdateChunkRequest(), + ); + request.chunk ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.UpdateChunkRequest', + ['chunk', 'name'], + ); + request.chunk.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateChunk(request), expectedError); + }); + }); + + describe('batchUpdateChunks', () => { + it('invokes batchUpdateChunks without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchUpdateChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.BatchUpdateChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchUpdateChunksResponse(), + ); + client.innerApiCalls.batchUpdateChunks = stubSimpleCall(expectedResponse); + const [response] = await client.batchUpdateChunks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchUpdateChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchUpdateChunks 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 retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.ListDocumentsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - 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 batchUpdateChunks without error using callback', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchUpdateChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.BatchUpdateChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchUpdateChunksResponse(), + ); + client.innerApiCalls.batchUpdateChunks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchUpdateChunks( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IBatchUpdateChunksResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchUpdateChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchUpdateChunks 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 retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.ListDocumentsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Document()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Document()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Document()), - ]; - client.descriptors.page.listDocuments.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listDocumentsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1beta.Document[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta.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 batchUpdateChunks with error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchUpdateChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.BatchUpdateChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchUpdateChunks = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.batchUpdateChunks(request), expectedError); + const actualRequest = ( + client.innerApiCalls.batchUpdateChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchUpdateChunks 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 retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.ListDocumentsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - 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.ai.generativelanguage.v1beta.Document[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta.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 batchUpdateChunks with closed client', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchUpdateChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.BatchUpdateChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.batchUpdateChunks(request), expectedError); + }); + }); + + describe('deleteChunk', () => { + it('invokes deleteChunk without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeleteChunkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteChunk = stubSimpleCall(expectedResponse); + const [response] = await client.deleteChunk(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteChunk 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 retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.ListDocumentsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Document()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Document()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Document()), - ]; - client.descriptors.page.listDocuments.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ai.generativelanguage.v1beta.IDocument[] = []; - const iterable = client.listDocumentsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes deleteChunk without error using callback', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeleteChunkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteChunk = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteChunk( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | 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 retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.ListDocumentsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - 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.ai.generativelanguage.v1beta.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.deleteChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteChunk as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listChunks', () => { - it('invokes listChunks without error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.ListChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Chunk()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Chunk()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Chunk()), - ]; - client.innerApiCalls.listChunks = stubSimpleCall(expectedResponse); - const [response] = await client.listChunks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listChunks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteChunk with error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeleteChunkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteChunk = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteChunk(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteChunk as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteChunk as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listChunks without error using callback', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.ListChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Chunk()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Chunk()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Chunk()), - ]; - client.innerApiCalls.listChunks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listChunks( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IChunk[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listChunks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteChunk with closed client', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.DeleteChunkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.DeleteChunkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteChunk(request), expectedError); + }); + }); + + describe('batchDeleteChunks', () => { + it('invokes batchDeleteChunks without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchDeleteChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.BatchDeleteChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.batchDeleteChunks = stubSimpleCall(expectedResponse); + const [response] = await client.batchDeleteChunks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchDeleteChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchDeleteChunks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listChunks with error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.ListChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listChunks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listChunks(request), expectedError); - const actualRequest = (client.innerApiCalls.listChunks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listChunks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchDeleteChunks without error using callback', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchDeleteChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.BatchDeleteChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.batchDeleteChunks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchDeleteChunks( + 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.batchDeleteChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchDeleteChunks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listChunksStream without error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.ListChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Chunk()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Chunk()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Chunk()), - ]; - client.descriptors.page.listChunks.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listChunksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1beta.Chunk[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta.Chunk) => { - 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.listChunks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listChunks, request)); - assert( - (client.descriptors.page.listChunks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes batchDeleteChunks with error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchDeleteChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.BatchDeleteChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchDeleteChunks = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.batchDeleteChunks(request), expectedError); + const actualRequest = ( + client.innerApiCalls.batchDeleteChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchDeleteChunks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listChunksStream with error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.ListChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listChunks.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listChunksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.ai.generativelanguage.v1beta.Chunk[] = []; - stream.on('data', (response: protos.google.ai.generativelanguage.v1beta.Chunk) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listChunks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listChunks, request)); - assert( - (client.descriptors.page.listChunks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes batchDeleteChunks with closed client', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchDeleteChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.BatchDeleteChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.batchDeleteChunks(request), expectedError); + }); + }); + + describe('listCorpora', () => { + it('invokes listCorpora without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListCorporaRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Corpus(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Corpus(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Corpus(), + ), + ]; + client.innerApiCalls.listCorpora = stubSimpleCall(expectedResponse); + const [response] = await client.listCorpora(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('uses async iteration with listChunks without error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.ListChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Chunk()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Chunk()), - generateSampleMessage(new protos.google.ai.generativelanguage.v1beta.Chunk()), - ]; - client.descriptors.page.listChunks.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.ai.generativelanguage.v1beta.IChunk[] = []; - const iterable = client.listChunksAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listCorpora without error using callback', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListCorporaRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Corpus(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Corpus(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Corpus(), + ), + ]; + client.innerApiCalls.listCorpora = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listCorpora( + request, + ( + err?: Error | null, + result?: + | protos.google.ai.generativelanguage.v1beta.ICorpus[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listChunks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listChunks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('uses async iteration with listChunks with error', async () => { - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.ListChunksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.ListChunksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listChunks.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listChunksAsync(request); - await assert.rejects(async () => { - const responses: protos.google.ai.generativelanguage.v1beta.IChunk[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listChunks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listChunks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listCorpora with error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListCorporaRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listCorpora = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listCorpora(request), expectedError); }); - describe('Path templates', () => { + it('invokes listCorporaStream without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListCorporaRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Corpus(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Corpus(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Corpus(), + ), + ]; + client.descriptors.page.listCorpora.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listCorporaStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1beta.Corpus[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1beta.Corpus) => { + 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.listCorpora.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCorpora, request), + ); + }); - describe('cachedContent', async () => { - const fakePath = "/rendered/path/cachedContent"; - const expectedParameters = { - id: "idValue", - }; - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.cachedContentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.cachedContentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('cachedContentPath', () => { - const result = client.cachedContentPath("idValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.cachedContentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes listCorporaStream with error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListCorporaRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listCorpora.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listCorporaStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1beta.Corpus[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1beta.Corpus) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listCorpora.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCorpora, request), + ); + }); - it('matchIdFromCachedContentName', () => { - const result = client.matchIdFromCachedContentName(fakePath); - assert.strictEqual(result, "idValue"); - assert((client.pathTemplates.cachedContentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listCorpora without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListCorporaRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Corpus(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Corpus(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Corpus(), + ), + ]; + client.descriptors.page.listCorpora.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ai.generativelanguage.v1beta.ICorpus[] = + []; + const iterable = client.listCorporaAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listCorpora.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); - describe('chunk', async () => { - const fakePath = "/rendered/path/chunk"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - chunk: "chunkValue", - }; - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.chunkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.chunkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('chunkPath', () => { - const result = client.chunkPath("corpusValue", "documentValue", "chunkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.chunkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('uses async iteration with listCorpora with error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListCorporaRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listCorpora.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listCorporaAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ai.generativelanguage.v1beta.ICorpus[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listCorpora.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + }); + }); + + describe('listDocuments', () => { + it('invokes listDocuments without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Document(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Document(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.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('matchCorpusFromChunkName', () => { - const result = client.matchCorpusFromChunkName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listDocuments without error using callback', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Document(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Document(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Document(), + ), + ]; + client.innerApiCalls.listDocuments = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listDocuments( + request, + ( + err?: Error | null, + result?: + | protos.google.ai.generativelanguage.v1beta.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('matchDocumentFromChunkName', () => { - const result = client.matchDocumentFromChunkName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listDocuments with error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + 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('matchChunkFromChunkName', () => { - const result = client.matchChunkFromChunkName(fakePath); - assert.strictEqual(result, "chunkValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes listDocumentsStream without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Document(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Document(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Document(), + ), + ]; + client.descriptors.page.listDocuments.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listDocumentsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1beta.Document[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1beta.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), + ); + }); - describe('corpus', async () => { - const fakePath = "/rendered/path/corpus"; - const expectedParameters = { - corpus: "corpusValue", - }; - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPath', () => { - const result = client.corpusPath("corpusValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes listDocumentsStream with error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + 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.ai.generativelanguage.v1beta.Document[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1beta.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('matchCorpusFromCorpusName', () => { - const result = client.matchCorpusFromCorpusName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listDocuments without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Document(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Document(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Document(), + ), + ]; + client.descriptors.page.listDocuments.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ai.generativelanguage.v1beta.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('corpusPermissions', async () => { - const fakePath = "/rendered/path/corpusPermissions"; - const expectedParameters = { - corpus: "corpusValue", - permission: "permissionValue", - }; - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPermissionsPath', () => { - const result = client.corpusPermissionsPath("corpusValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('uses async iteration with listDocuments with error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListDocumentsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.ListDocumentsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + 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.ai.generativelanguage.v1beta.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('listChunks', () => { + it('invokes listChunks without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.ListChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Chunk(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Chunk(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Chunk(), + ), + ]; + client.innerApiCalls.listChunks = stubSimpleCall(expectedResponse); + const [response] = await client.listChunks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listChunks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchCorpusFromCorpusPermissionsName', () => { - const result = client.matchCorpusFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listChunks without error using callback', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.ListChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Chunk(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Chunk(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Chunk(), + ), + ]; + client.innerApiCalls.listChunks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listChunks( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IChunk[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listChunks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchPermissionFromCorpusPermissionsName', () => { - const result = client.matchPermissionFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes listChunks with error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.ListChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listChunks = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listChunks(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listChunks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listChunks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('document', async () => { - const fakePath = "/rendered/path/document"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - }; - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.documentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.documentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('documentPath', () => { - const result = client.documentPath("corpusValue", "documentValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.documentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes listChunksStream without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.ListChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Chunk(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Chunk(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Chunk(), + ), + ]; + client.descriptors.page.listChunks.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listChunksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1beta.Chunk[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1beta.Chunk) => { + 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.listChunks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listChunks, request), + ); + assert( + (client.descriptors.page.listChunks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('matchCorpusFromDocumentName', () => { - const result = client.matchCorpusFromDocumentName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listChunksStream with error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.ListChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listChunks.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listChunksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.ai.generativelanguage.v1beta.Chunk[] = + []; + stream.on( + 'data', + (response: protos.google.ai.generativelanguage.v1beta.Chunk) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listChunks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listChunks, request), + ); + assert( + (client.descriptors.page.listChunks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('matchDocumentFromDocumentName', () => { - const result = client.matchDocumentFromDocumentName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listChunks without error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.ListChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Chunk(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Chunk(), + ), + generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.Chunk(), + ), + ]; + client.descriptors.page.listChunks.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.ai.generativelanguage.v1beta.IChunk[] = []; + const iterable = client.listChunksAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listChunks.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listChunks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('file', async () => { - const fakePath = "/rendered/path/file"; - const expectedParameters = { - file: "fileValue", - }; - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.filePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.filePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('filePath', () => { - const result = client.filePath("fileValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.filePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('uses async iteration with listChunks with error', async () => { + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.ListChunksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.ListChunksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listChunks.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listChunksAsync(request); + await assert.rejects(async () => { + const responses: protos.google.ai.generativelanguage.v1beta.IChunk[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listChunks.asyncIterate as SinonStub).getCall( + 0, + ).args[1], + request, + ); + assert( + (client.descriptors.page.listChunks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('cachedContent', async () => { + const fakePath = '/rendered/path/cachedContent'; + const expectedParameters = { + id: 'idValue', + }; + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.cachedContentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.cachedContentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('cachedContentPath', () => { + const result = client.cachedContentPath('idValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.cachedContentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchIdFromCachedContentName', () => { + const result = client.matchIdFromCachedContentName(fakePath); + assert.strictEqual(result, 'idValue'); + assert( + (client.pathTemplates.cachedContentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchFileFromFileName', () => { - const result = client.matchFileFromFileName(fakePath); - assert.strictEqual(result, "fileValue"); - assert((client.pathTemplates.filePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('chunk', async () => { + const fakePath = '/rendered/path/chunk'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + chunk: 'chunkValue', + }; + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.chunkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.chunkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('chunkPath', () => { + const result = client.chunkPath( + 'corpusValue', + 'documentValue', + 'chunkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.chunkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromChunkName', () => { + const result = client.matchCorpusFromChunkName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromChunkName', () => { + const result = client.matchDocumentFromChunkName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChunkFromChunkName', () => { + const result = client.matchChunkFromChunkName(fakePath); + assert.strictEqual(result, 'chunkValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('corpus', async () => { + const fakePath = '/rendered/path/corpus'; + const expectedParameters = { + corpus: 'corpusValue', + }; + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPath', () => { + const result = client.corpusPath('corpusValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.corpusPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusName', () => { + const result = client.matchCorpusFromCorpusName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.corpusPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpusPermissions', async () => { + const fakePath = '/rendered/path/corpusPermissions'; + const expectedParameters = { + corpus: 'corpusValue', + permission: 'permissionValue', + }; + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPermissionsPath', () => { + const result = client.corpusPermissionsPath( + 'corpusValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusPermissionsName', () => { + const result = client.matchCorpusFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromCorpusPermissionsName', () => { + const result = + client.matchPermissionFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModel', async () => { - const fakePath = "/rendered/path/tunedModel"; - const expectedParameters = { - tuned_model: "tunedModelValue", - }; - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPath', () => { - const result = client.tunedModelPath("tunedModelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('document', async () => { + const fakePath = '/rendered/path/document'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + }; + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.documentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.documentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('documentPath', () => { + const result = client.documentPath('corpusValue', 'documentValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.documentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromDocumentName', () => { + const result = client.matchCorpusFromDocumentName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromDocumentName', () => { + const result = client.matchDocumentFromDocumentName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchTunedModelFromTunedModelName', () => { - const result = client.matchTunedModelFromTunedModelName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('file', async () => { + const fakePath = '/rendered/path/file'; + const expectedParameters = { + file: 'fileValue', + }; + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.filePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.filePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('filePath', () => { + const result = client.filePath('fileValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.filePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFileFromFileName', () => { + const result = client.matchFileFromFileName(fakePath); + assert.strictEqual(result, 'fileValue'); + assert( + (client.pathTemplates.filePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModelPermissions', async () => { - const fakePath = "/rendered/path/tunedModelPermissions"; - const expectedParameters = { - tuned_model: "tunedModelValue", - permission: "permissionValue", - }; - const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPermissionsPath', () => { - const result = client.tunedModelPermissionsPath("tunedModelValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchTunedModelFromTunedModelPermissionsName', () => { - const result = client.matchTunedModelFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('tunedModel', async () => { + const fakePath = '/rendered/path/tunedModel'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + }; + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPath', () => { + const result = client.tunedModelPath('tunedModelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.tunedModelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelName', () => { + const result = client.matchTunedModelFromTunedModelName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.tunedModelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchPermissionFromTunedModelPermissionsName', () => { - const result = client.matchPermissionFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModelPermissions', async () => { + const fakePath = '/rendered/path/tunedModelPermissions'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + permission: 'permissionValue', + }; + const client = new retrieverserviceModule.v1beta.RetrieverServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPermissionsPath', () => { + const result = client.tunedModelPermissionsPath( + 'tunedModelValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelPermissionsName', () => { + const result = + client.matchTunedModelFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromTunedModelPermissionsName', () => { + const result = + client.matchPermissionFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_text_service_v1alpha.ts b/packages/google-ai-generativelanguage/test/gapic_text_service_v1alpha.ts index c1fa5e392719..91d2503fe483 100644 --- a/packages/google-ai-generativelanguage/test/gapic_text_service_v1alpha.ts +++ b/packages/google-ai-generativelanguage/test/gapic_text_service_v1alpha.ts @@ -19,941 +19,1196 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as textserviceModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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); } describe('v1alpha.TextServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new textserviceModule.v1alpha.TextServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new textserviceModule.v1alpha.TextServiceClient(); - 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 = textserviceModule.v1alpha.TextServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = textserviceModule.v1alpha.TextServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new textserviceModule.v1alpha.TextServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new textserviceModule.v1alpha.TextServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new textserviceModule.v1alpha.TextServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.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 textserviceModule.v1alpha.TextServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 textserviceModule.v1alpha.TextServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 textserviceModule.v1alpha.TextServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('has universeDomain', () => { + const client = new textserviceModule.v1alpha.TextServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has port', () => { - const port = textserviceModule.v1alpha.TextServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + textserviceModule.v1alpha.TextServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + textserviceModule.v1alpha.TextServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new textserviceModule.v1alpha.TextServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('should create a client with no option', () => { - const client = new textserviceModule.v1alpha.TextServiceClient(); - assert(client); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new textserviceModule.v1alpha.TextServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new textserviceModule.v1alpha.TextServiceClient({ - fallback: true, - }); - assert(client); + 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 textserviceModule.v1alpha.TextServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has initialize method and supports deferred initialization', async () => { - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.textServiceStub, undefined); - await client.initialize(); - assert(client.textServiceStub); + 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 textserviceModule.v1alpha.TextServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('has close method for the initialized client', done => { - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.textServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new textserviceModule.v1alpha.TextServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has close method for the non-initialized client', done => { - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.textServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = textserviceModule.v1alpha.TextServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new textserviceModule.v1alpha.TextServiceClient({ - 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('should create a client with no option', () => { + const client = new textserviceModule.v1alpha.TextServiceClient(); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new textserviceModule.v1alpha.TextServiceClient({ - 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('should create a client with gRPC fallback', () => { + const client = new textserviceModule.v1alpha.TextServiceClient({ + fallback: true, + }); + assert(client); }); - describe('generateText', () => { - it('invokes generateText without error', async () => { - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GenerateTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateTextResponse() - ); - client.innerApiCalls.generateText = stubSimpleCall(expectedResponse); - const [response] = await client.generateText(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateText 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 textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.textServiceStub, undefined); + await client.initialize(); + assert(client.textServiceStub); + }); - it('invokes generateText without error using callback', async () => { - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GenerateTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateTextResponse() - ); - client.innerApiCalls.generateText = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.generateText( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IGenerateTextResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateText 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 textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.textServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes generateText with error', async () => { - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GenerateTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.generateText = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.generateText(request), expectedError); - const actualRequest = (client.innerApiCalls.generateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateText 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 textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.textServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes generateText with closed client', async () => { - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.GenerateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.GenerateTextRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.generateText(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new textserviceModule.v1alpha.TextServiceClient({ + 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('embedText', () => { - it('invokes embedText without error', async () => { - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.EmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.EmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.EmbedTextResponse() - ); - client.innerApiCalls.embedText = stubSimpleCall(expectedResponse); - const [response] = await client.embedText(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.embedText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.embedText 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 textserviceModule.v1alpha.TextServiceClient({ + 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('generateText', () => { + it('invokes generateText without error', async () => { + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GenerateTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateTextResponse(), + ); + client.innerApiCalls.generateText = stubSimpleCall(expectedResponse); + const [response] = await client.generateText(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes embedText without error using callback', async () => { - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.EmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.EmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.EmbedTextResponse() - ); - client.innerApiCalls.embedText = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.embedText( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IEmbedTextResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.embedText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.embedText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes generateText without error using callback', async () => { + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GenerateTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateTextResponse(), + ); + client.innerApiCalls.generateText = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.generateText( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.IGenerateTextResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes embedText with error', async () => { - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.EmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.EmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.embedText = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.embedText(request), expectedError); - const actualRequest = (client.innerApiCalls.embedText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.embedText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes generateText with error', async () => { + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GenerateTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.generateText = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.generateText(request), expectedError); + const actualRequest = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes embedText with closed client', async () => { - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.EmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.EmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.embedText(request), expectedError); - }); + it('invokes generateText with closed client', async () => { + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.GenerateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.GenerateTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.generateText(request), expectedError); + }); + }); + + describe('embedText', () => { + it('invokes embedText without error', async () => { + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.EmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.EmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.EmbedTextResponse(), + ); + client.innerApiCalls.embedText = stubSimpleCall(expectedResponse); + const [response] = await client.embedText(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('batchEmbedText', () => { - it('invokes batchEmbedText without error', async () => { - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchEmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.BatchEmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchEmbedTextResponse() - ); - client.innerApiCalls.batchEmbedText = stubSimpleCall(expectedResponse); - const [response] = await client.batchEmbedText(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchEmbedText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchEmbedText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes embedText without error using callback', async () => { + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.EmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.EmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.EmbedTextResponse(), + ); + client.innerApiCalls.embedText = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.embedText( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.IEmbedTextResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchEmbedText without error using callback', async () => { - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchEmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.BatchEmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchEmbedTextResponse() - ); - client.innerApiCalls.batchEmbedText = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchEmbedText( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchEmbedText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchEmbedText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes embedText with error', async () => { + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.EmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.EmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.embedText = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.embedText(request), expectedError); + const actualRequest = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchEmbedText with error', async () => { - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchEmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.BatchEmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchEmbedText = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchEmbedText(request), expectedError); - const actualRequest = (client.innerApiCalls.batchEmbedText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchEmbedText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes embedText with closed client', async () => { + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.EmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.EmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.embedText(request), expectedError); + }); + }); + + describe('batchEmbedText', () => { + it('invokes batchEmbedText without error', async () => { + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchEmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.BatchEmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchEmbedTextResponse(), + ); + client.innerApiCalls.batchEmbedText = stubSimpleCall(expectedResponse); + const [response] = await client.batchEmbedText(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchEmbedText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchEmbedText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchEmbedText with closed client', async () => { - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.BatchEmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.BatchEmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchEmbedText(request), expectedError); - }); + it('invokes batchEmbedText without error using callback', async () => { + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchEmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.BatchEmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchEmbedTextResponse(), + ); + client.innerApiCalls.batchEmbedText = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchEmbedText( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.IBatchEmbedTextResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchEmbedText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchEmbedText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('countTextTokens', () => { - it('invokes countTextTokens without error', async () => { - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CountTextTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CountTextTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CountTextTokensResponse() - ); - client.innerApiCalls.countTextTokens = stubSimpleCall(expectedResponse); - const [response] = await client.countTextTokens(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.countTextTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countTextTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchEmbedText with error', async () => { + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchEmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.BatchEmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchEmbedText = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.batchEmbedText(request), expectedError); + const actualRequest = ( + client.innerApiCalls.batchEmbedText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchEmbedText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countTextTokens without error using callback', async () => { - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CountTextTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CountTextTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CountTextTokensResponse() - ); - client.innerApiCalls.countTextTokens = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.countTextTokens( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1alpha.ICountTextTokensResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.countTextTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countTextTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchEmbedText with closed client', async () => { + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.BatchEmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.BatchEmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.batchEmbedText(request), expectedError); + }); + }); + + describe('countTextTokens', () => { + it('invokes countTextTokens without error', async () => { + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CountTextTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CountTextTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CountTextTokensResponse(), + ); + client.innerApiCalls.countTextTokens = stubSimpleCall(expectedResponse); + const [response] = await client.countTextTokens(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.countTextTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countTextTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countTextTokens with error', async () => { - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CountTextTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CountTextTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.countTextTokens = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.countTextTokens(request), expectedError); - const actualRequest = (client.innerApiCalls.countTextTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countTextTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes countTextTokens without error using callback', async () => { + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CountTextTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CountTextTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CountTextTokensResponse(), + ); + client.innerApiCalls.countTextTokens = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.countTextTokens( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1alpha.ICountTextTokensResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.countTextTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countTextTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countTextTokens with closed client', async () => { - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1alpha.CountTextTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1alpha.CountTextTokensRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.countTextTokens(request), expectedError); - }); + it('invokes countTextTokens with error', async () => { + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CountTextTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CountTextTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.countTextTokens = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.countTextTokens(request), expectedError); + const actualRequest = ( + client.innerApiCalls.countTextTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countTextTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('cachedContent', async () => { - const fakePath = "/rendered/path/cachedContent"; - const expectedParameters = { - id: "idValue", - }; - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.cachedContentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.cachedContentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('cachedContentPath', () => { - const result = client.cachedContentPath("idValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.cachedContentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchIdFromCachedContentName', () => { - const result = client.matchIdFromCachedContentName(fakePath); - assert.strictEqual(result, "idValue"); - assert((client.pathTemplates.cachedContentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes countTextTokens with closed client', async () => { + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1alpha.CountTextTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1alpha.CountTextTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.countTextTokens(request), expectedError); + }); + }); + + describe('Path templates', () => { + describe('cachedContent', async () => { + const fakePath = '/rendered/path/cachedContent'; + const expectedParameters = { + id: 'idValue', + }; + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.cachedContentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.cachedContentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('cachedContentPath', () => { + const result = client.cachedContentPath('idValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.cachedContentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchIdFromCachedContentName', () => { + const result = client.matchIdFromCachedContentName(fakePath); + assert.strictEqual(result, 'idValue'); + assert( + (client.pathTemplates.cachedContentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('chunk', async () => { - const fakePath = "/rendered/path/chunk"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - chunk: "chunkValue", - }; - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.chunkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.chunkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('chunkPath', () => { - const result = client.chunkPath("corpusValue", "documentValue", "chunkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.chunkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromChunkName', () => { - const result = client.matchCorpusFromChunkName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromChunkName', () => { - const result = client.matchDocumentFromChunkName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChunkFromChunkName', () => { - const result = client.matchChunkFromChunkName(fakePath); - assert.strictEqual(result, "chunkValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('chunk', async () => { + const fakePath = '/rendered/path/chunk'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + chunk: 'chunkValue', + }; + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.chunkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.chunkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('chunkPath', () => { + const result = client.chunkPath( + 'corpusValue', + 'documentValue', + 'chunkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.chunkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromChunkName', () => { + const result = client.matchCorpusFromChunkName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromChunkName', () => { + const result = client.matchDocumentFromChunkName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChunkFromChunkName', () => { + const result = client.matchChunkFromChunkName(fakePath); + assert.strictEqual(result, 'chunkValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('corpus', async () => { - const fakePath = "/rendered/path/corpus"; - const expectedParameters = { - corpus: "corpusValue", - }; - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPath', () => { - const result = client.corpusPath("corpusValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusName', () => { - const result = client.matchCorpusFromCorpusName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpus', async () => { + const fakePath = '/rendered/path/corpus'; + const expectedParameters = { + corpus: 'corpusValue', + }; + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPath', () => { + const result = client.corpusPath('corpusValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.corpusPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusName', () => { + const result = client.matchCorpusFromCorpusName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.corpusPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('corpusPermissions', async () => { - const fakePath = "/rendered/path/corpusPermissions"; - const expectedParameters = { - corpus: "corpusValue", - permission: "permissionValue", - }; - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPermissionsPath', () => { - const result = client.corpusPermissionsPath("corpusValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusPermissionsName', () => { - const result = client.matchCorpusFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromCorpusPermissionsName', () => { - const result = client.matchPermissionFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpusPermissions', async () => { + const fakePath = '/rendered/path/corpusPermissions'; + const expectedParameters = { + corpus: 'corpusValue', + permission: 'permissionValue', + }; + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPermissionsPath', () => { + const result = client.corpusPermissionsPath( + 'corpusValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusPermissionsName', () => { + const result = client.matchCorpusFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromCorpusPermissionsName', () => { + const result = + client.matchPermissionFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('document', async () => { - const fakePath = "/rendered/path/document"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - }; - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.documentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.documentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('documentPath', () => { - const result = client.documentPath("corpusValue", "documentValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.documentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromDocumentName', () => { - const result = client.matchCorpusFromDocumentName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromDocumentName', () => { - const result = client.matchDocumentFromDocumentName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('document', async () => { + const fakePath = '/rendered/path/document'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + }; + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.documentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.documentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('documentPath', () => { + const result = client.documentPath('corpusValue', 'documentValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.documentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromDocumentName', () => { + const result = client.matchCorpusFromDocumentName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromDocumentName', () => { + const result = client.matchDocumentFromDocumentName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('file', async () => { - const fakePath = "/rendered/path/file"; - const expectedParameters = { - file: "fileValue", - }; - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.filePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.filePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('filePath', () => { - const result = client.filePath("fileValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.filePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFileFromFileName', () => { - const result = client.matchFileFromFileName(fakePath); - assert.strictEqual(result, "fileValue"); - assert((client.pathTemplates.filePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('file', async () => { + const fakePath = '/rendered/path/file'; + const expectedParameters = { + file: 'fileValue', + }; + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.filePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.filePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('filePath', () => { + const result = client.filePath('fileValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.filePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFileFromFileName', () => { + const result = client.matchFileFromFileName(fakePath); + assert.strictEqual(result, 'fileValue'); + assert( + (client.pathTemplates.filePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModel', async () => { - const fakePath = "/rendered/path/tunedModel"; - const expectedParameters = { - tuned_model: "tunedModelValue", - }; - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPath', () => { - const result = client.tunedModelPath("tunedModelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelName', () => { - const result = client.matchTunedModelFromTunedModelName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModel', async () => { + const fakePath = '/rendered/path/tunedModel'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + }; + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPath', () => { + const result = client.tunedModelPath('tunedModelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.tunedModelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelName', () => { + const result = client.matchTunedModelFromTunedModelName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.tunedModelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModelPermissions', async () => { - const fakePath = "/rendered/path/tunedModelPermissions"; - const expectedParameters = { - tuned_model: "tunedModelValue", - permission: "permissionValue", - }; - const client = new textserviceModule.v1alpha.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPermissionsPath', () => { - const result = client.tunedModelPermissionsPath("tunedModelValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelPermissionsName', () => { - const result = client.matchTunedModelFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromTunedModelPermissionsName', () => { - const result = client.matchPermissionFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModelPermissions', async () => { + const fakePath = '/rendered/path/tunedModelPermissions'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + permission: 'permissionValue', + }; + const client = new textserviceModule.v1alpha.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPermissionsPath', () => { + const result = client.tunedModelPermissionsPath( + 'tunedModelValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelPermissionsName', () => { + const result = + client.matchTunedModelFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromTunedModelPermissionsName', () => { + const result = + client.matchPermissionFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_text_service_v1beta.ts b/packages/google-ai-generativelanguage/test/gapic_text_service_v1beta.ts index 3b650c7f8d09..771aec3b88ae 100644 --- a/packages/google-ai-generativelanguage/test/gapic_text_service_v1beta.ts +++ b/packages/google-ai-generativelanguage/test/gapic_text_service_v1beta.ts @@ -19,941 +19,1196 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as textserviceModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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); } describe('v1beta.TextServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new textserviceModule.v1beta.TextServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new textserviceModule.v1beta.TextServiceClient(); - 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 = textserviceModule.v1beta.TextServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = textserviceModule.v1beta.TextServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new textserviceModule.v1beta.TextServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new textserviceModule.v1beta.TextServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new textserviceModule.v1beta.TextServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.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 textserviceModule.v1beta.TextServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 textserviceModule.v1beta.TextServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 textserviceModule.v1beta.TextServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('has universeDomain', () => { + const client = new textserviceModule.v1beta.TextServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has port', () => { - const port = textserviceModule.v1beta.TextServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + textserviceModule.v1beta.TextServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + textserviceModule.v1beta.TextServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new textserviceModule.v1beta.TextServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('should create a client with no option', () => { - const client = new textserviceModule.v1beta.TextServiceClient(); - assert(client); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new textserviceModule.v1beta.TextServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new textserviceModule.v1beta.TextServiceClient({ - fallback: true, - }); - assert(client); + 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 textserviceModule.v1beta.TextServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has initialize method and supports deferred initialization', async () => { - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.textServiceStub, undefined); - await client.initialize(); - assert(client.textServiceStub); + 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 textserviceModule.v1beta.TextServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('has close method for the initialized client', done => { - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.textServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new textserviceModule.v1beta.TextServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has close method for the non-initialized client', done => { - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.textServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = textserviceModule.v1beta.TextServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new textserviceModule.v1beta.TextServiceClient({ - 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('should create a client with no option', () => { + const client = new textserviceModule.v1beta.TextServiceClient(); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new textserviceModule.v1beta.TextServiceClient({ - 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('should create a client with gRPC fallback', () => { + const client = new textserviceModule.v1beta.TextServiceClient({ + fallback: true, + }); + assert(client); }); - describe('generateText', () => { - it('invokes generateText without error', async () => { - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GenerateTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateTextResponse() - ); - client.innerApiCalls.generateText = stubSimpleCall(expectedResponse); - const [response] = await client.generateText(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateText 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 textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.textServiceStub, undefined); + await client.initialize(); + assert(client.textServiceStub); + }); - it('invokes generateText without error using callback', async () => { - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GenerateTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateTextResponse() - ); - client.innerApiCalls.generateText = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.generateText( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IGenerateTextResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateText 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 textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.textServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes generateText with error', async () => { - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GenerateTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.generateText = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.generateText(request), expectedError); - const actualRequest = (client.innerApiCalls.generateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateText 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 textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.textServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes generateText with closed client', async () => { - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.GenerateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.GenerateTextRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.generateText(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new textserviceModule.v1beta.TextServiceClient({ + 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('embedText', () => { - it('invokes embedText without error', async () => { - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.EmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.EmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.EmbedTextResponse() - ); - client.innerApiCalls.embedText = stubSimpleCall(expectedResponse); - const [response] = await client.embedText(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.embedText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.embedText 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 textserviceModule.v1beta.TextServiceClient({ + 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('generateText', () => { + it('invokes generateText without error', async () => { + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GenerateTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateTextResponse(), + ); + client.innerApiCalls.generateText = stubSimpleCall(expectedResponse); + const [response] = await client.generateText(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes embedText without error using callback', async () => { - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.EmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.EmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.EmbedTextResponse() - ); - client.innerApiCalls.embedText = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.embedText( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IEmbedTextResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.embedText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.embedText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes generateText without error using callback', async () => { + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GenerateTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateTextResponse(), + ); + client.innerApiCalls.generateText = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.generateText( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IGenerateTextResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes embedText with error', async () => { - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.EmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.EmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.embedText = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.embedText(request), expectedError); - const actualRequest = (client.innerApiCalls.embedText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.embedText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes generateText with error', async () => { + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GenerateTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.generateText = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.generateText(request), expectedError); + const actualRequest = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes embedText with closed client', async () => { - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.EmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.EmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.embedText(request), expectedError); - }); + it('invokes generateText with closed client', async () => { + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.GenerateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.GenerateTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.generateText(request), expectedError); + }); + }); + + describe('embedText', () => { + it('invokes embedText without error', async () => { + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.EmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.EmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.EmbedTextResponse(), + ); + client.innerApiCalls.embedText = stubSimpleCall(expectedResponse); + const [response] = await client.embedText(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('batchEmbedText', () => { - it('invokes batchEmbedText without error', async () => { - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchEmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.BatchEmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchEmbedTextResponse() - ); - client.innerApiCalls.batchEmbedText = stubSimpleCall(expectedResponse); - const [response] = await client.batchEmbedText(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchEmbedText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchEmbedText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes embedText without error using callback', async () => { + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.EmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.EmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.EmbedTextResponse(), + ); + client.innerApiCalls.embedText = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.embedText( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IEmbedTextResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchEmbedText without error using callback', async () => { - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchEmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.BatchEmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchEmbedTextResponse() - ); - client.innerApiCalls.batchEmbedText = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchEmbedText( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchEmbedText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchEmbedText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes embedText with error', async () => { + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.EmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.EmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.embedText = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.embedText(request), expectedError); + const actualRequest = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchEmbedText with error', async () => { - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchEmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.BatchEmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchEmbedText = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchEmbedText(request), expectedError); - const actualRequest = (client.innerApiCalls.batchEmbedText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchEmbedText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes embedText with closed client', async () => { + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.EmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.EmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.embedText(request), expectedError); + }); + }); + + describe('batchEmbedText', () => { + it('invokes batchEmbedText without error', async () => { + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchEmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.BatchEmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchEmbedTextResponse(), + ); + client.innerApiCalls.batchEmbedText = stubSimpleCall(expectedResponse); + const [response] = await client.batchEmbedText(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchEmbedText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchEmbedText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchEmbedText with closed client', async () => { - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.BatchEmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.BatchEmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchEmbedText(request), expectedError); - }); + it('invokes batchEmbedText without error using callback', async () => { + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchEmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.BatchEmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchEmbedTextResponse(), + ); + client.innerApiCalls.batchEmbedText = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchEmbedText( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.IBatchEmbedTextResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchEmbedText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchEmbedText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('countTextTokens', () => { - it('invokes countTextTokens without error', async () => { - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CountTextTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CountTextTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CountTextTokensResponse() - ); - client.innerApiCalls.countTextTokens = stubSimpleCall(expectedResponse); - const [response] = await client.countTextTokens(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.countTextTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countTextTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchEmbedText with error', async () => { + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchEmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.BatchEmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchEmbedText = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.batchEmbedText(request), expectedError); + const actualRequest = ( + client.innerApiCalls.batchEmbedText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchEmbedText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countTextTokens without error using callback', async () => { - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CountTextTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CountTextTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CountTextTokensResponse() - ); - client.innerApiCalls.countTextTokens = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.countTextTokens( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta.ICountTextTokensResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.countTextTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countTextTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchEmbedText with closed client', async () => { + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.BatchEmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.BatchEmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.batchEmbedText(request), expectedError); + }); + }); + + describe('countTextTokens', () => { + it('invokes countTextTokens without error', async () => { + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CountTextTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CountTextTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CountTextTokensResponse(), + ); + client.innerApiCalls.countTextTokens = stubSimpleCall(expectedResponse); + const [response] = await client.countTextTokens(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.countTextTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countTextTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countTextTokens with error', async () => { - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CountTextTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CountTextTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.countTextTokens = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.countTextTokens(request), expectedError); - const actualRequest = (client.innerApiCalls.countTextTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countTextTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes countTextTokens without error using callback', async () => { + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CountTextTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CountTextTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CountTextTokensResponse(), + ); + client.innerApiCalls.countTextTokens = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.countTextTokens( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta.ICountTextTokensResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.countTextTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countTextTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countTextTokens with closed client', async () => { - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta.CountTextTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta.CountTextTokensRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.countTextTokens(request), expectedError); - }); + it('invokes countTextTokens with error', async () => { + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CountTextTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CountTextTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.countTextTokens = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.countTextTokens(request), expectedError); + const actualRequest = ( + client.innerApiCalls.countTextTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countTextTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('cachedContent', async () => { - const fakePath = "/rendered/path/cachedContent"; - const expectedParameters = { - id: "idValue", - }; - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.cachedContentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.cachedContentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('cachedContentPath', () => { - const result = client.cachedContentPath("idValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.cachedContentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchIdFromCachedContentName', () => { - const result = client.matchIdFromCachedContentName(fakePath); - assert.strictEqual(result, "idValue"); - assert((client.pathTemplates.cachedContentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes countTextTokens with closed client', async () => { + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta.CountTextTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta.CountTextTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.countTextTokens(request), expectedError); + }); + }); + + describe('Path templates', () => { + describe('cachedContent', async () => { + const fakePath = '/rendered/path/cachedContent'; + const expectedParameters = { + id: 'idValue', + }; + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.cachedContentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.cachedContentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('cachedContentPath', () => { + const result = client.cachedContentPath('idValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.cachedContentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchIdFromCachedContentName', () => { + const result = client.matchIdFromCachedContentName(fakePath); + assert.strictEqual(result, 'idValue'); + assert( + (client.pathTemplates.cachedContentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('chunk', async () => { - const fakePath = "/rendered/path/chunk"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - chunk: "chunkValue", - }; - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.chunkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.chunkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('chunkPath', () => { - const result = client.chunkPath("corpusValue", "documentValue", "chunkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.chunkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromChunkName', () => { - const result = client.matchCorpusFromChunkName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromChunkName', () => { - const result = client.matchDocumentFromChunkName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChunkFromChunkName', () => { - const result = client.matchChunkFromChunkName(fakePath); - assert.strictEqual(result, "chunkValue"); - assert((client.pathTemplates.chunkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('chunk', async () => { + const fakePath = '/rendered/path/chunk'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + chunk: 'chunkValue', + }; + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.chunkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.chunkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('chunkPath', () => { + const result = client.chunkPath( + 'corpusValue', + 'documentValue', + 'chunkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.chunkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromChunkName', () => { + const result = client.matchCorpusFromChunkName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromChunkName', () => { + const result = client.matchDocumentFromChunkName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChunkFromChunkName', () => { + const result = client.matchChunkFromChunkName(fakePath); + assert.strictEqual(result, 'chunkValue'); + assert( + (client.pathTemplates.chunkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('corpus', async () => { - const fakePath = "/rendered/path/corpus"; - const expectedParameters = { - corpus: "corpusValue", - }; - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPath', () => { - const result = client.corpusPath("corpusValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusName', () => { - const result = client.matchCorpusFromCorpusName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpus', async () => { + const fakePath = '/rendered/path/corpus'; + const expectedParameters = { + corpus: 'corpusValue', + }; + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPath', () => { + const result = client.corpusPath('corpusValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.corpusPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusName', () => { + const result = client.matchCorpusFromCorpusName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.corpusPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('corpusPermissions', async () => { - const fakePath = "/rendered/path/corpusPermissions"; - const expectedParameters = { - corpus: "corpusValue", - permission: "permissionValue", - }; - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.corpusPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.corpusPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('corpusPermissionsPath', () => { - const result = client.corpusPermissionsPath("corpusValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.corpusPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromCorpusPermissionsName', () => { - const result = client.matchCorpusFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromCorpusPermissionsName', () => { - const result = client.matchPermissionFromCorpusPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.corpusPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('corpusPermissions', async () => { + const fakePath = '/rendered/path/corpusPermissions'; + const expectedParameters = { + corpus: 'corpusValue', + permission: 'permissionValue', + }; + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.corpusPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.corpusPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('corpusPermissionsPath', () => { + const result = client.corpusPermissionsPath( + 'corpusValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromCorpusPermissionsName', () => { + const result = client.matchCorpusFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromCorpusPermissionsName', () => { + const result = + client.matchPermissionFromCorpusPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.corpusPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('document', async () => { - const fakePath = "/rendered/path/document"; - const expectedParameters = { - corpus: "corpusValue", - document: "documentValue", - }; - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.documentPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.documentPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('documentPath', () => { - const result = client.documentPath("corpusValue", "documentValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.documentPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchCorpusFromDocumentName', () => { - const result = client.matchCorpusFromDocumentName(fakePath); - assert.strictEqual(result, "corpusValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDocumentFromDocumentName', () => { - const result = client.matchDocumentFromDocumentName(fakePath); - assert.strictEqual(result, "documentValue"); - assert((client.pathTemplates.documentPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('document', async () => { + const fakePath = '/rendered/path/document'; + const expectedParameters = { + corpus: 'corpusValue', + document: 'documentValue', + }; + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.documentPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.documentPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('documentPath', () => { + const result = client.documentPath('corpusValue', 'documentValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.documentPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchCorpusFromDocumentName', () => { + const result = client.matchCorpusFromDocumentName(fakePath); + assert.strictEqual(result, 'corpusValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDocumentFromDocumentName', () => { + const result = client.matchDocumentFromDocumentName(fakePath); + assert.strictEqual(result, 'documentValue'); + assert( + (client.pathTemplates.documentPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('file', async () => { - const fakePath = "/rendered/path/file"; - const expectedParameters = { - file: "fileValue", - }; - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.filePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.filePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('filePath', () => { - const result = client.filePath("fileValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.filePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFileFromFileName', () => { - const result = client.matchFileFromFileName(fakePath); - assert.strictEqual(result, "fileValue"); - assert((client.pathTemplates.filePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('file', async () => { + const fakePath = '/rendered/path/file'; + const expectedParameters = { + file: 'fileValue', + }; + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.filePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.filePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('filePath', () => { + const result = client.filePath('fileValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.filePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFileFromFileName', () => { + const result = client.matchFileFromFileName(fakePath); + assert.strictEqual(result, 'fileValue'); + assert( + (client.pathTemplates.filePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModel', async () => { - const fakePath = "/rendered/path/tunedModel"; - const expectedParameters = { - tuned_model: "tunedModelValue", - }; - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPath', () => { - const result = client.tunedModelPath("tunedModelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelName', () => { - const result = client.matchTunedModelFromTunedModelName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModel', async () => { + const fakePath = '/rendered/path/tunedModel'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + }; + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPath', () => { + const result = client.tunedModelPath('tunedModelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.tunedModelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelName', () => { + const result = client.matchTunedModelFromTunedModelName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.tunedModelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModelPermissions', async () => { - const fakePath = "/rendered/path/tunedModelPermissions"; - const expectedParameters = { - tuned_model: "tunedModelValue", - permission: "permissionValue", - }; - const client = new textserviceModule.v1beta.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPermissionsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPermissionsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPermissionsPath', () => { - const result = client.tunedModelPermissionsPath("tunedModelValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelPermissionsName', () => { - const result = client.matchTunedModelFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromTunedModelPermissionsName', () => { - const result = client.matchPermissionFromTunedModelPermissionsName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.tunedModelPermissionsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModelPermissions', async () => { + const fakePath = '/rendered/path/tunedModelPermissions'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + permission: 'permissionValue', + }; + const client = new textserviceModule.v1beta.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPermissionsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPermissionsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPermissionsPath', () => { + const result = client.tunedModelPermissionsPath( + 'tunedModelValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelPermissionsName', () => { + const result = + client.matchTunedModelFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromTunedModelPermissionsName', () => { + const result = + client.matchPermissionFromTunedModelPermissionsName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + ( + client.pathTemplates.tunedModelPermissionsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_text_service_v1beta2.ts b/packages/google-ai-generativelanguage/test/gapic_text_service_v1beta2.ts index 9d187d39b65f..c4f10684bbcc 100644 --- a/packages/google-ai-generativelanguage/test/gapic_text_service_v1beta2.ts +++ b/packages/google-ai-generativelanguage/test/gapic_text_service_v1beta2.ts @@ -19,445 +19,542 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as textserviceModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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); } describe('v1beta2.TextServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new textserviceModule.v1beta2.TextServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new textserviceModule.v1beta2.TextServiceClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new textserviceModule.v1beta2.TextServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.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 = textserviceModule.v1beta2.TextServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = textserviceModule.v1beta2.TextServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new textserviceModule.v1beta2.TextServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); + it('has universeDomain', () => { + const client = new textserviceModule.v1beta2.TextServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new textserviceModule.v1beta2.TextServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 = + textserviceModule.v1beta2.TextServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + textserviceModule.v1beta2.TextServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new textserviceModule.v1beta2.TextServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.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 textserviceModule.v1beta2.TextServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 textserviceModule.v1beta2.TextServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 textserviceModule.v1beta2.TextServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new textserviceModule.v1beta2.TextServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('has port', () => { - const port = textserviceModule.v1beta2.TextServiceClient.port; - assert(port); - assert(typeof port === 'number'); + 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 textserviceModule.v1beta2.TextServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with no option', () => { - const client = new textserviceModule.v1beta2.TextServiceClient(); - assert(client); + 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 textserviceModule.v1beta2.TextServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with gRPC fallback', () => { - const client = new textserviceModule.v1beta2.TextServiceClient({ - fallback: true, - }); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new textserviceModule.v1beta2.TextServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new textserviceModule.v1beta2.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.textServiceStub, undefined); - await client.initialize(); - assert(client.textServiceStub); - }); + it('has port', () => { + const port = textserviceModule.v1beta2.TextServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the initialized client', done => { - const client = new textserviceModule.v1beta2.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.textServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new textserviceModule.v1beta2.TextServiceClient(); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new textserviceModule.v1beta2.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.textServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new textserviceModule.v1beta2.TextServiceClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new textserviceModule.v1beta2.TextServiceClient({ - 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 initialize method and supports deferred initialization', async () => { + const client = new textserviceModule.v1beta2.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.textServiceStub, undefined); + await client.initialize(); + assert(client.textServiceStub); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new textserviceModule.v1beta2.TextServiceClient({ - 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('has close method for the initialized client', (done) => { + const client = new textserviceModule.v1beta2.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.textServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('generateText', () => { - it('invokes generateText without error', async () => { - const client = new textserviceModule.v1beta2.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.GenerateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta2.GenerateTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.GenerateTextResponse() - ); - client.innerApiCalls.generateText = stubSimpleCall(expectedResponse); - const [response] = await client.generateText(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateText 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 textserviceModule.v1beta2.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.textServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes generateText without error using callback', async () => { - const client = new textserviceModule.v1beta2.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.GenerateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta2.GenerateTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.GenerateTextResponse() - ); - client.innerApiCalls.generateText = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.generateText( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta2.IGenerateTextResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateText 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 textserviceModule.v1beta2.TextServiceClient({ + 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 generateText with error', async () => { - const client = new textserviceModule.v1beta2.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.GenerateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta2.GenerateTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.generateText = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.generateText(request), expectedError); - const actualRequest = (client.innerApiCalls.generateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateText 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 textserviceModule.v1beta2.TextServiceClient({ + 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('generateText', () => { + it('invokes generateText without error', async () => { + const client = new textserviceModule.v1beta2.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.GenerateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta2.GenerateTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.GenerateTextResponse(), + ); + client.innerApiCalls.generateText = stubSimpleCall(expectedResponse); + const [response] = await client.generateText(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes generateText with closed client', async () => { - const client = new textserviceModule.v1beta2.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.GenerateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta2.GenerateTextRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.generateText(request), expectedError); - }); + it('invokes generateText without error using callback', async () => { + const client = new textserviceModule.v1beta2.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.GenerateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta2.GenerateTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.GenerateTextResponse(), + ); + client.innerApiCalls.generateText = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.generateText( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta2.IGenerateTextResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('embedText', () => { - it('invokes embedText without error', async () => { - const client = new textserviceModule.v1beta2.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.EmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta2.EmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.EmbedTextResponse() - ); - client.innerApiCalls.embedText = stubSimpleCall(expectedResponse); - const [response] = await client.embedText(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.embedText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.embedText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes generateText with error', async () => { + const client = new textserviceModule.v1beta2.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.GenerateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta2.GenerateTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.generateText = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.generateText(request), expectedError); + const actualRequest = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes embedText without error using callback', async () => { - const client = new textserviceModule.v1beta2.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.EmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta2.EmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.EmbedTextResponse() - ); - client.innerApiCalls.embedText = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.embedText( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta2.IEmbedTextResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.embedText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.embedText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes generateText with closed client', async () => { + const client = new textserviceModule.v1beta2.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.GenerateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta2.GenerateTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.generateText(request), expectedError); + }); + }); + + describe('embedText', () => { + it('invokes embedText without error', async () => { + const client = new textserviceModule.v1beta2.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.EmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta2.EmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.EmbedTextResponse(), + ); + client.innerApiCalls.embedText = stubSimpleCall(expectedResponse); + const [response] = await client.embedText(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes embedText with error', async () => { - const client = new textserviceModule.v1beta2.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.EmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta2.EmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.embedText = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.embedText(request), expectedError); - const actualRequest = (client.innerApiCalls.embedText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.embedText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes embedText without error using callback', async () => { + const client = new textserviceModule.v1beta2.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.EmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta2.EmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.EmbedTextResponse(), + ); + client.innerApiCalls.embedText = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.embedText( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta2.IEmbedTextResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes embedText with closed client', async () => { - const client = new textserviceModule.v1beta2.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta2.EmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta2.EmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.embedText(request), expectedError); - }); + it('invokes embedText with error', async () => { + const client = new textserviceModule.v1beta2.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.EmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta2.EmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.embedText = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.embedText(request), expectedError); + const actualRequest = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new textserviceModule.v1beta2.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes embedText with closed client', async () => { + const client = new textserviceModule.v1beta2.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta2.EmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta2.EmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.embedText(request), expectedError); + }); + }); + + describe('Path templates', () => { + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = new textserviceModule.v1beta2.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/test/gapic_text_service_v1beta3.ts b/packages/google-ai-generativelanguage/test/gapic_text_service_v1beta3.ts index 61ed6fcfeaf8..d3ef1e39ac91 100644 --- a/packages/google-ai-generativelanguage/test/gapic_text_service_v1beta3.ts +++ b/packages/google-ai-generativelanguage/test/gapic_text_service_v1beta3.ts @@ -19,729 +19,896 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as textserviceModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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); } describe('v1beta3.TextServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new textserviceModule.v1beta3.TextServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new textserviceModule.v1beta3.TextServiceClient(); - 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 = textserviceModule.v1beta3.TextServiceClient.servicePath; - assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = textserviceModule.v1beta3.TextServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new textserviceModule.v1beta3.TextServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new textserviceModule.v1beta3.TextServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 textserviceModule.v1beta3.TextServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 textserviceModule.v1beta3.TextServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'generativelanguage.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 textserviceModule.v1beta3.TextServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = textserviceModule.v1beta3.TextServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new textserviceModule.v1beta3.TextServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + }); - it('should create a client with no option', () => { - const client = new textserviceModule.v1beta3.TextServiceClient(); - assert(client); - }); + it('has universeDomain', () => { + const client = new textserviceModule.v1beta3.TextServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new textserviceModule.v1beta3.TextServiceClient({ - fallback: true, - }); - assert(client); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + textserviceModule.v1beta3.TextServiceClient.servicePath; + assert.strictEqual(servicePath, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + textserviceModule.v1beta3.TextServiceClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'generativelanguage.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new textserviceModule.v1beta3.TextServiceClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new textserviceModule.v1beta3.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.textServiceStub, undefined); - await client.initialize(); - assert(client.textServiceStub); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new textserviceModule.v1beta3.TextServiceClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.example.com'); + }); - it('has close method for the initialized client', done => { - const client = new textserviceModule.v1beta3.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.textServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + 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 textserviceModule.v1beta3.TextServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'generativelanguage.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 textserviceModule.v1beta3.TextServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'generativelanguage.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 textserviceModule.v1beta3.TextServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has close method for the non-initialized client', done => { - const client = new textserviceModule.v1beta3.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.textServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has port', () => { + const port = textserviceModule.v1beta3.TextServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new textserviceModule.v1beta3.TextServiceClient({ - 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('should create a client with no option', () => { + const client = new textserviceModule.v1beta3.TextServiceClient(); + assert(client); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new textserviceModule.v1beta3.TextServiceClient({ - 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('should create a client with gRPC fallback', () => { + const client = new textserviceModule.v1beta3.TextServiceClient({ + fallback: true, + }); + assert(client); }); - describe('generateText', () => { - it('invokes generateText without error', async () => { - const client = new textserviceModule.v1beta3.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GenerateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.GenerateTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GenerateTextResponse() - ); - client.innerApiCalls.generateText = stubSimpleCall(expectedResponse); - const [response] = await client.generateText(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateText 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 textserviceModule.v1beta3.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.textServiceStub, undefined); + await client.initialize(); + assert(client.textServiceStub); + }); - it('invokes generateText without error using callback', async () => { - const client = new textserviceModule.v1beta3.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GenerateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.GenerateTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GenerateTextResponse() - ); - client.innerApiCalls.generateText = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.generateText( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta3.IGenerateTextResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.generateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateText 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 textserviceModule.v1beta3.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.textServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes generateText with error', async () => { - const client = new textserviceModule.v1beta3.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GenerateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.GenerateTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.generateText = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.generateText(request), expectedError); - const actualRequest = (client.innerApiCalls.generateText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.generateText 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 textserviceModule.v1beta3.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.textServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes generateText with closed client', async () => { - const client = new textserviceModule.v1beta3.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.GenerateTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.GenerateTextRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.generateText(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new textserviceModule.v1beta3.TextServiceClient({ + 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('embedText', () => { - it('invokes embedText without error', async () => { - const client = new textserviceModule.v1beta3.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.EmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.EmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.EmbedTextResponse() - ); - client.innerApiCalls.embedText = stubSimpleCall(expectedResponse); - const [response] = await client.embedText(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.embedText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.embedText 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 textserviceModule.v1beta3.TextServiceClient({ + 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('generateText', () => { + it('invokes generateText without error', async () => { + const client = new textserviceModule.v1beta3.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GenerateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.GenerateTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GenerateTextResponse(), + ); + client.innerApiCalls.generateText = stubSimpleCall(expectedResponse); + const [response] = await client.generateText(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes embedText without error using callback', async () => { - const client = new textserviceModule.v1beta3.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.EmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.EmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.EmbedTextResponse() - ); - client.innerApiCalls.embedText = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.embedText( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta3.IEmbedTextResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.embedText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.embedText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes generateText without error using callback', async () => { + const client = new textserviceModule.v1beta3.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GenerateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.GenerateTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GenerateTextResponse(), + ); + client.innerApiCalls.generateText = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.generateText( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta3.IGenerateTextResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes embedText with error', async () => { - const client = new textserviceModule.v1beta3.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.EmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.EmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.embedText = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.embedText(request), expectedError); - const actualRequest = (client.innerApiCalls.embedText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.embedText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes generateText with error', async () => { + const client = new textserviceModule.v1beta3.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GenerateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.GenerateTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.generateText = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.generateText(request), expectedError); + const actualRequest = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.generateText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes embedText with closed client', async () => { - const client = new textserviceModule.v1beta3.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.EmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.EmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.embedText(request), expectedError); - }); + it('invokes generateText with closed client', async () => { + const client = new textserviceModule.v1beta3.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.GenerateTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.GenerateTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.generateText(request), expectedError); + }); + }); + + describe('embedText', () => { + it('invokes embedText without error', async () => { + const client = new textserviceModule.v1beta3.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.EmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.EmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.EmbedTextResponse(), + ); + client.innerApiCalls.embedText = stubSimpleCall(expectedResponse); + const [response] = await client.embedText(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('batchEmbedText', () => { - it('invokes batchEmbedText without error', async () => { - const client = new textserviceModule.v1beta3.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.BatchEmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.BatchEmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.BatchEmbedTextResponse() - ); - client.innerApiCalls.batchEmbedText = stubSimpleCall(expectedResponse); - const [response] = await client.batchEmbedText(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchEmbedText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchEmbedText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes embedText without error using callback', async () => { + const client = new textserviceModule.v1beta3.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.EmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.EmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.EmbedTextResponse(), + ); + client.innerApiCalls.embedText = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.embedText( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta3.IEmbedTextResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchEmbedText without error using callback', async () => { - const client = new textserviceModule.v1beta3.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.BatchEmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.BatchEmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.BatchEmbedTextResponse() - ); - client.innerApiCalls.batchEmbedText = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchEmbedText( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchEmbedText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchEmbedText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes embedText with error', async () => { + const client = new textserviceModule.v1beta3.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.EmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.EmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.embedText = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.embedText(request), expectedError); + const actualRequest = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.embedText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchEmbedText with error', async () => { - const client = new textserviceModule.v1beta3.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.BatchEmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.BatchEmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchEmbedText = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchEmbedText(request), expectedError); - const actualRequest = (client.innerApiCalls.batchEmbedText as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchEmbedText as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes embedText with closed client', async () => { + const client = new textserviceModule.v1beta3.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.EmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.EmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.embedText(request), expectedError); + }); + }); + + describe('batchEmbedText', () => { + it('invokes batchEmbedText without error', async () => { + const client = new textserviceModule.v1beta3.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.BatchEmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.BatchEmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.BatchEmbedTextResponse(), + ); + client.innerApiCalls.batchEmbedText = stubSimpleCall(expectedResponse); + const [response] = await client.batchEmbedText(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchEmbedText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchEmbedText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchEmbedText with closed client', async () => { - const client = new textserviceModule.v1beta3.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.BatchEmbedTextRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.BatchEmbedTextRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchEmbedText(request), expectedError); - }); + it('invokes batchEmbedText without error using callback', async () => { + const client = new textserviceModule.v1beta3.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.BatchEmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.BatchEmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.BatchEmbedTextResponse(), + ); + client.innerApiCalls.batchEmbedText = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchEmbedText( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta3.IBatchEmbedTextResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchEmbedText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchEmbedText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('countTextTokens', () => { - it('invokes countTextTokens without error', async () => { - const client = new textserviceModule.v1beta3.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.CountTextTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.CountTextTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.CountTextTokensResponse() - ); - client.innerApiCalls.countTextTokens = stubSimpleCall(expectedResponse); - const [response] = await client.countTextTokens(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.countTextTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countTextTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchEmbedText with error', async () => { + const client = new textserviceModule.v1beta3.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.BatchEmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.BatchEmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchEmbedText = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.batchEmbedText(request), expectedError); + const actualRequest = ( + client.innerApiCalls.batchEmbedText as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchEmbedText as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countTextTokens without error using callback', async () => { - const client = new textserviceModule.v1beta3.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.CountTextTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.CountTextTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.CountTextTokensResponse() - ); - client.innerApiCalls.countTextTokens = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.countTextTokens( - request, - (err?: Error|null, result?: protos.google.ai.generativelanguage.v1beta3.ICountTextTokensResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.countTextTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countTextTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchEmbedText with closed client', async () => { + const client = new textserviceModule.v1beta3.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.BatchEmbedTextRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.BatchEmbedTextRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.batchEmbedText(request), expectedError); + }); + }); + + describe('countTextTokens', () => { + it('invokes countTextTokens without error', async () => { + const client = new textserviceModule.v1beta3.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.CountTextTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.CountTextTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.CountTextTokensResponse(), + ); + client.innerApiCalls.countTextTokens = stubSimpleCall(expectedResponse); + const [response] = await client.countTextTokens(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.countTextTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countTextTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countTextTokens with error', async () => { - const client = new textserviceModule.v1beta3.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.CountTextTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.CountTextTokensRequest', ['model']); - request.model = defaultValue1; - const expectedHeaderRequestParams = `model=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.countTextTokens = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.countTextTokens(request), expectedError); - const actualRequest = (client.innerApiCalls.countTextTokens as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.countTextTokens as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes countTextTokens without error using callback', async () => { + const client = new textserviceModule.v1beta3.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.CountTextTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.CountTextTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.CountTextTokensResponse(), + ); + client.innerApiCalls.countTextTokens = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.countTextTokens( + request, + ( + err?: Error | null, + result?: protos.google.ai.generativelanguage.v1beta3.ICountTextTokensResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.countTextTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countTextTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes countTextTokens with closed client', async () => { - const client = new textserviceModule.v1beta3.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.ai.generativelanguage.v1beta3.CountTextTokensRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.ai.generativelanguage.v1beta3.CountTextTokensRequest', ['model']); - request.model = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.countTextTokens(request), expectedError); - }); + it('invokes countTextTokens with error', async () => { + const client = new textserviceModule.v1beta3.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.CountTextTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.CountTextTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedHeaderRequestParams = `model=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.countTextTokens = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.countTextTokens(request), expectedError); + const actualRequest = ( + client.innerApiCalls.countTextTokens as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.countTextTokens as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('model', async () => { - const fakePath = "/rendered/path/model"; - const expectedParameters = { - model: "modelValue", - }; - const client = new textserviceModule.v1beta3.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.modelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.modelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('modelPath', () => { - const result = client.modelPath("modelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.modelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchModelFromModelName', () => { - const result = client.matchModelFromModelName(fakePath); - assert.strictEqual(result, "modelValue"); - assert((client.pathTemplates.modelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes countTextTokens with closed client', async () => { + const client = new textserviceModule.v1beta3.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.ai.generativelanguage.v1beta3.CountTextTokensRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.ai.generativelanguage.v1beta3.CountTextTokensRequest', + ['model'], + ); + request.model = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.countTextTokens(request), expectedError); + }); + }); + + describe('Path templates', () => { + describe('model', async () => { + const fakePath = '/rendered/path/model'; + const expectedParameters = { + model: 'modelValue', + }; + const client = new textserviceModule.v1beta3.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.modelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.modelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('modelPath', () => { + const result = client.modelPath('modelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.modelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchModelFromModelName', () => { + const result = client.matchModelFromModelName(fakePath); + assert.strictEqual(result, 'modelValue'); + assert( + (client.pathTemplates.modelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('permission', async () => { - const fakePath = "/rendered/path/permission"; - const expectedParameters = { - tuned_model: "tunedModelValue", - permission: "permissionValue", - }; - const client = new textserviceModule.v1beta3.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.permissionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.permissionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('permissionPath', () => { - const result = client.permissionPath("tunedModelValue", "permissionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.permissionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromPermissionName', () => { - const result = client.matchTunedModelFromPermissionName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.permissionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchPermissionFromPermissionName', () => { - const result = client.matchPermissionFromPermissionName(fakePath); - assert.strictEqual(result, "permissionValue"); - assert((client.pathTemplates.permissionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('permission', async () => { + const fakePath = '/rendered/path/permission'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + permission: 'permissionValue', + }; + const client = new textserviceModule.v1beta3.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.permissionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.permissionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('permissionPath', () => { + const result = client.permissionPath( + 'tunedModelValue', + 'permissionValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.permissionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromPermissionName', () => { + const result = client.matchTunedModelFromPermissionName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.permissionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchPermissionFromPermissionName', () => { + const result = client.matchPermissionFromPermissionName(fakePath); + assert.strictEqual(result, 'permissionValue'); + assert( + (client.pathTemplates.permissionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('tunedModel', async () => { - const fakePath = "/rendered/path/tunedModel"; - const expectedParameters = { - tuned_model: "tunedModelValue", - }; - const client = new textserviceModule.v1beta3.TextServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.tunedModelPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.tunedModelPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('tunedModelPath', () => { - const result = client.tunedModelPath("tunedModelValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.tunedModelPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchTunedModelFromTunedModelName', () => { - const result = client.matchTunedModelFromTunedModelName(fakePath); - assert.strictEqual(result, "tunedModelValue"); - assert((client.pathTemplates.tunedModelPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('tunedModel', async () => { + const fakePath = '/rendered/path/tunedModel'; + const expectedParameters = { + tuned_model: 'tunedModelValue', + }; + const client = new textserviceModule.v1beta3.TextServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.tunedModelPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.tunedModelPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('tunedModelPath', () => { + const result = client.tunedModelPath('tunedModelValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.tunedModelPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchTunedModelFromTunedModelName', () => { + const result = client.matchTunedModelFromTunedModelName(fakePath); + assert.strictEqual(result, 'tunedModelValue'); + assert( + (client.pathTemplates.tunedModelPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-ai-generativelanguage/webpack.config.js b/packages/google-ai-generativelanguage/webpack.config.js index fda582397e43..85fa10ca3a1c 100644 --- a/packages/google-ai-generativelanguage/webpack.config.js +++ b/packages/google-ai-generativelanguage/webpack.config.js @@ -1,4 +1,4 @@ -// Copyright 2026 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/packages/google-analytics-admin/.eslintignore b/packages/google-analytics-admin/.eslintignore new file mode 100644 index 000000000000..cfc348ec4d11 --- /dev/null +++ b/packages/google-analytics-admin/.eslintignore @@ -0,0 +1,7 @@ +**/node_modules +**/.coverage +build/ +docs/ +protos/ +system-test/ +samples/generated/ diff --git a/packages/google-analytics-admin/.eslintrc.json b/packages/google-analytics-admin/.eslintrc.json new file mode 100644 index 000000000000..3e8d97ccb390 --- /dev/null +++ b/packages/google-analytics-admin/.eslintrc.json @@ -0,0 +1,4 @@ +{ + "extends": "./node_modules/gts", + "root": true +} diff --git a/packages/google-analytics-admin/README.md b/packages/google-analytics-admin/README.md index 3a395c9b7c09..d1e8c78de39f 100644 --- a/packages/google-analytics-admin/README.md +++ b/packages/google-analytics-admin/README.md @@ -301,7 +301,7 @@ More Information: [Google Cloud Platform Launch Stages][launch_stages] ## Contributing -Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-analytics-admin/CONTRIBUTING.md). +Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/google-cloud-node/blob/main/CONTRIBUTING.md). Please note that this `README.md` and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`) @@ -311,7 +311,7 @@ are generated from a central template. Apache Version 2.0 -See [LICENSE](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-analytics-admin/LICENSE) +See [LICENSE](https://github.com/googleapis/google-cloud-node/blob/main/LICENSE) [shell_img]: https://gstatic.com/cloudssh/images/open-btn.png [projects]: https://console.cloud.google.com/project diff --git a/packages/google-analytics-admin/protos/protos.d.ts b/packages/google-analytics-admin/protos/protos.d.ts index 816163f86ca9..532faeeb5e9e 100644 --- a/packages/google-analytics-admin/protos/protos.d.ts +++ b/packages/google-analytics-admin/protos/protos.d.ts @@ -49709,6 +49709,9 @@ export namespace google { /** CommonLanguageSettings destinations */ destinations?: (google.api.ClientLibraryDestination[]|null); + + /** CommonLanguageSettings selectiveGapicGeneration */ + selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); } /** Represents a CommonLanguageSettings. */ @@ -49726,6 +49729,9 @@ export namespace google { /** CommonLanguageSettings destinations. */ public destinations: google.api.ClientLibraryDestination[]; + /** CommonLanguageSettings selectiveGapicGeneration. */ + public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + /** * Creates a new CommonLanguageSettings instance using the specified properties. * @param [properties] Properties to set @@ -50426,6 +50432,9 @@ export namespace google { /** PythonSettings common */ common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures */ + experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); } /** Represents a PythonSettings. */ @@ -50440,6 +50449,9 @@ export namespace google { /** PythonSettings common. */ public common?: (google.api.ICommonLanguageSettings|null); + /** PythonSettings experimentalFeatures. */ + public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + /** * Creates a new PythonSettings instance using the specified properties. * @param [properties] Properties to set @@ -50518,6 +50530,118 @@ 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); + + /** ExperimentalFeatures unversionedPackageDisabled */ + unversionedPackageDisabled?: (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; + + /** ExperimentalFeatures unversionedPackageDisabled. */ + public unversionedPackageDisabled: boolean; + + /** + * Creates a new ExperimentalFeatures instance using the specified properties. + * @param [properties] Properties to set + * @returns ExperimentalFeatures instance + */ + public static create(properties?: google.api.PythonSettings.IExperimentalFeatures): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Encodes the specified ExperimentalFeatures message. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @param message ExperimentalFeatures message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.PythonSettings.IExperimentalFeatures, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExperimentalFeatures message, length delimited. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @param message ExperimentalFeatures message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.PythonSettings.IExperimentalFeatures, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Verifies an ExperimentalFeatures message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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 { @@ -50844,6 +50968,9 @@ export namespace google { /** GoSettings common */ common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); } /** Represents a GoSettings. */ @@ -50858,6 +50985,9 @@ export namespace google { /** GoSettings common. */ public common?: (google.api.ICommonLanguageSettings|null); + /** GoSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + /** * Creates a new GoSettings instance using the specified properties. * @param [properties] Properties to set @@ -51182,6 +51312,109 @@ export namespace google { PACKAGE_MANAGER = 20 } + /** 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 new SelectiveGapicGeneration instance using the specified properties. + * @param [properties] Properties to set + * @returns SelectiveGapicGeneration instance + */ + public static create(properties?: google.api.ISelectiveGapicGeneration): google.api.SelectiveGapicGeneration; + + /** + * Encodes the specified SelectiveGapicGeneration message. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @param message SelectiveGapicGeneration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.ISelectiveGapicGeneration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SelectiveGapicGeneration message, length delimited. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @param message SelectiveGapicGeneration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.ISelectiveGapicGeneration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.SelectiveGapicGeneration; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.SelectiveGapicGeneration; + + /** + * Verifies a SelectiveGapicGeneration message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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. */ enum LaunchStage { LAUNCH_STAGE_UNSPECIFIED = 0, @@ -51298,6 +51531,7 @@ export namespace google { /** Edition enum. */ enum Edition { EDITION_UNKNOWN = 0, + EDITION_LEGACY = 900, EDITION_PROTO2 = 998, EDITION_PROTO3 = 999, EDITION_2023 = 1000, @@ -51328,6 +51562,9 @@ export namespace google { /** FileDescriptorProto weakDependency */ weakDependency?: (number[]|null); + /** FileDescriptorProto optionDependency */ + optionDependency?: (string[]|null); + /** FileDescriptorProto messageType */ messageType?: (google.protobuf.IDescriptorProto[]|null); @@ -51377,6 +51614,9 @@ export namespace google { /** FileDescriptorProto weakDependency. */ public weakDependency: number[]; + /** FileDescriptorProto optionDependency. */ + public optionDependency: string[]; + /** FileDescriptorProto messageType. */ public messageType: google.protobuf.IDescriptorProto[]; @@ -51511,6 +51751,9 @@ export namespace google { /** DescriptorProto reservedName */ reservedName?: (string[]|null); + + /** DescriptorProto visibility */ + visibility?: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility|null); } /** Represents a DescriptorProto. */ @@ -51552,6 +51795,9 @@ export namespace google { /** DescriptorProto reservedName. */ public reservedName: string[]; + /** DescriptorProto visibility. */ + public visibility: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility); + /** * Creates a new DescriptorProto instance using the specified properties. * @param [properties] Properties to set @@ -52399,6 +52645,9 @@ export namespace google { /** EnumDescriptorProto reservedName */ reservedName?: (string[]|null); + + /** EnumDescriptorProto visibility */ + visibility?: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility|null); } /** Represents an EnumDescriptorProto. */ @@ -52425,6 +52674,9 @@ export namespace google { /** EnumDescriptorProto reservedName. */ public reservedName: string[]; + /** EnumDescriptorProto visibility. */ + public visibility: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility); + /** * Creates a new EnumDescriptorProto instance using the specified properties. * @param [properties] Properties to set @@ -53359,6 +53611,9 @@ 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); @@ -53414,6 +53669,9 @@ 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[]; @@ -53634,6 +53892,121 @@ export namespace google { */ public static getTypeUrl(typeUrlPrefix?: string): string; } + + /** Properties of a FeatureSupport. */ + interface IFeatureSupport { + + /** FeatureSupport editionIntroduced */ + editionIntroduced?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + + /** FeatureSupport editionDeprecated */ + editionDeprecated?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + + /** FeatureSupport deprecationWarning */ + deprecationWarning?: (string|null); + + /** FeatureSupport editionRemoved */ + editionRemoved?: (google.protobuf.Edition|keyof typeof 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|keyof typeof google.protobuf.Edition); + + /** FeatureSupport editionDeprecated. */ + public editionDeprecated: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** FeatureSupport deprecationWarning. */ + public deprecationWarning: string; + + /** FeatureSupport editionRemoved. */ + public editionRemoved: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** + * Creates a new FeatureSupport instance using the specified properties. + * @param [properties] Properties to set + * @returns FeatureSupport instance + */ + public static create(properties?: google.protobuf.FieldOptions.IFeatureSupport): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Encodes the specified FeatureSupport message. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @param message FeatureSupport message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.FieldOptions.IFeatureSupport, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FeatureSupport message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @param message FeatureSupport message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.FieldOptions.IFeatureSupport, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Verifies a FeatureSupport message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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. */ @@ -53872,6 +54245,9 @@ export namespace google { /** EnumValueOptions debugRedact */ debugRedact?: (boolean|null); + /** EnumValueOptions featureSupport */ + featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); + /** EnumValueOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } @@ -53894,6 +54270,9 @@ export namespace google { /** EnumValueOptions debugRedact. */ public debugRedact: boolean; + /** EnumValueOptions featureSupport. */ + public featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); + /** EnumValueOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -54483,6 +54862,12 @@ export namespace google { /** FeatureSet jsonFormat */ jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|keyof typeof google.protobuf.FeatureSet.JsonFormat|null); + + /** FeatureSet enforceNamingStyle */ + enforceNamingStyle?: (google.protobuf.FeatureSet.EnforceNamingStyle|keyof typeof google.protobuf.FeatureSet.EnforceNamingStyle|null); + + /** FeatureSet defaultSymbolVisibility */ + defaultSymbolVisibility?: (google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|keyof typeof google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|null); } /** Represents a FeatureSet. */ @@ -54512,6 +54897,12 @@ export namespace google { /** FeatureSet jsonFormat. */ public jsonFormat: (google.protobuf.FeatureSet.JsonFormat|keyof typeof google.protobuf.FeatureSet.JsonFormat); + /** FeatureSet enforceNamingStyle. */ + public enforceNamingStyle: (google.protobuf.FeatureSet.EnforceNamingStyle|keyof typeof google.protobuf.FeatureSet.EnforceNamingStyle); + + /** FeatureSet defaultSymbolVisibility. */ + public defaultSymbolVisibility: (google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|keyof typeof google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility); + /** * Creates a new FeatureSet instance using the specified properties. * @param [properties] Properties to set @@ -54634,6 +55025,116 @@ export namespace google { ALLOW = 1, LEGACY_BEST_EFFORT = 2 } + + /** EnforceNamingStyle enum. */ + enum EnforceNamingStyle { + ENFORCE_NAMING_STYLE_UNKNOWN = 0, + STYLE2024 = 1, + STYLE_LEGACY = 2 + } + + /** Properties of a VisibilityFeature. */ + interface IVisibilityFeature { + } + + /** Represents a VisibilityFeature. */ + class VisibilityFeature implements IVisibilityFeature { + + /** + * Constructs a new VisibilityFeature. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FeatureSet.IVisibilityFeature); + + /** + * Creates a new VisibilityFeature instance using the specified properties. + * @param [properties] Properties to set + * @returns VisibilityFeature instance + */ + public static create(properties?: google.protobuf.FeatureSet.IVisibilityFeature): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Encodes the specified VisibilityFeature message. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @param message VisibilityFeature message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.FeatureSet.IVisibilityFeature, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified VisibilityFeature message, length delimited. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @param message VisibilityFeature message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.FeatureSet.IVisibilityFeature, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Verifies a VisibilityFeature message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a VisibilityFeature message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns VisibilityFeature + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Creates a plain object from a VisibilityFeature message. Also converts values to other types if specified. + * @param message VisibilityFeature + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet.VisibilityFeature, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this VisibilityFeature to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for VisibilityFeature + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace VisibilityFeature { + + /** DefaultSymbolVisibility enum. */ + enum DefaultSymbolVisibility { + DEFAULT_SYMBOL_VISIBILITY_UNKNOWN = 0, + EXPORT_ALL = 1, + EXPORT_TOP_LEVEL = 2, + LOCAL_ALL = 3, + STRICT = 4 + } + } } /** Properties of a FeatureSetDefaults. */ @@ -54753,8 +55254,11 @@ export namespace google { /** FeatureSetEditionDefault edition */ edition?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); - /** FeatureSetEditionDefault features */ - features?: (google.protobuf.IFeatureSet|null); + /** FeatureSetEditionDefault overridableFeatures */ + overridableFeatures?: (google.protobuf.IFeatureSet|null); + + /** FeatureSetEditionDefault fixedFeatures */ + fixedFeatures?: (google.protobuf.IFeatureSet|null); } /** Represents a FeatureSetEditionDefault. */ @@ -54769,8 +55273,11 @@ export namespace google { /** FeatureSetEditionDefault edition. */ public edition: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); - /** FeatureSetEditionDefault features. */ - public features?: (google.protobuf.IFeatureSet|null); + /** FeatureSetEditionDefault overridableFeatures. */ + public overridableFeatures?: (google.protobuf.IFeatureSet|null); + + /** FeatureSetEditionDefault fixedFeatures. */ + public fixedFeatures?: (google.protobuf.IFeatureSet|null); /** * Creates a new FeatureSetEditionDefault instance using the specified properties. @@ -55303,6 +55810,13 @@ export namespace google { } } + /** SymbolVisibility enum. */ + enum SymbolVisibility { + VISIBILITY_UNSET = 0, + VISIBILITY_LOCAL = 1, + VISIBILITY_EXPORT = 2 + } + /** Properties of a Duration. */ interface IDuration { diff --git a/packages/google-analytics-admin/protos/protos.js b/packages/google-analytics-admin/protos/protos.js index 7a73bd7c7215..2a648353a808 100644 --- a/packages/google-analytics-admin/protos/protos.js +++ b/packages/google-analytics-admin/protos/protos.js @@ -117540,6 +117540,7 @@ * @interface ICommonLanguageSettings * @property {string|null} [referenceDocsUri] CommonLanguageSettings referenceDocsUri * @property {Array.|null} [destinations] CommonLanguageSettings destinations + * @property {google.api.ISelectiveGapicGeneration|null} [selectiveGapicGeneration] CommonLanguageSettings selectiveGapicGeneration */ /** @@ -117574,6 +117575,14 @@ */ 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 new CommonLanguageSettings instance using the specified properties. * @function create @@ -117606,6 +117615,8 @@ writer.int32(message.destinations[i]); writer.ldelim(); } + if (message.selectiveGapicGeneration != null && Object.hasOwnProperty.call(message, "selectiveGapicGeneration")) + $root.google.api.SelectiveGapicGeneration.encode(message.selectiveGapicGeneration, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); return writer; }; @@ -117657,6 +117668,10 @@ message.destinations.push(reader.int32()); break; } + case 3: { + message.selectiveGapicGeneration = $root.google.api.SelectiveGapicGeneration.decode(reader, reader.uint32()); + break; + } default: reader.skipType(tag & 7); break; @@ -117708,6 +117723,11 @@ break; } } + if (message.selectiveGapicGeneration != null && message.hasOwnProperty("selectiveGapicGeneration")) { + var error = $root.google.api.SelectiveGapicGeneration.verify(message.selectiveGapicGeneration); + if (error) + return "selectiveGapicGeneration." + error; + } return null; }; @@ -117750,6 +117770,11 @@ 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; }; @@ -117768,8 +117793,10 @@ 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) { @@ -117777,6 +117804,8 @@ 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; }; @@ -119599,6 +119628,7 @@ * @memberof google.api * @interface IPythonSettings * @property {google.api.ICommonLanguageSettings|null} [common] PythonSettings common + * @property {google.api.PythonSettings.IExperimentalFeatures|null} [experimentalFeatures] PythonSettings experimentalFeatures */ /** @@ -119624,6 +119654,14 @@ */ 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 new PythonSettings instance using the specified properties. * @function create @@ -119650,6 +119688,8 @@ writer = $Writer.create(); if (message.common != null && Object.hasOwnProperty.call(message, "common")) $root.google.api.CommonLanguageSettings.encode(message.common, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.experimentalFeatures != null && Object.hasOwnProperty.call(message, "experimentalFeatures")) + $root.google.api.PythonSettings.ExperimentalFeatures.encode(message.experimentalFeatures, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); return writer; }; @@ -119690,6 +119730,10 @@ message.common = $root.google.api.CommonLanguageSettings.decode(reader, reader.uint32()); break; } + case 2: { + message.experimentalFeatures = $root.google.api.PythonSettings.ExperimentalFeatures.decode(reader, reader.uint32()); + break; + } default: reader.skipType(tag & 7); break; @@ -119730,6 +119774,11 @@ if (error) return "common." + error; } + if (message.experimentalFeatures != null && message.hasOwnProperty("experimentalFeatures")) { + var error = $root.google.api.PythonSettings.ExperimentalFeatures.verify(message.experimentalFeatures); + if (error) + return "experimentalFeatures." + error; + } return null; }; @@ -119750,6 +119799,11 @@ 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; }; @@ -119766,10 +119820,14 @@ 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; }; @@ -119799,6 +119857,258 @@ 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 + * @property {boolean|null} [unversionedPackageDisabled] ExperimentalFeatures unversionedPackageDisabled + */ + + /** + * 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; + + /** + * ExperimentalFeatures unversionedPackageDisabled. + * @member {boolean} unversionedPackageDisabled + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @instance + */ + ExperimentalFeatures.prototype.unversionedPackageDisabled = false; + + /** + * Creates a new ExperimentalFeatures instance using the specified properties. + * @function create + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures=} [properties] Properties to set + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures instance + */ + ExperimentalFeatures.create = function create(properties) { + return new ExperimentalFeatures(properties); + }; + + /** + * Encodes the specified ExperimentalFeatures message. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @function encode + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures} message ExperimentalFeatures message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExperimentalFeatures.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.restAsyncIoEnabled != null && Object.hasOwnProperty.call(message, "restAsyncIoEnabled")) + writer.uint32(/* id 1, wireType 0 =*/8).bool(message.restAsyncIoEnabled); + if (message.protobufPythonicTypesEnabled != null && Object.hasOwnProperty.call(message, "protobufPythonicTypesEnabled")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.protobufPythonicTypesEnabled); + if (message.unversionedPackageDisabled != null && Object.hasOwnProperty.call(message, "unversionedPackageDisabled")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.unversionedPackageDisabled); + return writer; + }; + + /** + * Encodes the specified ExperimentalFeatures message, length delimited. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures} message ExperimentalFeatures message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExperimentalFeatures.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer. + * @function decode + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExperimentalFeatures.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.PythonSettings.ExperimentalFeatures(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.restAsyncIoEnabled = reader.bool(); + break; + } + case 2: { + message.protobufPythonicTypesEnabled = reader.bool(); + break; + } + case 3: { + message.unversionedPackageDisabled = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExperimentalFeatures.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ExperimentalFeatures message. + * @function verify + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExperimentalFeatures.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.restAsyncIoEnabled != null && message.hasOwnProperty("restAsyncIoEnabled")) + if (typeof message.restAsyncIoEnabled !== "boolean") + return "restAsyncIoEnabled: boolean expected"; + if (message.protobufPythonicTypesEnabled != null && message.hasOwnProperty("protobufPythonicTypesEnabled")) + if (typeof message.protobufPythonicTypesEnabled !== "boolean") + return "protobufPythonicTypesEnabled: boolean expected"; + if (message.unversionedPackageDisabled != null && message.hasOwnProperty("unversionedPackageDisabled")) + if (typeof message.unversionedPackageDisabled !== "boolean") + return "unversionedPackageDisabled: boolean expected"; + return null; + }; + + /** + * 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); + if (object.unversionedPackageDisabled != null) + message.unversionedPackageDisabled = Boolean(object.unversionedPackageDisabled); + 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; + object.unversionedPackageDisabled = false; + } + if (message.restAsyncIoEnabled != null && message.hasOwnProperty("restAsyncIoEnabled")) + object.restAsyncIoEnabled = message.restAsyncIoEnabled; + if (message.protobufPythonicTypesEnabled != null && message.hasOwnProperty("protobufPythonicTypesEnabled")) + object.protobufPythonicTypesEnabled = message.protobufPythonicTypesEnabled; + if (message.unversionedPackageDisabled != null && message.hasOwnProperty("unversionedPackageDisabled")) + object.unversionedPackageDisabled = message.unversionedPackageDisabled; + 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; })(); @@ -120675,6 +120985,7 @@ * @memberof google.api * @interface IGoSettings * @property {google.api.ICommonLanguageSettings|null} [common] GoSettings common + * @property {Object.|null} [renamedServices] GoSettings renamedServices */ /** @@ -120686,6 +120997,7 @@ * @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) @@ -120700,6 +121012,14 @@ */ GoSettings.prototype.common = null; + /** + * GoSettings renamedServices. + * @member {Object.} renamedServices + * @memberof google.api.GoSettings + * @instance + */ + GoSettings.prototype.renamedServices = $util.emptyObject; + /** * Creates a new GoSettings instance using the specified properties. * @function create @@ -120726,6 +121046,9 @@ writer = $Writer.create(); if (message.common != null && Object.hasOwnProperty.call(message, "common")) $root.google.api.CommonLanguageSettings.encode(message.common, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.renamedServices != null && Object.hasOwnProperty.call(message, "renamedServices")) + for (var keys = Object.keys(message.renamedServices), i = 0; i < keys.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.renamedServices[keys[i]]).ldelim(); return writer; }; @@ -120756,7 +121079,7 @@ GoSettings.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.GoSettings(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.GoSettings(), key, value; while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -120766,6 +121089,29 @@ message.common = $root.google.api.CommonLanguageSettings.decode(reader, reader.uint32()); break; } + case 2: { + if (message.renamedServices === $util.emptyObject) + message.renamedServices = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.renamedServices[key] = value; + break; + } default: reader.skipType(tag & 7); break; @@ -120806,6 +121152,14 @@ if (error) return "common." + error; } + if (message.renamedServices != null && message.hasOwnProperty("renamedServices")) { + if (!$util.isObject(message.renamedServices)) + return "renamedServices: object expected"; + var key = Object.keys(message.renamedServices); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.renamedServices[key[i]])) + return "renamedServices: string{k:string} expected"; + } return null; }; @@ -120826,6 +121180,13 @@ 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; }; @@ -120842,10 +121203,18 @@ 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; }; @@ -121484,30 +121853,275 @@ return values; })(); - /** - * LaunchStage enum. - * @name google.api.LaunchStage - * @enum {number} - * @property {number} LAUNCH_STAGE_UNSPECIFIED=0 LAUNCH_STAGE_UNSPECIFIED value - * @property {number} UNIMPLEMENTED=6 UNIMPLEMENTED value - * @property {number} PRELAUNCH=7 PRELAUNCH value - * @property {number} EARLY_ACCESS=1 EARLY_ACCESS value - * @property {number} ALPHA=2 ALPHA value - * @property {number} BETA=3 BETA value - * @property {number} GA=4 GA value - * @property {number} DEPRECATED=5 DEPRECATED value - */ - api.LaunchStage = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "LAUNCH_STAGE_UNSPECIFIED"] = 0; - values[valuesById[6] = "UNIMPLEMENTED"] = 6; - values[valuesById[7] = "PRELAUNCH"] = 7; - values[valuesById[1] = "EARLY_ACCESS"] = 1; - values[valuesById[2] = "ALPHA"] = 2; - values[valuesById[3] = "BETA"] = 3; - values[valuesById[4] = "GA"] = 4; - values[valuesById[5] = "DEPRECATED"] = 5; - 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 new SelectiveGapicGeneration instance using the specified properties. + * @function create + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration=} [properties] Properties to set + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration instance + */ + SelectiveGapicGeneration.create = function create(properties) { + return new SelectiveGapicGeneration(properties); + }; + + /** + * Encodes the specified SelectiveGapicGeneration message. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @function encode + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration} message SelectiveGapicGeneration message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SelectiveGapicGeneration.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.methods != null && message.methods.length) + for (var i = 0; i < message.methods.length; ++i) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.methods[i]); + if (message.generateOmittedAsInternal != null && Object.hasOwnProperty.call(message, "generateOmittedAsInternal")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.generateOmittedAsInternal); + return writer; + }; + + /** + * Encodes the specified SelectiveGapicGeneration message, length delimited. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration} message SelectiveGapicGeneration message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SelectiveGapicGeneration.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer. + * @function decode + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SelectiveGapicGeneration.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.SelectiveGapicGeneration(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.methods && message.methods.length)) + message.methods = []; + message.methods.push(reader.string()); + break; + } + case 2: { + message.generateOmittedAsInternal = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SelectiveGapicGeneration.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SelectiveGapicGeneration message. + * @function verify + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SelectiveGapicGeneration.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.methods != null && message.hasOwnProperty("methods")) { + if (!Array.isArray(message.methods)) + return "methods: array expected"; + for (var i = 0; i < message.methods.length; ++i) + if (!$util.isString(message.methods[i])) + return "methods: string[] expected"; + } + if (message.generateOmittedAsInternal != null && message.hasOwnProperty("generateOmittedAsInternal")) + if (typeof message.generateOmittedAsInternal !== "boolean") + return "generateOmittedAsInternal: boolean expected"; + return null; + }; + + /** + * 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 + * @enum {number} + * @property {number} LAUNCH_STAGE_UNSPECIFIED=0 LAUNCH_STAGE_UNSPECIFIED value + * @property {number} UNIMPLEMENTED=6 UNIMPLEMENTED value + * @property {number} PRELAUNCH=7 PRELAUNCH value + * @property {number} EARLY_ACCESS=1 EARLY_ACCESS value + * @property {number} ALPHA=2 ALPHA value + * @property {number} BETA=3 BETA value + * @property {number} GA=4 GA value + * @property {number} DEPRECATED=5 DEPRECATED value + */ + api.LaunchStage = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "LAUNCH_STAGE_UNSPECIFIED"] = 0; + values[valuesById[6] = "UNIMPLEMENTED"] = 6; + values[valuesById[7] = "PRELAUNCH"] = 7; + values[valuesById[1] = "EARLY_ACCESS"] = 1; + values[valuesById[2] = "ALPHA"] = 2; + values[valuesById[3] = "BETA"] = 3; + values[valuesById[4] = "GA"] = 4; + values[valuesById[5] = "DEPRECATED"] = 5; + return values; })(); return api; @@ -121753,6 +122367,7 @@ * @name google.protobuf.Edition * @enum {number} * @property {number} EDITION_UNKNOWN=0 EDITION_UNKNOWN value + * @property {number} EDITION_LEGACY=900 EDITION_LEGACY value * @property {number} EDITION_PROTO2=998 EDITION_PROTO2 value * @property {number} EDITION_PROTO3=999 EDITION_PROTO3 value * @property {number} EDITION_2023=1000 EDITION_2023 value @@ -121767,6 +122382,7 @@ protobuf.Edition = (function() { var valuesById = {}, values = Object.create(valuesById); values[valuesById[0] = "EDITION_UNKNOWN"] = 0; + values[valuesById[900] = "EDITION_LEGACY"] = 900; values[valuesById[998] = "EDITION_PROTO2"] = 998; values[valuesById[999] = "EDITION_PROTO3"] = 999; values[valuesById[1000] = "EDITION_2023"] = 1000; @@ -121791,6 +122407,7 @@ * @property {Array.|null} [dependency] FileDescriptorProto dependency * @property {Array.|null} [publicDependency] FileDescriptorProto publicDependency * @property {Array.|null} [weakDependency] FileDescriptorProto weakDependency + * @property {Array.|null} [optionDependency] FileDescriptorProto optionDependency * @property {Array.|null} [messageType] FileDescriptorProto messageType * @property {Array.|null} [enumType] FileDescriptorProto enumType * @property {Array.|null} [service] FileDescriptorProto service @@ -121813,6 +122430,7 @@ this.dependency = []; this.publicDependency = []; this.weakDependency = []; + this.optionDependency = []; this.messageType = []; this.enumType = []; this.service = []; @@ -121863,6 +122481,14 @@ */ FileDescriptorProto.prototype.weakDependency = $util.emptyArray; + /** + * FileDescriptorProto optionDependency. + * @member {Array.} optionDependency + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.optionDependency = $util.emptyArray; + /** * FileDescriptorProto messageType. * @member {Array.} messageType @@ -121984,6 +122610,9 @@ writer.uint32(/* id 12, wireType 2 =*/98).string(message.syntax); if (message.edition != null && Object.hasOwnProperty.call(message, "edition")) writer.uint32(/* id 14, wireType 0 =*/112).int32(message.edition); + if (message.optionDependency != null && message.optionDependency.length) + for (var i = 0; i < message.optionDependency.length; ++i) + writer.uint32(/* id 15, wireType 2 =*/122).string(message.optionDependency[i]); return writer; }; @@ -122056,6 +122685,12 @@ message.weakDependency.push(reader.int32()); break; } + case 15: { + if (!(message.optionDependency && message.optionDependency.length)) + message.optionDependency = []; + message.optionDependency.push(reader.string()); + break; + } case 4: { if (!(message.messageType && message.messageType.length)) message.messageType = []; @@ -122158,6 +122793,13 @@ if (!$util.isInteger(message.weakDependency[i])) return "weakDependency: integer[] expected"; } + if (message.optionDependency != null && message.hasOwnProperty("optionDependency")) { + if (!Array.isArray(message.optionDependency)) + return "optionDependency: array expected"; + for (var i = 0; i < message.optionDependency.length; ++i) + if (!$util.isString(message.optionDependency[i])) + return "optionDependency: string[] expected"; + } if (message.messageType != null && message.hasOwnProperty("messageType")) { if (!Array.isArray(message.messageType)) return "messageType: array expected"; @@ -122212,6 +122854,7 @@ default: return "edition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -122264,6 +122907,13 @@ for (var i = 0; i < object.weakDependency.length; ++i) message.weakDependency[i] = object.weakDependency[i] | 0; } + if (object.optionDependency) { + if (!Array.isArray(object.optionDependency)) + throw TypeError(".google.protobuf.FileDescriptorProto.optionDependency: array expected"); + message.optionDependency = []; + for (var i = 0; i < object.optionDependency.length; ++i) + message.optionDependency[i] = String(object.optionDependency[i]); + } if (object.messageType) { if (!Array.isArray(object.messageType)) throw TypeError(".google.protobuf.FileDescriptorProto.messageType: array expected"); @@ -122327,6 +122977,10 @@ case 0: message.edition = 0; break; + case "EDITION_LEGACY": + case 900: + message.edition = 900; + break; case "EDITION_PROTO2": case 998: message.edition = 998; @@ -122392,6 +123046,7 @@ object.extension = []; object.publicDependency = []; object.weakDependency = []; + object.optionDependency = []; } if (options.defaults) { object.name = ""; @@ -122448,6 +123103,11 @@ 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; + if (message.optionDependency && message.optionDependency.length) { + object.optionDependency = []; + for (var j = 0; j < message.optionDependency.length; ++j) + object.optionDependency[j] = message.optionDependency[j]; + } return object; }; @@ -122496,6 +123156,7 @@ * @property {google.protobuf.IMessageOptions|null} [options] DescriptorProto options * @property {Array.|null} [reservedRange] DescriptorProto reservedRange * @property {Array.|null} [reservedName] DescriptorProto reservedName + * @property {google.protobuf.SymbolVisibility|null} [visibility] DescriptorProto visibility */ /** @@ -122601,6 +123262,14 @@ */ DescriptorProto.prototype.reservedName = $util.emptyArray; + /** + * DescriptorProto visibility. + * @member {google.protobuf.SymbolVisibility} visibility + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.visibility = 0; + /** * Creates a new DescriptorProto instance using the specified properties. * @function create @@ -122653,6 +123322,8 @@ if (message.reservedName != null && message.reservedName.length) for (var i = 0; i < message.reservedName.length; ++i) writer.uint32(/* id 10, wireType 2 =*/82).string(message.reservedName[i]); + if (message.visibility != null && Object.hasOwnProperty.call(message, "visibility")) + writer.uint32(/* id 11, wireType 0 =*/88).int32(message.visibility); return writer; }; @@ -122745,6 +123416,10 @@ message.reservedName.push(reader.string()); break; } + case 11: { + message.visibility = reader.int32(); + break; + } default: reader.skipType(tag & 7); break; @@ -122858,6 +123533,15 @@ if (!$util.isString(message.reservedName[i])) return "reservedName: string[] expected"; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + switch (message.visibility) { + default: + return "visibility: enum value expected"; + case 0: + case 1: + case 2: + break; + } return null; }; @@ -122957,6 +123641,26 @@ for (var i = 0; i < object.reservedName.length; ++i) message.reservedName[i] = String(object.reservedName[i]); } + switch (object.visibility) { + default: + if (typeof object.visibility === "number") { + message.visibility = object.visibility; + break; + } + break; + case "VISIBILITY_UNSET": + case 0: + message.visibility = 0; + break; + case "VISIBILITY_LOCAL": + case 1: + message.visibility = 1; + break; + case "VISIBILITY_EXPORT": + case 2: + message.visibility = 2; + break; + } return message; }; @@ -122986,6 +123690,7 @@ if (options.defaults) { object.name = ""; object.options = null; + object.visibility = options.enums === String ? "VISIBILITY_UNSET" : 0; } if (message.name != null && message.hasOwnProperty("name")) object.name = message.name; @@ -123031,6 +123736,8 @@ for (var j = 0; j < message.reservedName.length; ++j) object.reservedName[j] = message.reservedName[j]; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + object.visibility = options.enums === String ? $root.google.protobuf.SymbolVisibility[message.visibility] === undefined ? message.visibility : $root.google.protobuf.SymbolVisibility[message.visibility] : message.visibility; return object; }; @@ -125075,6 +125782,7 @@ * @property {google.protobuf.IEnumOptions|null} [options] EnumDescriptorProto options * @property {Array.|null} [reservedRange] EnumDescriptorProto reservedRange * @property {Array.|null} [reservedName] EnumDescriptorProto reservedName + * @property {google.protobuf.SymbolVisibility|null} [visibility] EnumDescriptorProto visibility */ /** @@ -125135,6 +125843,14 @@ */ EnumDescriptorProto.prototype.reservedName = $util.emptyArray; + /** + * EnumDescriptorProto visibility. + * @member {google.protobuf.SymbolVisibility} visibility + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.visibility = 0; + /** * Creates a new EnumDescriptorProto instance using the specified properties. * @function create @@ -125172,6 +125888,8 @@ if (message.reservedName != null && message.reservedName.length) for (var i = 0; i < message.reservedName.length; ++i) writer.uint32(/* id 5, wireType 2 =*/42).string(message.reservedName[i]); + if (message.visibility != null && Object.hasOwnProperty.call(message, "visibility")) + writer.uint32(/* id 6, wireType 0 =*/48).int32(message.visibility); return writer; }; @@ -125234,6 +125952,10 @@ message.reservedName.push(reader.string()); break; } + case 6: { + message.visibility = reader.int32(); + break; + } default: reader.skipType(tag & 7); break; @@ -125302,6 +126024,15 @@ if (!$util.isString(message.reservedName[i])) return "reservedName: string[] expected"; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + switch (message.visibility) { + default: + return "visibility: enum value expected"; + case 0: + case 1: + case 2: + break; + } return null; }; @@ -125351,6 +126082,26 @@ for (var i = 0; i < object.reservedName.length; ++i) message.reservedName[i] = String(object.reservedName[i]); } + switch (object.visibility) { + default: + if (typeof object.visibility === "number") { + message.visibility = object.visibility; + break; + } + break; + case "VISIBILITY_UNSET": + case 0: + message.visibility = 0; + break; + case "VISIBILITY_LOCAL": + case 1: + message.visibility = 1; + break; + case "VISIBILITY_EXPORT": + case 2: + message.visibility = 2; + break; + } return message; }; @@ -125375,6 +126126,7 @@ if (options.defaults) { object.name = ""; object.options = null; + object.visibility = options.enums === String ? "VISIBILITY_UNSET" : 0; } if (message.name != null && message.hasOwnProperty("name")) object.name = message.name; @@ -125395,6 +126147,8 @@ for (var j = 0; j < message.reservedName.length; ++j) object.reservedName[j] = message.reservedName[j]; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + object.visibility = options.enums === String ? $root.google.protobuf.SymbolVisibility[message.visibility] === undefined ? message.visibility : $root.google.protobuf.SymbolVisibility[message.visibility] : message.visibility; return object; }; @@ -127713,6 +128467,7 @@ * @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 @@ -127833,6 +128588,14 @@ */ 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 @@ -127907,6 +128670,8 @@ $root.google.protobuf.FieldOptions.EditionDefault.encode(message.editionDefaults[i], writer.uint32(/* id 20, wireType 2 =*/162).fork()).ldelim(); if (message.features != null && Object.hasOwnProperty.call(message, "features")) $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 21, wireType 2 =*/170).fork()).ldelim(); + if (message.featureSupport != null && Object.hasOwnProperty.call(message, "featureSupport")) + $root.google.protobuf.FieldOptions.FeatureSupport.encode(message.featureSupport, writer.uint32(/* id 22, wireType 2 =*/178).fork()).ldelim(); if (message.uninterpretedOption != null && message.uninterpretedOption.length) for (var i = 0; i < message.uninterpretedOption.length; ++i) $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); @@ -128008,6 +128773,10 @@ message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); break; } + case 22: { + message.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.decode(reader, reader.uint32()); + break; + } case 999: { if (!(message.uninterpretedOption && message.uninterpretedOption.length)) message.uninterpretedOption = []; @@ -128143,6 +128912,11 @@ if (error) return "features." + error; } + if (message.featureSupport != null && message.hasOwnProperty("featureSupport")) { + var error = $root.google.protobuf.FieldOptions.FeatureSupport.verify(message.featureSupport); + if (error) + return "featureSupport." + error; + } if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { if (!Array.isArray(message.uninterpretedOption)) return "uninterpretedOption: array expected"; @@ -128331,6 +129105,11 @@ 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"); @@ -128428,6 +129207,7 @@ 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")) @@ -128460,6 +129240,8 @@ } 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) @@ -128732,6 +129514,7 @@ default: return "edition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -128773,103 +129556,589 @@ 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; + 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 EditionDefault message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {google.protobuf.FieldOptions.EditionDefault} message EditionDefault + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EditionDefault.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.value = ""; + object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; + } + 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 EditionDefault to JSON. + * @function toJSON + * @memberof google.protobuf.FieldOptions.EditionDefault + * @instance + * @returns {Object.} JSON object + */ + EditionDefault.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * 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; + })(); + + 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 new FeatureSupport instance using the specified properties. + * @function create + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport=} [properties] Properties to set + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport instance + */ + FeatureSupport.create = function create(properties) { + return new FeatureSupport(properties); + }; + + /** + * Encodes the specified FeatureSupport message. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport} message FeatureSupport message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FeatureSupport.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.editionIntroduced != null && Object.hasOwnProperty.call(message, "editionIntroduced")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.editionIntroduced); + if (message.editionDeprecated != null && Object.hasOwnProperty.call(message, "editionDeprecated")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.editionDeprecated); + if (message.deprecationWarning != null && Object.hasOwnProperty.call(message, "deprecationWarning")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.deprecationWarning); + if (message.editionRemoved != null && Object.hasOwnProperty.call(message, "editionRemoved")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.editionRemoved); + return writer; + }; + + /** + * Encodes the specified FeatureSupport message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport} message FeatureSupport message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FeatureSupport.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FeatureSupport.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FieldOptions.FeatureSupport(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.editionIntroduced = reader.int32(); + break; + } + case 2: { + message.editionDeprecated = reader.int32(); + break; + } + case 3: { + message.deprecationWarning = reader.string(); + break; + } + case 4: { + message.editionRemoved = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FeatureSupport.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FeatureSupport message. + * @function verify + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FeatureSupport.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.editionIntroduced != null && message.hasOwnProperty("editionIntroduced")) + switch (message.editionIntroduced) { + default: + return "editionIntroduced: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + if (message.editionDeprecated != null && message.hasOwnProperty("editionDeprecated")) + switch (message.editionDeprecated) { + default: + return "editionDeprecated: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + if (message.deprecationWarning != null && message.hasOwnProperty("deprecationWarning")) + if (!$util.isString(message.deprecationWarning)) + return "deprecationWarning: string expected"; + if (message.editionRemoved != null && message.hasOwnProperty("editionRemoved")) + switch (message.editionRemoved) { + default: + return "editionRemoved: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + return null; + }; + + /** + * 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.edition = 1000; + message.editionRemoved = 1000; break; case "EDITION_2024": case 1001: - message.edition = 1001; + message.editionRemoved = 1001; break; case "EDITION_1_TEST_ONLY": case 1: - message.edition = 1; + message.editionRemoved = 1; break; case "EDITION_2_TEST_ONLY": case 2: - message.edition = 2; + message.editionRemoved = 2; break; case "EDITION_99997_TEST_ONLY": case 99997: - message.edition = 99997; + message.editionRemoved = 99997; break; case "EDITION_99998_TEST_ONLY": case 99998: - message.edition = 99998; + message.editionRemoved = 99998; break; case "EDITION_99999_TEST_ONLY": case 99999: - message.edition = 99999; + message.editionRemoved = 99999; break; case "EDITION_MAX": case 2147483647: - message.edition = 2147483647; + message.editionRemoved = 2147483647; break; } - 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 FeatureSupport message. Also converts values to other types if specified. * @function toObject - * @memberof google.protobuf.FieldOptions.EditionDefault + * @memberof google.protobuf.FieldOptions.FeatureSupport * @static - * @param {google.protobuf.FieldOptions.EditionDefault} message EditionDefault + * @param {google.protobuf.FieldOptions.FeatureSupport} message FeatureSupport * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - EditionDefault.toObject = function toObject(message, options) { + FeatureSupport.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { - object.value = ""; - object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; - } - 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; + 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 EditionDefault to JSON. + * Converts this FeatureSupport to JSON. * @function toJSON - * @memberof google.protobuf.FieldOptions.EditionDefault + * @memberof google.protobuf.FieldOptions.FeatureSupport * @instance * @returns {Object.} JSON object */ - EditionDefault.prototype.toJSON = function toJSON() { + FeatureSupport.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 FeatureSupport * @function getTypeUrl - * @memberof google.protobuf.FieldOptions.EditionDefault + * @memberof google.protobuf.FieldOptions.FeatureSupport * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - EditionDefault.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + FeatureSupport.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.protobuf.FieldOptions.EditionDefault"; + return typeUrlPrefix + "/google.protobuf.FieldOptions.FeatureSupport"; }; - return EditionDefault; + return FeatureSupport; })(); return FieldOptions; @@ -129464,6 +130733,7 @@ * @property {boolean|null} [deprecated] EnumValueOptions deprecated * @property {google.protobuf.IFeatureSet|null} [features] EnumValueOptions features * @property {boolean|null} [debugRedact] EnumValueOptions debugRedact + * @property {google.protobuf.FieldOptions.IFeatureSupport|null} [featureSupport] EnumValueOptions featureSupport * @property {Array.|null} [uninterpretedOption] EnumValueOptions uninterpretedOption */ @@ -129507,6 +130777,14 @@ */ EnumValueOptions.prototype.debugRedact = false; + /** + * EnumValueOptions featureSupport. + * @member {google.protobuf.FieldOptions.IFeatureSupport|null|undefined} featureSupport + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.featureSupport = null; + /** * EnumValueOptions uninterpretedOption. * @member {Array.} uninterpretedOption @@ -129545,6 +130823,8 @@ $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); if (message.debugRedact != null && Object.hasOwnProperty.call(message, "debugRedact")) writer.uint32(/* id 3, wireType 0 =*/24).bool(message.debugRedact); + if (message.featureSupport != null && Object.hasOwnProperty.call(message, "featureSupport")) + $root.google.protobuf.FieldOptions.FeatureSupport.encode(message.featureSupport, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); if (message.uninterpretedOption != null && message.uninterpretedOption.length) for (var i = 0; i < message.uninterpretedOption.length; ++i) $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); @@ -129596,6 +130876,10 @@ message.debugRedact = reader.bool(); break; } + case 4: { + message.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.decode(reader, reader.uint32()); + break; + } case 999: { if (!(message.uninterpretedOption && message.uninterpretedOption.length)) message.uninterpretedOption = []; @@ -129648,6 +130932,11 @@ if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) if (typeof message.debugRedact !== "boolean") return "debugRedact: boolean expected"; + if (message.featureSupport != null && message.hasOwnProperty("featureSupport")) { + var error = $root.google.protobuf.FieldOptions.FeatureSupport.verify(message.featureSupport); + if (error) + return "featureSupport." + error; + } if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { if (!Array.isArray(message.uninterpretedOption)) return "uninterpretedOption: array expected"; @@ -129681,6 +130970,11 @@ } if (object.debugRedact != null) message.debugRedact = Boolean(object.debugRedact); + if (object.featureSupport != null) { + if (typeof object.featureSupport !== "object") + throw TypeError(".google.protobuf.EnumValueOptions.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.EnumValueOptions.uninterpretedOption: array expected"); @@ -129713,6 +131007,7 @@ object.deprecated = false; object.features = null; object.debugRedact = false; + object.featureSupport = null; } if (message.deprecated != null && message.hasOwnProperty("deprecated")) object.deprecated = message.deprecated; @@ -129720,6 +131015,8 @@ object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) object.debugRedact = message.debugRedact; + 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) @@ -131159,6 +132456,8 @@ * @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 + * @property {google.protobuf.FeatureSet.EnforceNamingStyle|null} [enforceNamingStyle] FeatureSet enforceNamingStyle + * @property {google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|null} [defaultSymbolVisibility] FeatureSet defaultSymbolVisibility */ /** @@ -131224,6 +132523,22 @@ */ FeatureSet.prototype.jsonFormat = 0; + /** + * FeatureSet enforceNamingStyle. + * @member {google.protobuf.FeatureSet.EnforceNamingStyle} enforceNamingStyle + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.enforceNamingStyle = 0; + + /** + * FeatureSet defaultSymbolVisibility. + * @member {google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility} defaultSymbolVisibility + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.defaultSymbolVisibility = 0; + /** * Creates a new FeatureSet instance using the specified properties. * @function create @@ -131260,6 +132575,10 @@ writer.uint32(/* id 5, wireType 0 =*/40).int32(message.messageEncoding); if (message.jsonFormat != null && Object.hasOwnProperty.call(message, "jsonFormat")) writer.uint32(/* id 6, wireType 0 =*/48).int32(message.jsonFormat); + if (message.enforceNamingStyle != null && Object.hasOwnProperty.call(message, "enforceNamingStyle")) + writer.uint32(/* id 7, wireType 0 =*/56).int32(message.enforceNamingStyle); + if (message.defaultSymbolVisibility != null && Object.hasOwnProperty.call(message, "defaultSymbolVisibility")) + writer.uint32(/* id 8, wireType 0 =*/64).int32(message.defaultSymbolVisibility); return writer; }; @@ -131320,6 +132639,14 @@ message.jsonFormat = reader.int32(); break; } + case 7: { + message.enforceNamingStyle = reader.int32(); + break; + } + case 8: { + message.defaultSymbolVisibility = reader.int32(); + break; + } default: reader.skipType(tag & 7); break; @@ -131410,6 +132737,26 @@ case 2: break; } + if (message.enforceNamingStyle != null && message.hasOwnProperty("enforceNamingStyle")) + switch (message.enforceNamingStyle) { + default: + return "enforceNamingStyle: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.defaultSymbolVisibility != null && message.hasOwnProperty("defaultSymbolVisibility")) + switch (message.defaultSymbolVisibility) { + default: + return "defaultSymbolVisibility: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + break; + } return null; }; @@ -131549,6 +132896,54 @@ message.jsonFormat = 2; break; } + switch (object.enforceNamingStyle) { + default: + if (typeof object.enforceNamingStyle === "number") { + message.enforceNamingStyle = object.enforceNamingStyle; + break; + } + break; + case "ENFORCE_NAMING_STYLE_UNKNOWN": + case 0: + message.enforceNamingStyle = 0; + break; + case "STYLE2024": + case 1: + message.enforceNamingStyle = 1; + break; + case "STYLE_LEGACY": + case 2: + message.enforceNamingStyle = 2; + break; + } + switch (object.defaultSymbolVisibility) { + default: + if (typeof object.defaultSymbolVisibility === "number") { + message.defaultSymbolVisibility = object.defaultSymbolVisibility; + break; + } + break; + case "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN": + case 0: + message.defaultSymbolVisibility = 0; + break; + case "EXPORT_ALL": + case 1: + message.defaultSymbolVisibility = 1; + break; + case "EXPORT_TOP_LEVEL": + case 2: + message.defaultSymbolVisibility = 2; + break; + case "LOCAL_ALL": + case 3: + message.defaultSymbolVisibility = 3; + break; + case "STRICT": + case 4: + message.defaultSymbolVisibility = 4; + break; + } return message; }; @@ -131572,6 +132967,8 @@ 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; + object.enforceNamingStyle = options.enums === String ? "ENFORCE_NAMING_STYLE_UNKNOWN" : 0; + object.defaultSymbolVisibility = options.enums === String ? "DEFAULT_SYMBOL_VISIBILITY_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; @@ -131585,6 +132982,10 @@ 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; + if (message.enforceNamingStyle != null && message.hasOwnProperty("enforceNamingStyle")) + object.enforceNamingStyle = options.enums === String ? $root.google.protobuf.FeatureSet.EnforceNamingStyle[message.enforceNamingStyle] === undefined ? message.enforceNamingStyle : $root.google.protobuf.FeatureSet.EnforceNamingStyle[message.enforceNamingStyle] : message.enforceNamingStyle; + if (message.defaultSymbolVisibility != null && message.hasOwnProperty("defaultSymbolVisibility")) + object.defaultSymbolVisibility = options.enums === String ? $root.google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility[message.defaultSymbolVisibility] === undefined ? message.defaultSymbolVisibility : $root.google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility[message.defaultSymbolVisibility] : message.defaultSymbolVisibility; return object; }; @@ -131712,6 +133113,219 @@ return values; })(); + /** + * EnforceNamingStyle enum. + * @name google.protobuf.FeatureSet.EnforceNamingStyle + * @enum {number} + * @property {number} ENFORCE_NAMING_STYLE_UNKNOWN=0 ENFORCE_NAMING_STYLE_UNKNOWN value + * @property {number} STYLE2024=1 STYLE2024 value + * @property {number} STYLE_LEGACY=2 STYLE_LEGACY value + */ + FeatureSet.EnforceNamingStyle = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ENFORCE_NAMING_STYLE_UNKNOWN"] = 0; + values[valuesById[1] = "STYLE2024"] = 1; + values[valuesById[2] = "STYLE_LEGACY"] = 2; + return values; + })(); + + FeatureSet.VisibilityFeature = (function() { + + /** + * Properties of a VisibilityFeature. + * @memberof google.protobuf.FeatureSet + * @interface IVisibilityFeature + */ + + /** + * Constructs a new VisibilityFeature. + * @memberof google.protobuf.FeatureSet + * @classdesc Represents a VisibilityFeature. + * @implements IVisibilityFeature + * @constructor + * @param {google.protobuf.FeatureSet.IVisibilityFeature=} [properties] Properties to set + */ + function VisibilityFeature(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 new VisibilityFeature instance using the specified properties. + * @function create + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature=} [properties] Properties to set + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature instance + */ + VisibilityFeature.create = function create(properties) { + return new VisibilityFeature(properties); + }; + + /** + * Encodes the specified VisibilityFeature message. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature} message VisibilityFeature message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + VisibilityFeature.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + return writer; + }; + + /** + * Encodes the specified VisibilityFeature message, length delimited. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature} message VisibilityFeature message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + VisibilityFeature.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + VisibilityFeature.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FeatureSet.VisibilityFeature(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + VisibilityFeature.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a VisibilityFeature message. + * @function verify + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + VisibilityFeature.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + return null; + }; + + /** + * Creates a VisibilityFeature message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + */ + VisibilityFeature.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FeatureSet.VisibilityFeature) + return object; + return new $root.google.protobuf.FeatureSet.VisibilityFeature(); + }; + + /** + * Creates a plain object from a VisibilityFeature message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.VisibilityFeature} message VisibilityFeature + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + VisibilityFeature.toObject = function toObject() { + return {}; + }; + + /** + * Converts this VisibilityFeature to JSON. + * @function toJSON + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @instance + * @returns {Object.} JSON object + */ + VisibilityFeature.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for VisibilityFeature + * @function getTypeUrl + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + VisibilityFeature.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FeatureSet.VisibilityFeature"; + }; + + /** + * DefaultSymbolVisibility enum. + * @name google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility + * @enum {number} + * @property {number} DEFAULT_SYMBOL_VISIBILITY_UNKNOWN=0 DEFAULT_SYMBOL_VISIBILITY_UNKNOWN value + * @property {number} EXPORT_ALL=1 EXPORT_ALL value + * @property {number} EXPORT_TOP_LEVEL=2 EXPORT_TOP_LEVEL value + * @property {number} LOCAL_ALL=3 LOCAL_ALL value + * @property {number} STRICT=4 STRICT value + */ + VisibilityFeature.DefaultSymbolVisibility = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN"] = 0; + values[valuesById[1] = "EXPORT_ALL"] = 1; + values[valuesById[2] = "EXPORT_TOP_LEVEL"] = 2; + values[valuesById[3] = "LOCAL_ALL"] = 3; + values[valuesById[4] = "STRICT"] = 4; + return values; + })(); + + return VisibilityFeature; + })(); + return FeatureSet; })(); @@ -131896,6 +133510,7 @@ default: return "minimumEdition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -131913,6 +133528,7 @@ default: return "maximumEdition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -131961,6 +133577,10 @@ case 0: message.minimumEdition = 0; break; + case "EDITION_LEGACY": + case 900: + message.minimumEdition = 900; + break; case "EDITION_PROTO2": case 998: message.minimumEdition = 998; @@ -132013,6 +133633,10 @@ case 0: message.maximumEdition = 0; break; + case "EDITION_LEGACY": + case 900: + message.maximumEdition = 900; + break; case "EDITION_PROTO2": case 998: message.maximumEdition = 998; @@ -132121,7 +133745,8 @@ * @memberof google.protobuf.FeatureSetDefaults * @interface IFeatureSetEditionDefault * @property {google.protobuf.Edition|null} [edition] FeatureSetEditionDefault edition - * @property {google.protobuf.IFeatureSet|null} [features] FeatureSetEditionDefault features + * @property {google.protobuf.IFeatureSet|null} [overridableFeatures] FeatureSetEditionDefault overridableFeatures + * @property {google.protobuf.IFeatureSet|null} [fixedFeatures] FeatureSetEditionDefault fixedFeatures */ /** @@ -132148,12 +133773,20 @@ FeatureSetEditionDefault.prototype.edition = 0; /** - * FeatureSetEditionDefault features. - * @member {google.protobuf.IFeatureSet|null|undefined} features + * 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 * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault * @instance */ - FeatureSetEditionDefault.prototype.features = null; + FeatureSetEditionDefault.prototype.fixedFeatures = null; /** * Creates a new FeatureSetEditionDefault instance using the specified properties. @@ -132179,10 +133812,12 @@ FeatureSetEditionDefault.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); - if (message.features != null && Object.hasOwnProperty.call(message, "features")) - $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); if (message.edition != null && Object.hasOwnProperty.call(message, "edition")) writer.uint32(/* id 3, wireType 0 =*/24).int32(message.edition); + if (message.overridableFeatures != null && Object.hasOwnProperty.call(message, "overridableFeatures")) + $root.google.protobuf.FeatureSet.encode(message.overridableFeatures, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.fixedFeatures != null && Object.hasOwnProperty.call(message, "fixedFeatures")) + $root.google.protobuf.FeatureSet.encode(message.fixedFeatures, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); return writer; }; @@ -132223,8 +133858,12 @@ message.edition = reader.int32(); break; } - case 2: { - message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + case 4: { + message.overridableFeatures = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + break; + } + case 5: { + message.fixedFeatures = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); break; } default: @@ -132267,6 +133906,7 @@ default: return "edition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -132279,10 +133919,15 @@ case 2147483647: break; } - if (message.features != null && message.hasOwnProperty("features")) { - var error = $root.google.protobuf.FeatureSet.verify(message.features); + if (message.overridableFeatures != null && message.hasOwnProperty("overridableFeatures")) { + var error = $root.google.protobuf.FeatureSet.verify(message.overridableFeatures); + if (error) + return "overridableFeatures." + error; + } + if (message.fixedFeatures != null && message.hasOwnProperty("fixedFeatures")) { + var error = $root.google.protobuf.FeatureSet.verify(message.fixedFeatures); if (error) - return "features." + error; + return "fixedFeatures." + error; } return null; }; @@ -132310,6 +133955,10 @@ case 0: message.edition = 0; break; + case "EDITION_LEGACY": + case 900: + message.edition = 900; + break; case "EDITION_PROTO2": case 998: message.edition = 998; @@ -132351,10 +134000,15 @@ message.edition = 2147483647; break; } - 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); + 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); } return message; }; @@ -132373,13 +134027,16 @@ 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; }; @@ -133594,6 +135251,22 @@ return GeneratedCodeInfo; })(); + /** + * SymbolVisibility enum. + * @name google.protobuf.SymbolVisibility + * @enum {number} + * @property {number} VISIBILITY_UNSET=0 VISIBILITY_UNSET value + * @property {number} VISIBILITY_LOCAL=1 VISIBILITY_LOCAL value + * @property {number} VISIBILITY_EXPORT=2 VISIBILITY_EXPORT value + */ + protobuf.SymbolVisibility = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "VISIBILITY_UNSET"] = 0; + values[valuesById[1] = "VISIBILITY_LOCAL"] = 1; + values[valuesById[2] = "VISIBILITY_EXPORT"] = 2; + return values; + })(); + protobuf.Duration = (function() { /** diff --git a/packages/google-analytics-admin/protos/protos.json b/packages/google-analytics-admin/protos/protos.json index 500d56de6fef..38065231730d 100644 --- a/packages/google-analytics-admin/protos/protos.json +++ b/packages/google-analytics-admin/protos/protos.json @@ -13413,8 +13413,7 @@ "java_multiple_files": true, "java_outer_classname": "LaunchStageProto", "java_package": "com.google.api", - "objc_class_prefix": "GAPI", - "cc_enable_arenas": true + "objc_class_prefix": "GAPI" }, "nested": { "fieldBehavior": { @@ -13637,6 +13636,10 @@ "rule": "repeated", "type": "ClientLibraryDestination", "id": 2 + }, + "selectiveGapicGeneration": { + "type": "SelectiveGapicGeneration", + "id": 3 } } }, @@ -13777,6 +13780,28 @@ "common": { "type": "CommonLanguageSettings", "id": 1 + }, + "experimentalFeatures": { + "type": "ExperimentalFeatures", + "id": 2 + } + }, + "nested": { + "ExperimentalFeatures": { + "fields": { + "restAsyncIoEnabled": { + "type": "bool", + "id": 1 + }, + "protobufPythonicTypesEnabled": { + "type": "bool", + "id": 2 + }, + "unversionedPackageDisabled": { + "type": "bool", + "id": 3 + } + } } } }, @@ -13834,6 +13859,11 @@ "common": { "type": "CommonLanguageSettings", "id": 1 + }, + "renamedServices": { + "keyType": "string", + "type": "string", + "id": 2 } } }, @@ -13895,6 +13925,19 @@ "PACKAGE_MANAGER": 20 } }, + "SelectiveGapicGeneration": { + "fields": { + "methods": { + "rule": "repeated", + "type": "string", + "id": 1 + }, + "generateOmittedAsInternal": { + "type": "bool", + "id": 2 + } + } + }, "LaunchStage": { "values": { "LAUNCH_STAGE_UNSPECIFIED": 0, @@ -13928,12 +13971,19 @@ "type": "FileDescriptorProto", "id": 1 } - } + }, + "extensions": [ + [ + 536000000, + 536000000 + ] + ] }, "Edition": { "edition": "proto2", "values": { "EDITION_UNKNOWN": 0, + "EDITION_LEGACY": 900, "EDITION_PROTO2": 998, "EDITION_PROTO3": 999, "EDITION_2023": 1000, @@ -13972,6 +14022,11 @@ "type": "int32", "id": 11 }, + "optionDependency": { + "rule": "repeated", + "type": "string", + "id": 15 + }, "messageType": { "rule": "repeated", "type": "DescriptorProto", @@ -14060,6 +14115,10 @@ "rule": "repeated", "type": "string", "id": 10 + }, + "visibility": { + "type": "SymbolVisibility", + "id": 11 } }, "nested": { @@ -14285,6 +14344,10 @@ "rule": "repeated", "type": "string", "id": 5 + }, + "visibility": { + "type": "SymbolVisibility", + "id": 6 } }, "nested": { @@ -14335,7 +14398,14 @@ "type": "ServiceOptions", "id": 3 } - } + }, + "reserved": [ + [ + 4, + 4 + ], + "stream" + ] }, "MethodDescriptorProto": { "edition": "proto2", @@ -14499,6 +14569,7 @@ 42, 42 ], + "php_generic_services", [ 38, 38 @@ -14634,7 +14705,8 @@ "type": "bool", "id": 10, "options": { - "default": false + "default": false, + "deprecated": true } }, "debugRedact": { @@ -14662,6 +14734,10 @@ "type": "FeatureSet", "id": 21 }, + "featureSupport": { + "type": "FeatureSupport", + "id": 22 + }, "uninterpretedOption": { "rule": "repeated", "type": "UninterpretedOption", @@ -14731,6 +14807,26 @@ "id": 2 } } + }, + "FeatureSupport": { + "fields": { + "editionIntroduced": { + "type": "Edition", + "id": 1 + }, + "editionDeprecated": { + "type": "Edition", + "id": 2 + }, + "deprecationWarning": { + "type": "string", + "id": 3 + }, + "editionRemoved": { + "type": "Edition", + "id": 4 + } + } } } }, @@ -14819,6 +14915,10 @@ "default": false } }, + "featureSupport": { + "type": "FieldOptions.FeatureSupport", + "id": 4 + }, "uninterpretedOption": { "rule": "repeated", "type": "UninterpretedOption", @@ -14961,6 +15061,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_2023", "edition_defaults.value": "EXPLICIT" } @@ -14971,6 +15072,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "OPEN" } @@ -14981,6 +15083,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "PACKED" } @@ -14991,6 +15094,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "VERIFY" } @@ -15001,7 +15105,8 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", - "edition_defaults.edition": "EDITION_PROTO2", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_LEGACY", "edition_defaults.value": "LENGTH_PREFIXED" } }, @@ -15011,27 +15116,38 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "ALLOW" } + }, + "enforceNamingStyle": { + "type": "EnforceNamingStyle", + "id": 7, + "options": { + "retention": "RETENTION_SOURCE", + "targets": "TARGET_TYPE_METHOD", + "feature_support.edition_introduced": "EDITION_2024", + "edition_defaults.edition": "EDITION_2024", + "edition_defaults.value": "STYLE2024" + } + }, + "defaultSymbolVisibility": { + "type": "VisibilityFeature.DefaultSymbolVisibility", + "id": 8, + "options": { + "retention": "RETENTION_SOURCE", + "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2024", + "edition_defaults.edition": "EDITION_2024", + "edition_defaults.value": "EXPORT_TOP_LEVEL" + } } }, "extensions": [ [ 1000, - 1000 - ], - [ - 1001, - 1001 - ], - [ - 1002, - 1002 - ], - [ - 9990, - 9990 + 9994 ], [ 9995, @@ -15076,7 +15192,13 @@ "UTF8_VALIDATION_UNKNOWN": 0, "VERIFY": 2, "NONE": 3 - } + }, + "reserved": [ + [ + 1, + 1 + ] + ] }, "MessageEncoding": { "values": { @@ -15091,6 +15213,33 @@ "ALLOW": 1, "LEGACY_BEST_EFFORT": 2 } + }, + "EnforceNamingStyle": { + "values": { + "ENFORCE_NAMING_STYLE_UNKNOWN": 0, + "STYLE2024": 1, + "STYLE_LEGACY": 2 + } + }, + "VisibilityFeature": { + "fields": {}, + "reserved": [ + [ + 1, + 536870911 + ] + ], + "nested": { + "DefaultSymbolVisibility": { + "values": { + "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN": 0, + "EXPORT_ALL": 1, + "EXPORT_TOP_LEVEL": 2, + "LOCAL_ALL": 3, + "STRICT": 4 + } + } + } } } }, @@ -15118,11 +15267,26 @@ "type": "Edition", "id": 3 }, - "features": { + "overridableFeatures": { "type": "FeatureSet", - "id": 2 + "id": 4 + }, + "fixedFeatures": { + "type": "FeatureSet", + "id": 5 } - } + }, + "reserved": [ + [ + 1, + 1 + ], + [ + 2, + 2 + ], + "features" + ] } } }, @@ -15135,6 +15299,12 @@ "id": 1 } }, + "extensions": [ + [ + 536000000, + 536000000 + ] + ], "nested": { "Location": { "fields": { @@ -15220,6 +15390,14 @@ } } }, + "SymbolVisibility": { + "edition": "proto2", + "values": { + "VISIBILITY_UNSET": 0, + "VISIBILITY_LOCAL": 1, + "VISIBILITY_EXPORT": 2 + } + }, "Duration": { "fields": { "seconds": { diff --git a/packages/google-analytics-admin/samples/generated/v1alpha/snippet_metadata_google.analytics.admin.v1alpha.json b/packages/google-analytics-admin/samples/generated/v1alpha/snippet_metadata_google.analytics.admin.v1alpha.json index 0d477c8a7f66..c56b5e2941a5 100644 --- a/packages/google-analytics-admin/samples/generated/v1alpha/snippet_metadata_google.analytics.admin.v1alpha.json +++ b/packages/google-analytics-admin/samples/generated/v1alpha/snippet_metadata_google.analytics.admin.v1alpha.json @@ -1,7 +1,7 @@ { "clientLibrary": { "name": "nodejs-admin", - "version": "9.0.1", + "version": "0.1.0", "language": "TYPESCRIPT", "apis": [ { diff --git a/packages/google-analytics-admin/samples/generated/v1beta/snippet_metadata_google.analytics.admin.v1beta.json b/packages/google-analytics-admin/samples/generated/v1beta/snippet_metadata_google.analytics.admin.v1beta.json index 17e2171e7289..94275696a5b7 100644 --- a/packages/google-analytics-admin/samples/generated/v1beta/snippet_metadata_google.analytics.admin.v1beta.json +++ b/packages/google-analytics-admin/samples/generated/v1beta/snippet_metadata_google.analytics.admin.v1beta.json @@ -1,7 +1,7 @@ { "clientLibrary": { "name": "nodejs-admin", - "version": "9.0.1", + "version": "0.1.0", "language": "TYPESCRIPT", "apis": [ { diff --git a/packages/google-analytics-admin/src/v1alpha/analytics_admin_service_client.ts b/packages/google-analytics-admin/src/v1alpha/analytics_admin_service_client.ts index d6b042d51303..add687f89959 100644 --- a/packages/google-analytics-admin/src/v1alpha/analytics_admin_service_client.ts +++ b/packages/google-analytics-admin/src/v1alpha/analytics_admin_service_client.ts @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class AnalyticsAdminServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('admin'); @@ -57,9 +64,9 @@ export class AnalyticsAdminServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - analyticsAdminServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + analyticsAdminServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of AnalyticsAdminServiceClient. @@ -100,21 +107,43 @@ export class AnalyticsAdminServiceClient { * const client = new AnalyticsAdminServiceClient({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 AnalyticsAdminServiceClient; - 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 staticMembers = this + .constructor as typeof AnalyticsAdminServiceClient; + 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 = 'analyticsadmin.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -139,7 +168,7 @@ export class AnalyticsAdminServiceClient { 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; @@ -153,10 +182,7 @@ export class AnalyticsAdminServiceClient { } // 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 { @@ -178,118 +204,121 @@ export class AnalyticsAdminServiceClient { // Create useful helper objects for these. this.pathTemplates = { accountPathTemplate: new this._gaxModule.PathTemplate( - 'accounts/{account}' + 'accounts/{account}', ), accountAccessBindingPathTemplate: new this._gaxModule.PathTemplate( - 'accounts/{account}/accessBindings/{access_binding}' + 'accounts/{account}/accessBindings/{access_binding}', ), accountSummaryPathTemplate: new this._gaxModule.PathTemplate( - 'accountSummaries/{account_summary}' + 'accountSummaries/{account_summary}', ), adSenseLinkPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/adSenseLinks/{adsense_link}' + 'properties/{property}/adSenseLinks/{adsense_link}', ), attributionSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/attributionSettings' + 'properties/{property}/attributionSettings', ), audiencePathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/audiences/{audience}' + 'properties/{property}/audiences/{audience}', ), bigQueryLinkPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/bigQueryLinks/{bigquery_link}' + 'properties/{property}/bigQueryLinks/{bigquery_link}', ), calculatedMetricPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/calculatedMetrics/{calculated_metric}' + 'properties/{property}/calculatedMetrics/{calculated_metric}', ), channelGroupPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/channelGroups/{channel_group}' + 'properties/{property}/channelGroups/{channel_group}', ), conversionEventPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/conversionEvents/{conversion_event}' + 'properties/{property}/conversionEvents/{conversion_event}', ), customDimensionPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/customDimensions/{custom_dimension}' + 'properties/{property}/customDimensions/{custom_dimension}', ), customMetricPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/customMetrics/{custom_metric}' + 'properties/{property}/customMetrics/{custom_metric}', ), dataRedactionSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/dataStreams/{data_stream}/dataRedactionSettings' + 'properties/{property}/dataStreams/{data_stream}/dataRedactionSettings', ), dataRetentionSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/dataRetentionSettings' + 'properties/{property}/dataRetentionSettings', ), dataSharingSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'accounts/{account}/dataSharingSettings' + 'accounts/{account}/dataSharingSettings', ), dataStreamPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/dataStreams/{data_stream}' - ), - displayVideo360AdvertiserLinkPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/displayVideo360AdvertiserLinks/{display_video_360_advertiser_link}' - ), - displayVideo360AdvertiserLinkProposalPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/displayVideo360AdvertiserLinkProposals/{display_video_360_advertiser_link_proposal}' + 'properties/{property}/dataStreams/{data_stream}', ), + displayVideo360AdvertiserLinkPathTemplate: + new this._gaxModule.PathTemplate( + 'properties/{property}/displayVideo360AdvertiserLinks/{display_video_360_advertiser_link}', + ), + displayVideo360AdvertiserLinkProposalPathTemplate: + new this._gaxModule.PathTemplate( + 'properties/{property}/displayVideo360AdvertiserLinkProposals/{display_video_360_advertiser_link_proposal}', + ), enhancedMeasurementSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/dataStreams/{data_stream}/enhancedMeasurementSettings' + 'properties/{property}/dataStreams/{data_stream}/enhancedMeasurementSettings', ), eventCreateRulePathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/dataStreams/{data_stream}/eventCreateRules/{event_create_rule}' + 'properties/{property}/dataStreams/{data_stream}/eventCreateRules/{event_create_rule}', ), eventEditRulePathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/dataStreams/{data_stream}/eventEditRules/{event_edit_rule}' + 'properties/{property}/dataStreams/{data_stream}/eventEditRules/{event_edit_rule}', ), expandedDataSetPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/expandedDataSets/{expanded_data_set}' + 'properties/{property}/expandedDataSets/{expanded_data_set}', ), firebaseLinkPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/firebaseLinks/{firebase_link}' + 'properties/{property}/firebaseLinks/{firebase_link}', ), globalSiteTagPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/dataStreams/{data_stream}/globalSiteTag' + 'properties/{property}/dataStreams/{data_stream}/globalSiteTag', ), googleAdsLinkPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/googleAdsLinks/{google_ads_link}' + 'properties/{property}/googleAdsLinks/{google_ads_link}', ), googleSignalsSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/googleSignalsSettings' + 'properties/{property}/googleSignalsSettings', ), keyEventPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/keyEvents/{key_event}' + 'properties/{property}/keyEvents/{key_event}', ), measurementProtocolSecretPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/dataStreams/{data_stream}/measurementProtocolSecrets/{measurement_protocol_secret}' + 'properties/{property}/dataStreams/{data_stream}/measurementProtocolSecrets/{measurement_protocol_secret}', ), propertyPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}' + 'properties/{property}', ), propertyAccessBindingPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/accessBindings/{access_binding}' + 'properties/{property}/accessBindings/{access_binding}', ), reportingDataAnnotationPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/reportingDataAnnotations/{reporting_data_annotation}' + 'properties/{property}/reportingDataAnnotations/{reporting_data_annotation}', ), reportingIdentitySettingsPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/reportingIdentitySettings' + 'properties/{property}/reportingIdentitySettings', ), rollupPropertySourceLinkPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/rollupPropertySourceLinks/{rollup_property_source_link}' - ), - sKAdNetworkConversionValueSchemaPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/dataStreams/{data_stream}/sKAdNetworkConversionValueSchema/{skadnetwork_conversion_value_schema}' + 'properties/{property}/rollupPropertySourceLinks/{rollup_property_source_link}', ), + sKAdNetworkConversionValueSchemaPathTemplate: + new this._gaxModule.PathTemplate( + 'properties/{property}/dataStreams/{data_stream}/sKAdNetworkConversionValueSchema/{skadnetwork_conversion_value_schema}', + ), searchAds360LinkPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/searchAds360Links/{search_ads_360_link}' + 'properties/{property}/searchAds360Links/{search_ads_360_link}', ), subpropertyEventFilterPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/subpropertyEventFilters/{sub_property_event_filter}' + 'properties/{property}/subpropertyEventFilters/{sub_property_event_filter}', ), subpropertySyncConfigPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/subpropertySyncConfigs/{subproperty_sync_config}' + 'properties/{property}/subpropertySyncConfigs/{subproperty_sync_config}', ), userProvidedDataSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/userProvidedDataSettings' + 'properties/{property}/userProvidedDataSettings', ), }; @@ -297,70 +326,161 @@ export class AnalyticsAdminServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listAccounts: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'accounts'), - listAccountSummaries: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'accountSummaries'), - listProperties: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'properties'), - listFirebaseLinks: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'firebaseLinks'), - listGoogleAdsLinks: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'googleAdsLinks'), - listMeasurementProtocolSecrets: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'measurementProtocolSecrets'), - listSKAdNetworkConversionValueSchemas: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'skadnetworkConversionValueSchemas'), - searchChangeHistoryEvents: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'changeHistoryEvents'), - listConversionEvents: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'conversionEvents'), - listKeyEvents: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'keyEvents'), - listDisplayVideo360AdvertiserLinks: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'displayVideo_360AdvertiserLinks'), + listAccounts: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'accounts', + ), + listAccountSummaries: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'accountSummaries', + ), + listProperties: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'properties', + ), + listFirebaseLinks: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'firebaseLinks', + ), + listGoogleAdsLinks: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'googleAdsLinks', + ), + listMeasurementProtocolSecrets: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'measurementProtocolSecrets', + ), + listSKAdNetworkConversionValueSchemas: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'skadnetworkConversionValueSchemas', + ), + searchChangeHistoryEvents: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'changeHistoryEvents', + ), + listConversionEvents: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'conversionEvents', + ), + listKeyEvents: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'keyEvents', + ), + listDisplayVideo360AdvertiserLinks: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'displayVideo_360AdvertiserLinks', + ), listDisplayVideo360AdvertiserLinkProposals: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'displayVideo_360AdvertiserLinkProposals'), - listCustomDimensions: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'customDimensions'), - listCustomMetrics: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'customMetrics'), - listDataStreams: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'dataStreams'), - listAudiences: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'audiences'), - listSearchAds360Links: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'searchAds_360Links'), - listAccessBindings: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'accessBindings'), - listExpandedDataSets: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'expandedDataSets'), - listChannelGroups: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'channelGroups'), - listBigQueryLinks: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'bigqueryLinks'), - listAdSenseLinks: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'adsenseLinks'), - listEventCreateRules: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'eventCreateRules'), - listEventEditRules: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'eventEditRules'), - listCalculatedMetrics: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'calculatedMetrics'), - listRollupPropertySourceLinks: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'rollupPropertySourceLinks'), - listSubpropertyEventFilters: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'subpropertyEventFilters'), - listReportingDataAnnotations: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'reportingDataAnnotations'), - listSubpropertySyncConfigs: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'subpropertySyncConfigs') + new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'displayVideo_360AdvertiserLinkProposals', + ), + listCustomDimensions: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'customDimensions', + ), + listCustomMetrics: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'customMetrics', + ), + listDataStreams: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'dataStreams', + ), + listAudiences: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'audiences', + ), + listSearchAds360Links: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'searchAds_360Links', + ), + listAccessBindings: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'accessBindings', + ), + listExpandedDataSets: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'expandedDataSets', + ), + listChannelGroups: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'channelGroups', + ), + listBigQueryLinks: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'bigqueryLinks', + ), + listAdSenseLinks: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'adsenseLinks', + ), + listEventCreateRules: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'eventCreateRules', + ), + listEventEditRules: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'eventEditRules', + ), + listCalculatedMetrics: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'calculatedMetrics', + ), + listRollupPropertySourceLinks: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'rollupPropertySourceLinks', + ), + listSubpropertyEventFilters: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'subpropertyEventFilters', + ), + listReportingDataAnnotations: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'reportingDataAnnotations', + ), + listSubpropertySyncConfigs: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'subpropertySyncConfigs', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.analytics.admin.v1alpha.AnalyticsAdminService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.analytics.admin.v1alpha.AnalyticsAdminService', + 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 @@ -391,37 +511,197 @@ export class AnalyticsAdminServiceClient { // Put together the "service stub" for // google.analytics.admin.v1alpha.AnalyticsAdminService. this.analyticsAdminServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.analytics.admin.v1alpha.AnalyticsAdminService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.analytics.admin.v1alpha.AnalyticsAdminService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.analytics.admin.v1alpha.AnalyticsAdminService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.analytics.admin.v1alpha + .AnalyticsAdminService, + 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 analyticsAdminServiceStubMethods = - ['getAccount', 'listAccounts', 'deleteAccount', 'updateAccount', 'provisionAccountTicket', 'listAccountSummaries', 'getProperty', 'listProperties', 'createProperty', 'deleteProperty', 'updateProperty', 'createFirebaseLink', 'deleteFirebaseLink', 'listFirebaseLinks', 'getGlobalSiteTag', 'createGoogleAdsLink', 'updateGoogleAdsLink', 'deleteGoogleAdsLink', 'listGoogleAdsLinks', 'getDataSharingSettings', 'getMeasurementProtocolSecret', 'listMeasurementProtocolSecrets', 'createMeasurementProtocolSecret', 'deleteMeasurementProtocolSecret', 'updateMeasurementProtocolSecret', 'acknowledgeUserDataCollection', 'getSkAdNetworkConversionValueSchema', 'createSkAdNetworkConversionValueSchema', 'deleteSkAdNetworkConversionValueSchema', 'updateSkAdNetworkConversionValueSchema', 'listSkAdNetworkConversionValueSchemas', 'searchChangeHistoryEvents', 'getGoogleSignalsSettings', 'updateGoogleSignalsSettings', 'createConversionEvent', 'updateConversionEvent', 'getConversionEvent', 'deleteConversionEvent', 'listConversionEvents', 'createKeyEvent', 'updateKeyEvent', 'getKeyEvent', 'deleteKeyEvent', 'listKeyEvents', 'getDisplayVideo360AdvertiserLink', 'listDisplayVideo360AdvertiserLinks', 'createDisplayVideo360AdvertiserLink', 'deleteDisplayVideo360AdvertiserLink', 'updateDisplayVideo360AdvertiserLink', 'getDisplayVideo360AdvertiserLinkProposal', 'listDisplayVideo360AdvertiserLinkProposals', 'createDisplayVideo360AdvertiserLinkProposal', 'deleteDisplayVideo360AdvertiserLinkProposal', 'approveDisplayVideo360AdvertiserLinkProposal', 'cancelDisplayVideo360AdvertiserLinkProposal', 'createCustomDimension', 'updateCustomDimension', 'listCustomDimensions', 'archiveCustomDimension', 'getCustomDimension', 'createCustomMetric', 'updateCustomMetric', 'listCustomMetrics', 'archiveCustomMetric', 'getCustomMetric', 'getDataRetentionSettings', 'updateDataRetentionSettings', 'createDataStream', 'deleteDataStream', 'updateDataStream', 'listDataStreams', 'getDataStream', 'getAudience', 'listAudiences', 'createAudience', 'updateAudience', 'archiveAudience', 'getSearchAds360Link', 'listSearchAds360Links', 'createSearchAds360Link', 'deleteSearchAds360Link', 'updateSearchAds360Link', 'getAttributionSettings', 'updateAttributionSettings', 'runAccessReport', 'createAccessBinding', 'getAccessBinding', 'updateAccessBinding', 'deleteAccessBinding', 'listAccessBindings', 'batchCreateAccessBindings', 'batchGetAccessBindings', 'batchUpdateAccessBindings', 'batchDeleteAccessBindings', 'getExpandedDataSet', 'listExpandedDataSets', 'createExpandedDataSet', 'updateExpandedDataSet', 'deleteExpandedDataSet', 'getChannelGroup', 'listChannelGroups', 'createChannelGroup', 'updateChannelGroup', 'deleteChannelGroup', 'createBigQueryLink', 'getBigQueryLink', 'listBigQueryLinks', 'deleteBigQueryLink', 'updateBigQueryLink', 'getEnhancedMeasurementSettings', 'updateEnhancedMeasurementSettings', 'getAdSenseLink', 'createAdSenseLink', 'deleteAdSenseLink', 'listAdSenseLinks', 'getEventCreateRule', 'listEventCreateRules', 'createEventCreateRule', 'updateEventCreateRule', 'deleteEventCreateRule', 'getEventEditRule', 'listEventEditRules', 'createEventEditRule', 'updateEventEditRule', 'deleteEventEditRule', 'reorderEventEditRules', 'updateDataRedactionSettings', 'getDataRedactionSettings', 'getCalculatedMetric', 'createCalculatedMetric', 'listCalculatedMetrics', 'updateCalculatedMetric', 'deleteCalculatedMetric', 'createRollupProperty', 'getRollupPropertySourceLink', 'listRollupPropertySourceLinks', 'createRollupPropertySourceLink', 'deleteRollupPropertySourceLink', 'provisionSubproperty', 'createSubpropertyEventFilter', 'getSubpropertyEventFilter', 'listSubpropertyEventFilters', 'updateSubpropertyEventFilter', 'deleteSubpropertyEventFilter', 'createReportingDataAnnotation', 'getReportingDataAnnotation', 'listReportingDataAnnotations', 'updateReportingDataAnnotation', 'deleteReportingDataAnnotation', 'submitUserDeletion', 'listSubpropertySyncConfigs', 'updateSubpropertySyncConfig', 'getSubpropertySyncConfig', 'getReportingIdentitySettings', 'getUserProvidedDataSettings']; + const analyticsAdminServiceStubMethods = [ + 'getAccount', + 'listAccounts', + 'deleteAccount', + 'updateAccount', + 'provisionAccountTicket', + 'listAccountSummaries', + 'getProperty', + 'listProperties', + 'createProperty', + 'deleteProperty', + 'updateProperty', + 'createFirebaseLink', + 'deleteFirebaseLink', + 'listFirebaseLinks', + 'getGlobalSiteTag', + 'createGoogleAdsLink', + 'updateGoogleAdsLink', + 'deleteGoogleAdsLink', + 'listGoogleAdsLinks', + 'getDataSharingSettings', + 'getMeasurementProtocolSecret', + 'listMeasurementProtocolSecrets', + 'createMeasurementProtocolSecret', + 'deleteMeasurementProtocolSecret', + 'updateMeasurementProtocolSecret', + 'acknowledgeUserDataCollection', + 'getSkAdNetworkConversionValueSchema', + 'createSkAdNetworkConversionValueSchema', + 'deleteSkAdNetworkConversionValueSchema', + 'updateSkAdNetworkConversionValueSchema', + 'listSkAdNetworkConversionValueSchemas', + 'searchChangeHistoryEvents', + 'getGoogleSignalsSettings', + 'updateGoogleSignalsSettings', + 'createConversionEvent', + 'updateConversionEvent', + 'getConversionEvent', + 'deleteConversionEvent', + 'listConversionEvents', + 'createKeyEvent', + 'updateKeyEvent', + 'getKeyEvent', + 'deleteKeyEvent', + 'listKeyEvents', + 'getDisplayVideo360AdvertiserLink', + 'listDisplayVideo360AdvertiserLinks', + 'createDisplayVideo360AdvertiserLink', + 'deleteDisplayVideo360AdvertiserLink', + 'updateDisplayVideo360AdvertiserLink', + 'getDisplayVideo360AdvertiserLinkProposal', + 'listDisplayVideo360AdvertiserLinkProposals', + 'createDisplayVideo360AdvertiserLinkProposal', + 'deleteDisplayVideo360AdvertiserLinkProposal', + 'approveDisplayVideo360AdvertiserLinkProposal', + 'cancelDisplayVideo360AdvertiserLinkProposal', + 'createCustomDimension', + 'updateCustomDimension', + 'listCustomDimensions', + 'archiveCustomDimension', + 'getCustomDimension', + 'createCustomMetric', + 'updateCustomMetric', + 'listCustomMetrics', + 'archiveCustomMetric', + 'getCustomMetric', + 'getDataRetentionSettings', + 'updateDataRetentionSettings', + 'createDataStream', + 'deleteDataStream', + 'updateDataStream', + 'listDataStreams', + 'getDataStream', + 'getAudience', + 'listAudiences', + 'createAudience', + 'updateAudience', + 'archiveAudience', + 'getSearchAds360Link', + 'listSearchAds360Links', + 'createSearchAds360Link', + 'deleteSearchAds360Link', + 'updateSearchAds360Link', + 'getAttributionSettings', + 'updateAttributionSettings', + 'runAccessReport', + 'createAccessBinding', + 'getAccessBinding', + 'updateAccessBinding', + 'deleteAccessBinding', + 'listAccessBindings', + 'batchCreateAccessBindings', + 'batchGetAccessBindings', + 'batchUpdateAccessBindings', + 'batchDeleteAccessBindings', + 'getExpandedDataSet', + 'listExpandedDataSets', + 'createExpandedDataSet', + 'updateExpandedDataSet', + 'deleteExpandedDataSet', + 'getChannelGroup', + 'listChannelGroups', + 'createChannelGroup', + 'updateChannelGroup', + 'deleteChannelGroup', + 'createBigQueryLink', + 'getBigQueryLink', + 'listBigQueryLinks', + 'deleteBigQueryLink', + 'updateBigQueryLink', + 'getEnhancedMeasurementSettings', + 'updateEnhancedMeasurementSettings', + 'getAdSenseLink', + 'createAdSenseLink', + 'deleteAdSenseLink', + 'listAdSenseLinks', + 'getEventCreateRule', + 'listEventCreateRules', + 'createEventCreateRule', + 'updateEventCreateRule', + 'deleteEventCreateRule', + 'getEventEditRule', + 'listEventEditRules', + 'createEventEditRule', + 'updateEventEditRule', + 'deleteEventEditRule', + 'reorderEventEditRules', + 'updateDataRedactionSettings', + 'getDataRedactionSettings', + 'getCalculatedMetric', + 'createCalculatedMetric', + 'listCalculatedMetrics', + 'updateCalculatedMetric', + 'deleteCalculatedMetric', + 'createRollupProperty', + 'getRollupPropertySourceLink', + 'listRollupPropertySourceLinks', + 'createRollupPropertySourceLink', + 'deleteRollupPropertySourceLink', + 'provisionSubproperty', + 'createSubpropertyEventFilter', + 'getSubpropertyEventFilter', + 'listSubpropertyEventFilters', + 'updateSubpropertyEventFilter', + 'deleteSubpropertyEventFilter', + 'createReportingDataAnnotation', + 'getReportingDataAnnotation', + 'listReportingDataAnnotations', + 'updateReportingDataAnnotation', + 'deleteReportingDataAnnotation', + 'submitUserDeletion', + 'listSubpropertySyncConfigs', + 'updateSubpropertySyncConfig', + 'getSubpropertySyncConfig', + 'getReportingIdentitySettings', + 'getUserProvidedDataSettings', + ]; for (const methodName of analyticsAdminServiceStubMethods) { const callPromise = this.analyticsAdminServiceStub.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] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -436,8 +716,14 @@ export class AnalyticsAdminServiceClient { * @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 'analyticsadmin.googleapis.com'; } @@ -448,8 +734,14 @@ export class AnalyticsAdminServiceClient { * @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 'analyticsadmin.googleapis.com'; } @@ -484,7 +776,7 @@ export class AnalyticsAdminServiceClient { 'https://www.googleapis.com/auth/analytics.edit', 'https://www.googleapis.com/auth/analytics.manage.users', 'https://www.googleapis.com/auth/analytics.manage.users.readonly', - 'https://www.googleapis.com/auth/analytics.readonly' + 'https://www.googleapis.com/auth/analytics.readonly', ]; } @@ -494,8 +786,9 @@ export class AnalyticsAdminServiceClient { * 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; @@ -506,12487 +799,18743 @@ export class AnalyticsAdminServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Lookup for a single Account. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the account to lookup. - * Format: accounts/{account} - * Example: "accounts/100" - * @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.analytics.admin.v1alpha.Account|Account}. - * 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/v1alpha/analytics_admin_service.get_account.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetAccount_async - */ + /** + * Lookup for a single Account. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the account to lookup. + * Format: accounts/{account} + * Example: "accounts/100" + * @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.analytics.admin.v1alpha.Account|Account}. + * 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/v1alpha/analytics_admin_service.get_account.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetAccount_async + */ getAccount( - request?: protos.google.analytics.admin.v1alpha.IGetAccountRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IAccount, - protos.google.analytics.admin.v1alpha.IGetAccountRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetAccountRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAccount, + protos.google.analytics.admin.v1alpha.IGetAccountRequest | undefined, + {} | undefined, + ] + >; getAccount( - request: protos.google.analytics.admin.v1alpha.IGetAccountRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAccount, - protos.google.analytics.admin.v1alpha.IGetAccountRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetAccountRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAccount, + | protos.google.analytics.admin.v1alpha.IGetAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAccount( - request: protos.google.analytics.admin.v1alpha.IGetAccountRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAccount, - protos.google.analytics.admin.v1alpha.IGetAccountRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetAccountRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAccount, + | protos.google.analytics.admin.v1alpha.IGetAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAccount( - request?: protos.google.analytics.admin.v1alpha.IGetAccountRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IGetAccountRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IAccount, - protos.google.analytics.admin.v1alpha.IGetAccountRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IAccount, - protos.google.analytics.admin.v1alpha.IGetAccountRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IAccount, - protos.google.analytics.admin.v1alpha.IGetAccountRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetAccountRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IAccount, + | protos.google.analytics.admin.v1alpha.IGetAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAccount, + protos.google.analytics.admin.v1alpha.IGetAccountRequest | 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('getAccount request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IAccount, - protos.google.analytics.admin.v1alpha.IGetAccountRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IAccount, + | protos.google.analytics.admin.v1alpha.IGetAccountRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getAccount response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getAccount(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IAccount, - protos.google.analytics.admin.v1alpha.IGetAccountRequest|undefined, - {}|undefined - ]) => { - this._log.info('getAccount response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getAccount(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IAccount, + protos.google.analytics.admin.v1alpha.IGetAccountRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getAccount response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Marks target Account as soft-deleted (ie: "trashed") and returns it. - * - * This API does not have a method to restore soft-deleted accounts. - * However, they can be restored using the Trash Can UI. - * - * If the accounts are not restored before the expiration time, the account - * and all child resources (eg: Properties, GoogleAdsLinks, Streams, - * AccessBindings) will be permanently purged. - * https://support.google.com/analytics/answer/6154772 - * - * Returns an error if the target is not found. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the Account to soft-delete. - * Format: accounts/{account} - * Example: "accounts/100" - * @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/v1alpha/analytics_admin_service.delete_account.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteAccount_async - */ + /** + * Marks target Account as soft-deleted (ie: "trashed") and returns it. + * + * This API does not have a method to restore soft-deleted accounts. + * However, they can be restored using the Trash Can UI. + * + * If the accounts are not restored before the expiration time, the account + * and all child resources (eg: Properties, GoogleAdsLinks, Streams, + * AccessBindings) will be permanently purged. + * https://support.google.com/analytics/answer/6154772 + * + * Returns an error if the target is not found. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the Account to soft-delete. + * Format: accounts/{account} + * Example: "accounts/100" + * @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/v1alpha/analytics_admin_service.delete_account.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteAccount_async + */ deleteAccount( - request?: protos.google.analytics.admin.v1alpha.IDeleteAccountRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAccountRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IDeleteAccountRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.analytics.admin.v1alpha.IDeleteAccountRequest | undefined, + {} | undefined, + ] + >; deleteAccount( - request: protos.google.analytics.admin.v1alpha.IDeleteAccountRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAccountRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteAccountRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteAccount( - request: protos.google.analytics.admin.v1alpha.IDeleteAccountRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAccountRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteAccountRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteAccount( - request?: protos.google.analytics.admin.v1alpha.IDeleteAccountRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAccountRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IDeleteAccountRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAccountRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAccountRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IDeleteAccountRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.analytics.admin.v1alpha.IDeleteAccountRequest | 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('deleteAccount request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAccountRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteAccountRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteAccount response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteAccount(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAccountRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteAccount response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteAccount(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteAccountRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteAccount response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates an account. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.Account} request.account - * Required. The account to update. - * The account's `name` field is used to identify the account. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Field names must be in snake - * case (for example, "field_to_update"). Omitted fields will not be updated. - * To replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1alpha.Account|Account}. - * 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/v1alpha/analytics_admin_service.update_account.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateAccount_async - */ + /** + * Updates an account. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.Account} request.account + * Required. The account to update. + * The account's `name` field is used to identify the account. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Field names must be in snake + * case (for example, "field_to_update"). Omitted fields will not be updated. + * To replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1alpha.Account|Account}. + * 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/v1alpha/analytics_admin_service.update_account.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateAccount_async + */ updateAccount( - request?: protos.google.analytics.admin.v1alpha.IUpdateAccountRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IAccount, - protos.google.analytics.admin.v1alpha.IUpdateAccountRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateAccountRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAccount, + protos.google.analytics.admin.v1alpha.IUpdateAccountRequest | undefined, + {} | undefined, + ] + >; updateAccount( - request: protos.google.analytics.admin.v1alpha.IUpdateAccountRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAccount, - protos.google.analytics.admin.v1alpha.IUpdateAccountRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateAccountRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAccount, + | protos.google.analytics.admin.v1alpha.IUpdateAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateAccount( - request: protos.google.analytics.admin.v1alpha.IUpdateAccountRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAccount, - protos.google.analytics.admin.v1alpha.IUpdateAccountRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateAccountRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAccount, + | protos.google.analytics.admin.v1alpha.IUpdateAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateAccount( - request?: protos.google.analytics.admin.v1alpha.IUpdateAccountRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IAccount, - protos.google.analytics.admin.v1alpha.IUpdateAccountRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateAccountRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IAccount, - protos.google.analytics.admin.v1alpha.IUpdateAccountRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IAccount, - protos.google.analytics.admin.v1alpha.IUpdateAccountRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateAccountRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IAccount, + | protos.google.analytics.admin.v1alpha.IUpdateAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAccount, + protos.google.analytics.admin.v1alpha.IUpdateAccountRequest | 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({ - 'account.name': request.account!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'account.name': request.account!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateAccount request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IAccount, - protos.google.analytics.admin.v1alpha.IUpdateAccountRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IAccount, + | protos.google.analytics.admin.v1alpha.IUpdateAccountRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateAccount response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateAccount(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IAccount, - protos.google.analytics.admin.v1alpha.IUpdateAccountRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateAccount response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateAccount(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IAccount, + ( + | protos.google.analytics.admin.v1alpha.IUpdateAccountRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateAccount response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Requests a ticket for creating an account. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.Account} request.account - * The account to create. - * @param {string} request.redirectUri - * Redirect URI where the user will be sent after accepting Terms of Service. - * Must be configured in Cloud Console as a Redirect URI. - * @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.analytics.admin.v1alpha.ProvisionAccountTicketResponse|ProvisionAccountTicketResponse}. - * 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/v1alpha/analytics_admin_service.provision_account_ticket.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ProvisionAccountTicket_async - */ + /** + * Requests a ticket for creating an account. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.Account} request.account + * The account to create. + * @param {string} request.redirectUri + * Redirect URI where the user will be sent after accepting Terms of Service. + * Must be configured in Cloud Console as a Redirect URI. + * @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.analytics.admin.v1alpha.ProvisionAccountTicketResponse|ProvisionAccountTicketResponse}. + * 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/v1alpha/analytics_admin_service.provision_account_ticket.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ProvisionAccountTicket_async + */ provisionAccountTicket( - request?: protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IProvisionAccountTicketResponse, - protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IProvisionAccountTicketResponse, + ( + | protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest + | undefined + ), + {} | undefined, + ] + >; provisionAccountTicket( - request: protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IProvisionAccountTicketResponse, - protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IProvisionAccountTicketResponse, + | protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest + | null + | undefined, + {} | null | undefined + >, + ): void; provisionAccountTicket( - request: protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IProvisionAccountTicketResponse, - protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IProvisionAccountTicketResponse, + | protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest + | null + | undefined, + {} | null | undefined + >, + ): void; provisionAccountTicket( - request?: protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IProvisionAccountTicketResponse, - protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IProvisionAccountTicketResponse, - protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IProvisionAccountTicketResponse, - protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IProvisionAccountTicketResponse, + | protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IProvisionAccountTicketResponse, + ( + | protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest + | 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 || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('provisionAccountTicket request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IProvisionAccountTicketResponse, - protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IProvisionAccountTicketResponse, + | protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('provisionAccountTicket response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.provisionAccountTicket(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IProvisionAccountTicketResponse, - protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest|undefined, - {}|undefined - ]) => { - this._log.info('provisionAccountTicket response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .provisionAccountTicket(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IProvisionAccountTicketResponse, + ( + | protos.google.analytics.admin.v1alpha.IProvisionAccountTicketRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('provisionAccountTicket response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for a single GA Property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the property to lookup. - * Format: properties/{property_id} - * Example: "properties/1000" - * @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.analytics.admin.v1alpha.Property|Property}. - * 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/v1alpha/analytics_admin_service.get_property.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetProperty_async - */ + /** + * Lookup for a single GA Property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the property to lookup. + * Format: properties/{property_id} + * Example: "properties/1000" + * @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.analytics.admin.v1alpha.Property|Property}. + * 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/v1alpha/analytics_admin_service.get_property.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetProperty_async + */ getProperty( - request?: protos.google.analytics.admin.v1alpha.IGetPropertyRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IGetPropertyRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetPropertyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IProperty, + protos.google.analytics.admin.v1alpha.IGetPropertyRequest | undefined, + {} | undefined, + ] + >; getProperty( - request: protos.google.analytics.admin.v1alpha.IGetPropertyRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IGetPropertyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetPropertyRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IProperty, + | protos.google.analytics.admin.v1alpha.IGetPropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getProperty( - request: protos.google.analytics.admin.v1alpha.IGetPropertyRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IGetPropertyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetPropertyRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IProperty, + | protos.google.analytics.admin.v1alpha.IGetPropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getProperty( - request?: protos.google.analytics.admin.v1alpha.IGetPropertyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IGetPropertyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IGetPropertyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IGetPropertyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IGetPropertyRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetPropertyRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IProperty, + | protos.google.analytics.admin.v1alpha.IGetPropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IProperty, + protos.google.analytics.admin.v1alpha.IGetPropertyRequest | 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('getProperty request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IGetPropertyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IProperty, + | protos.google.analytics.admin.v1alpha.IGetPropertyRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getProperty response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getProperty(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IGetPropertyRequest|undefined, - {}|undefined - ]) => { - this._log.info('getProperty response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getProperty(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IProperty, + protos.google.analytics.admin.v1alpha.IGetPropertyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getProperty response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a Google Analytics property with the specified location and - * attributes. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.Property} request.property - * Required. The property to create. - * Note: the supplied property must specify its parent. - * @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.analytics.admin.v1alpha.Property|Property}. - * 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/v1alpha/analytics_admin_service.create_property.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateProperty_async - */ + /** + * Creates a Google Analytics property with the specified location and + * attributes. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.Property} request.property + * Required. The property to create. + * Note: the supplied property must specify its parent. + * @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.analytics.admin.v1alpha.Property|Property}. + * 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/v1alpha/analytics_admin_service.create_property.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateProperty_async + */ createProperty( - request?: protos.google.analytics.admin.v1alpha.ICreatePropertyRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.ICreatePropertyRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreatePropertyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IProperty, + protos.google.analytics.admin.v1alpha.ICreatePropertyRequest | undefined, + {} | undefined, + ] + >; createProperty( - request: protos.google.analytics.admin.v1alpha.ICreatePropertyRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.ICreatePropertyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreatePropertyRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IProperty, + | protos.google.analytics.admin.v1alpha.ICreatePropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createProperty( - request: protos.google.analytics.admin.v1alpha.ICreatePropertyRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.ICreatePropertyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreatePropertyRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IProperty, + | protos.google.analytics.admin.v1alpha.ICreatePropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createProperty( - request?: protos.google.analytics.admin.v1alpha.ICreatePropertyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.ICreatePropertyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.ICreatePropertyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.ICreatePropertyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.ICreatePropertyRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreatePropertyRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IProperty, + | protos.google.analytics.admin.v1alpha.ICreatePropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IProperty, + protos.google.analytics.admin.v1alpha.ICreatePropertyRequest | 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 || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createProperty request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.ICreatePropertyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IProperty, + | protos.google.analytics.admin.v1alpha.ICreatePropertyRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createProperty response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createProperty(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.ICreatePropertyRequest|undefined, - {}|undefined - ]) => { - this._log.info('createProperty response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createProperty(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IProperty, + ( + | protos.google.analytics.admin.v1alpha.ICreatePropertyRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createProperty response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Marks target Property as soft-deleted (ie: "trashed") and returns it. - * - * This API does not have a method to restore soft-deleted properties. - * However, they can be restored using the Trash Can UI. - * - * If the properties are not restored before the expiration time, the Property - * and all child resources (eg: GoogleAdsLinks, Streams, AccessBindings) - * will be permanently purged. - * https://support.google.com/analytics/answer/6154772 - * - * Returns an error if the target is not found. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the Property to soft-delete. - * Format: properties/{property_id} - * Example: "properties/1000" - * @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.analytics.admin.v1alpha.Property|Property}. - * 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/v1alpha/analytics_admin_service.delete_property.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteProperty_async - */ + /** + * Marks target Property as soft-deleted (ie: "trashed") and returns it. + * + * This API does not have a method to restore soft-deleted properties. + * However, they can be restored using the Trash Can UI. + * + * If the properties are not restored before the expiration time, the Property + * and all child resources (eg: GoogleAdsLinks, Streams, AccessBindings) + * will be permanently purged. + * https://support.google.com/analytics/answer/6154772 + * + * Returns an error if the target is not found. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the Property to soft-delete. + * Format: properties/{property_id} + * Example: "properties/1000" + * @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.analytics.admin.v1alpha.Property|Property}. + * 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/v1alpha/analytics_admin_service.delete_property.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteProperty_async + */ deleteProperty( - request?: protos.google.analytics.admin.v1alpha.IDeletePropertyRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IDeletePropertyRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IDeletePropertyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IProperty, + protos.google.analytics.admin.v1alpha.IDeletePropertyRequest | undefined, + {} | undefined, + ] + >; deleteProperty( - request: protos.google.analytics.admin.v1alpha.IDeletePropertyRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IDeletePropertyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeletePropertyRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IProperty, + | protos.google.analytics.admin.v1alpha.IDeletePropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteProperty( - request: protos.google.analytics.admin.v1alpha.IDeletePropertyRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IDeletePropertyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeletePropertyRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IProperty, + | protos.google.analytics.admin.v1alpha.IDeletePropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteProperty( - request?: protos.google.analytics.admin.v1alpha.IDeletePropertyRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IDeletePropertyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IDeletePropertyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IDeletePropertyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IDeletePropertyRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IDeletePropertyRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IProperty, + | protos.google.analytics.admin.v1alpha.IDeletePropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IProperty, + protos.google.analytics.admin.v1alpha.IDeletePropertyRequest | 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('deleteProperty request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IDeletePropertyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IProperty, + | protos.google.analytics.admin.v1alpha.IDeletePropertyRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteProperty response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteProperty(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IDeletePropertyRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteProperty response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteProperty(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IProperty, + ( + | protos.google.analytics.admin.v1alpha.IDeletePropertyRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteProperty response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.Property} request.property - * Required. The property to update. - * The property's `name` field is used to identify the property to be - * updated. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Field names must be in snake - * case (e.g., "field_to_update"). Omitted fields will not be updated. To - * replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1alpha.Property|Property}. - * 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/v1alpha/analytics_admin_service.update_property.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateProperty_async - */ + /** + * Updates a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.Property} request.property + * Required. The property to update. + * The property's `name` field is used to identify the property to be + * updated. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Field names must be in snake + * case (e.g., "field_to_update"). Omitted fields will not be updated. To + * replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1alpha.Property|Property}. + * 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/v1alpha/analytics_admin_service.update_property.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateProperty_async + */ updateProperty( - request?: protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IProperty, + protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest | undefined, + {} | undefined, + ] + >; updateProperty( - request: protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IProperty, + | protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateProperty( - request: protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IProperty, + | protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateProperty( - request?: protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IProperty, + | protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IProperty, + protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest | 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({ - 'property.name': request.property!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'property.name': request.property!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateProperty request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IProperty, + | protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateProperty response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateProperty(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IProperty, - protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateProperty response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateProperty(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IProperty, + ( + | protos.google.analytics.admin.v1alpha.IUpdatePropertyRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateProperty response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a FirebaseLink. - * - * Properties can have at most one FirebaseLink. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Format: properties/{property_id} - * - * Example: `properties/1234` - * @param {google.analytics.admin.v1alpha.FirebaseLink} request.firebaseLink - * Required. The Firebase link 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.analytics.admin.v1alpha.FirebaseLink|FirebaseLink}. - * 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/v1alpha/analytics_admin_service.create_firebase_link.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateFirebaseLink_async - */ + /** + * Creates a FirebaseLink. + * + * Properties can have at most one FirebaseLink. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Format: properties/{property_id} + * + * Example: `properties/1234` + * @param {google.analytics.admin.v1alpha.FirebaseLink} request.firebaseLink + * Required. The Firebase link 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.analytics.admin.v1alpha.FirebaseLink|FirebaseLink}. + * 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/v1alpha/analytics_admin_service.create_firebase_link.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateFirebaseLink_async + */ createFirebaseLink( - request?: protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IFirebaseLink, - protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IFirebaseLink, + ( + | protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest + | undefined + ), + {} | undefined, + ] + >; createFirebaseLink( - request: protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IFirebaseLink, - protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IFirebaseLink, + | protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createFirebaseLink( - request: protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IFirebaseLink, - protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IFirebaseLink, + | protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createFirebaseLink( - request?: protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IFirebaseLink, - protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IFirebaseLink, - protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IFirebaseLink, - protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IFirebaseLink, + | protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IFirebaseLink, + ( + | protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest + | 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('createFirebaseLink request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IFirebaseLink, - protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IFirebaseLink, + | protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createFirebaseLink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createFirebaseLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IFirebaseLink, - protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('createFirebaseLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createFirebaseLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IFirebaseLink, + ( + | protos.google.analytics.admin.v1alpha.ICreateFirebaseLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createFirebaseLink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a FirebaseLink on a property - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Format: properties/{property_id}/firebaseLinks/{firebase_link_id} - * - * Example: `properties/1234/firebaseLinks/5678` - * @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/v1alpha/analytics_admin_service.delete_firebase_link.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteFirebaseLink_async - */ + /** + * Deletes a FirebaseLink on a property + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Format: properties/{property_id}/firebaseLinks/{firebase_link_id} + * + * Example: `properties/1234/firebaseLinks/5678` + * @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/v1alpha/analytics_admin_service.delete_firebase_link.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteFirebaseLink_async + */ deleteFirebaseLink( - request?: protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest + | undefined + ), + {} | undefined, + ] + >; deleteFirebaseLink( - request: protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteFirebaseLink( - request: protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteFirebaseLink( - request?: protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest + | 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('deleteFirebaseLink request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteFirebaseLink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteFirebaseLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteFirebaseLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteFirebaseLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteFirebaseLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteFirebaseLink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns the Site Tag for the specified web stream. - * Site Tags are immutable singletons. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the site tag to lookup. - * Note that site tags are singletons and do not have unique IDs. - * Format: properties/{property_id}/dataStreams/{stream_id}/globalSiteTag - * - * Example: `properties/123/dataStreams/456/globalSiteTag` - * @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.analytics.admin.v1alpha.GlobalSiteTag|GlobalSiteTag}. - * 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/v1alpha/analytics_admin_service.get_global_site_tag.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetGlobalSiteTag_async - */ + /** + * Returns the Site Tag for the specified web stream. + * Site Tags are immutable singletons. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the site tag to lookup. + * Note that site tags are singletons and do not have unique IDs. + * Format: properties/{property_id}/dataStreams/{stream_id}/globalSiteTag + * + * Example: `properties/123/dataStreams/456/globalSiteTag` + * @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.analytics.admin.v1alpha.GlobalSiteTag|GlobalSiteTag}. + * 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/v1alpha/analytics_admin_service.get_global_site_tag.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetGlobalSiteTag_async + */ getGlobalSiteTag( - request?: protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IGlobalSiteTag, - protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IGlobalSiteTag, + ( + | protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest + | undefined + ), + {} | undefined, + ] + >; getGlobalSiteTag( - request: protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IGlobalSiteTag, - protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IGlobalSiteTag, + | protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getGlobalSiteTag( - request: protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IGlobalSiteTag, - protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IGlobalSiteTag, + | protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getGlobalSiteTag( - request?: protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IGlobalSiteTag, - protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IGlobalSiteTag, - protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IGlobalSiteTag, - protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IGlobalSiteTag, + | protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IGlobalSiteTag, + ( + | protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest + | 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('getGlobalSiteTag request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IGlobalSiteTag, - protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IGlobalSiteTag, + | protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getGlobalSiteTag response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getGlobalSiteTag(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IGlobalSiteTag, - protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest|undefined, - {}|undefined - ]) => { - this._log.info('getGlobalSiteTag response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getGlobalSiteTag(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IGlobalSiteTag, + ( + | protos.google.analytics.admin.v1alpha.IGetGlobalSiteTagRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getGlobalSiteTag response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a GoogleAdsLink. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {google.analytics.admin.v1alpha.GoogleAdsLink} request.googleAdsLink - * Required. The GoogleAdsLink 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.analytics.admin.v1alpha.GoogleAdsLink|GoogleAdsLink}. - * 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/v1alpha/analytics_admin_service.create_google_ads_link.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateGoogleAdsLink_async - */ + /** + * Creates a GoogleAdsLink. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {google.analytics.admin.v1alpha.GoogleAdsLink} request.googleAdsLink + * Required. The GoogleAdsLink 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.analytics.admin.v1alpha.GoogleAdsLink|GoogleAdsLink}. + * 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/v1alpha/analytics_admin_service.create_google_ads_link.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateGoogleAdsLink_async + */ createGoogleAdsLink( - request?: protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IGoogleAdsLink, - protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IGoogleAdsLink, + ( + | protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest + | undefined + ), + {} | undefined, + ] + >; createGoogleAdsLink( - request: protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IGoogleAdsLink, - protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IGoogleAdsLink, + | protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createGoogleAdsLink( - request: protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IGoogleAdsLink, - protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IGoogleAdsLink, + | protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createGoogleAdsLink( - request?: protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IGoogleAdsLink, - protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IGoogleAdsLink, - protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IGoogleAdsLink, - protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IGoogleAdsLink, + | protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IGoogleAdsLink, + ( + | protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest + | 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('createGoogleAdsLink request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IGoogleAdsLink, - protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IGoogleAdsLink, + | protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createGoogleAdsLink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createGoogleAdsLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IGoogleAdsLink, - protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('createGoogleAdsLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createGoogleAdsLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IGoogleAdsLink, + ( + | protos.google.analytics.admin.v1alpha.ICreateGoogleAdsLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createGoogleAdsLink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a GoogleAdsLink on a property - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.GoogleAdsLink} request.googleAdsLink - * The GoogleAdsLink to update - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Field names must be in snake - * case (e.g., "field_to_update"). Omitted fields will not be updated. To - * replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1alpha.GoogleAdsLink|GoogleAdsLink}. - * 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/v1alpha/analytics_admin_service.update_google_ads_link.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateGoogleAdsLink_async - */ - updateGoogleAdsLink( - request?: protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IGoogleAdsLink, - protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest|undefined, {}|undefined - ]>; + /** + * Updates a GoogleAdsLink on a property + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.GoogleAdsLink} request.googleAdsLink + * The GoogleAdsLink to update + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Field names must be in snake + * case (e.g., "field_to_update"). Omitted fields will not be updated. To + * replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1alpha.GoogleAdsLink|GoogleAdsLink}. + * 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/v1alpha/analytics_admin_service.update_google_ads_link.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateGoogleAdsLink_async + */ updateGoogleAdsLink( - request: protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IGoogleAdsLink, - protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>): void; + request?: protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IGoogleAdsLink, + ( + | protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest + | undefined + ), + {} | undefined, + ] + >; updateGoogleAdsLink( - request: protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IGoogleAdsLink, - protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IGoogleAdsLink, + | protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateGoogleAdsLink( - request?: protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IGoogleAdsLink, - protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request: protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IGoogleAdsLink, + | protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + updateGoogleAdsLink( + request?: protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IGoogleAdsLink, - protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IGoogleAdsLink, - protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IGoogleAdsLink, + | protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IGoogleAdsLink, + ( + | protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest + | 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({ - 'google_ads_link.name': request.googleAdsLink!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'google_ads_link.name': request.googleAdsLink!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateGoogleAdsLink request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IGoogleAdsLink, - protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IGoogleAdsLink, + | protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateGoogleAdsLink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateGoogleAdsLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IGoogleAdsLink, - protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateGoogleAdsLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateGoogleAdsLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IGoogleAdsLink, + ( + | protos.google.analytics.admin.v1alpha.IUpdateGoogleAdsLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateGoogleAdsLink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a GoogleAdsLink on a property - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Example format: properties/1234/googleAdsLinks/5678 - * @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/v1alpha/analytics_admin_service.delete_google_ads_link.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteGoogleAdsLink_async - */ + /** + * Deletes a GoogleAdsLink on a property + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Example format: properties/1234/googleAdsLinks/5678 + * @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/v1alpha/analytics_admin_service.delete_google_ads_link.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteGoogleAdsLink_async + */ deleteGoogleAdsLink( - request?: protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest + | undefined + ), + {} | undefined, + ] + >; deleteGoogleAdsLink( - request: protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteGoogleAdsLink( - request: protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteGoogleAdsLink( - request?: protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest + | 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('deleteGoogleAdsLink request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteGoogleAdsLink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteGoogleAdsLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteGoogleAdsLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteGoogleAdsLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteGoogleAdsLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteGoogleAdsLink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Get data sharing settings on an account. - * Data sharing settings are singletons. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the settings to lookup. - * Format: accounts/{account}/dataSharingSettings - * - * Example: `accounts/1000/dataSharingSettings` - * @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.analytics.admin.v1alpha.DataSharingSettings|DataSharingSettings}. - * 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/v1alpha/analytics_admin_service.get_data_sharing_settings.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetDataSharingSettings_async - */ + /** + * Get data sharing settings on an account. + * Data sharing settings are singletons. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the settings to lookup. + * Format: accounts/{account}/dataSharingSettings + * + * Example: `accounts/1000/dataSharingSettings` + * @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.analytics.admin.v1alpha.DataSharingSettings|DataSharingSettings}. + * 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/v1alpha/analytics_admin_service.get_data_sharing_settings.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetDataSharingSettings_async + */ getDataSharingSettings( - request?: protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IDataSharingSettings, - protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDataSharingSettings, + ( + | protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest + | undefined + ), + {} | undefined, + ] + >; getDataSharingSettings( - request: protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDataSharingSettings, - protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDataSharingSettings, + | protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDataSharingSettings( - request: protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDataSharingSettings, - protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDataSharingSettings, + | protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDataSharingSettings( - request?: protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IDataSharingSettings, - protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IDataSharingSettings, - protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IDataSharingSettings, - protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IDataSharingSettings, + | protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDataSharingSettings, + ( + | protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest + | 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('getDataSharingSettings request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IDataSharingSettings, - protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IDataSharingSettings, + | protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getDataSharingSettings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getDataSharingSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IDataSharingSettings, - protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('getDataSharingSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getDataSharingSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IDataSharingSettings, + ( + | protos.google.analytics.admin.v1alpha.IGetDataSharingSettingsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getDataSharingSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for a single MeasurementProtocolSecret. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the measurement protocol secret to lookup. - * Format: - * properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret} - * @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.analytics.admin.v1alpha.MeasurementProtocolSecret|MeasurementProtocolSecret}. - * 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/v1alpha/analytics_admin_service.get_measurement_protocol_secret.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetMeasurementProtocolSecret_async - */ + /** + * Lookup for a single MeasurementProtocolSecret. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the measurement protocol secret to lookup. + * Format: + * properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret} + * @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.analytics.admin.v1alpha.MeasurementProtocolSecret|MeasurementProtocolSecret}. + * 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/v1alpha/analytics_admin_service.get_measurement_protocol_secret.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetMeasurementProtocolSecret_async + */ getMeasurementProtocolSecret( - request?: protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, + ( + | protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest + | undefined + ), + {} | undefined, + ] + >; getMeasurementProtocolSecret( - request: protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getMeasurementProtocolSecret( - request: protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getMeasurementProtocolSecret( - request?: protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, + ( + | protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest + | 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('getMeasurementProtocolSecret request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getMeasurementProtocolSecret response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getMeasurementProtocolSecret(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest|undefined, - {}|undefined - ]) => { - this._log.info('getMeasurementProtocolSecret response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getMeasurementProtocolSecret(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, + ( + | protos.google.analytics.admin.v1alpha.IGetMeasurementProtocolSecretRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getMeasurementProtocolSecret response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a measurement protocol secret. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource where this secret will be created. - * Format: properties/{property}/dataStreams/{dataStream} - * @param {google.analytics.admin.v1alpha.MeasurementProtocolSecret} request.measurementProtocolSecret - * Required. The measurement protocol secret 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.analytics.admin.v1alpha.MeasurementProtocolSecret|MeasurementProtocolSecret}. - * 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/v1alpha/analytics_admin_service.create_measurement_protocol_secret.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateMeasurementProtocolSecret_async - */ + /** + * Creates a measurement protocol secret. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource where this secret will be created. + * Format: properties/{property}/dataStreams/{dataStream} + * @param {google.analytics.admin.v1alpha.MeasurementProtocolSecret} request.measurementProtocolSecret + * Required. The measurement protocol secret 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.analytics.admin.v1alpha.MeasurementProtocolSecret|MeasurementProtocolSecret}. + * 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/v1alpha/analytics_admin_service.create_measurement_protocol_secret.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateMeasurementProtocolSecret_async + */ createMeasurementProtocolSecret( - request?: protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, + ( + | protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest + | undefined + ), + {} | undefined, + ] + >; createMeasurementProtocolSecret( - request: protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createMeasurementProtocolSecret( - request: protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createMeasurementProtocolSecret( - request?: protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, + ( + | protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest + | 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('createMeasurementProtocolSecret request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('createMeasurementProtocolSecret response %j', response); + this._log.info( + 'createMeasurementProtocolSecret response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createMeasurementProtocolSecret(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest|undefined, - {}|undefined - ]) => { - this._log.info('createMeasurementProtocolSecret response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createMeasurementProtocolSecret(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, + ( + | protos.google.analytics.admin.v1alpha.ICreateMeasurementProtocolSecretRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'createMeasurementProtocolSecret response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes target MeasurementProtocolSecret. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the MeasurementProtocolSecret to delete. - * Format: - * properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret} - * @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/v1alpha/analytics_admin_service.delete_measurement_protocol_secret.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteMeasurementProtocolSecret_async - */ + /** + * Deletes target MeasurementProtocolSecret. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the MeasurementProtocolSecret to delete. + * Format: + * properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret} + * @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/v1alpha/analytics_admin_service.delete_measurement_protocol_secret.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteMeasurementProtocolSecret_async + */ deleteMeasurementProtocolSecret( - request?: protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest + | undefined + ), + {} | undefined, + ] + >; deleteMeasurementProtocolSecret( - request: protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteMeasurementProtocolSecret( - request: protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteMeasurementProtocolSecret( - request?: protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest + | 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('deleteMeasurementProtocolSecret request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('deleteMeasurementProtocolSecret response %j', response); + this._log.info( + 'deleteMeasurementProtocolSecret response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteMeasurementProtocolSecret(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteMeasurementProtocolSecret response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteMeasurementProtocolSecret(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteMeasurementProtocolSecretRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'deleteMeasurementProtocolSecret response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a measurement protocol secret. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.MeasurementProtocolSecret} request.measurementProtocolSecret - * Required. The measurement protocol secret to update. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Omitted fields will not 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.analytics.admin.v1alpha.MeasurementProtocolSecret|MeasurementProtocolSecret}. - * 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/v1alpha/analytics_admin_service.update_measurement_protocol_secret.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateMeasurementProtocolSecret_async - */ + /** + * Updates a measurement protocol secret. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.MeasurementProtocolSecret} request.measurementProtocolSecret + * Required. The measurement protocol secret to update. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Omitted fields will not 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.analytics.admin.v1alpha.MeasurementProtocolSecret|MeasurementProtocolSecret}. + * 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/v1alpha/analytics_admin_service.update_measurement_protocol_secret.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateMeasurementProtocolSecret_async + */ updateMeasurementProtocolSecret( - request?: protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, + ( + | protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest + | undefined + ), + {} | undefined, + ] + >; updateMeasurementProtocolSecret( - request: protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateMeasurementProtocolSecret( - request: protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateMeasurementProtocolSecret( - request?: protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, + ( + | protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest + | 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({ - 'measurement_protocol_secret.name': request.measurementProtocolSecret!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'measurement_protocol_secret.name': + request.measurementProtocolSecret!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateMeasurementProtocolSecret request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('updateMeasurementProtocolSecret response %j', response); + this._log.info( + 'updateMeasurementProtocolSecret response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateMeasurementProtocolSecret(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateMeasurementProtocolSecret response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateMeasurementProtocolSecret(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret, + ( + | protos.google.analytics.admin.v1alpha.IUpdateMeasurementProtocolSecretRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'updateMeasurementProtocolSecret response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Acknowledges the terms of user data collection for the specified property. - * - * This acknowledgement must be completed (either in the Google Analytics UI - * or through this API) before MeasurementProtocolSecret resources may be - * created. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.property - * Required. The property for which to acknowledge user data collection. - * @param {string} request.acknowledgement - * Required. An acknowledgement that the caller of this method understands the - * terms of user data collection. - * - * This field must contain the exact value: - * "I acknowledge that I have the necessary privacy disclosures and rights - * from my end users for the collection and processing of their data, - * including the association of such data with the visitation information - * Google Analytics collects from my site and/or app property." - * @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.analytics.admin.v1alpha.AcknowledgeUserDataCollectionResponse|AcknowledgeUserDataCollectionResponse}. - * 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/v1alpha/analytics_admin_service.acknowledge_user_data_collection.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_AcknowledgeUserDataCollection_async - */ + /** + * Acknowledges the terms of user data collection for the specified property. + * + * This acknowledgement must be completed (either in the Google Analytics UI + * or through this API) before MeasurementProtocolSecret resources may be + * created. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.property + * Required. The property for which to acknowledge user data collection. + * @param {string} request.acknowledgement + * Required. An acknowledgement that the caller of this method understands the + * terms of user data collection. + * + * This field must contain the exact value: + * "I acknowledge that I have the necessary privacy disclosures and rights + * from my end users for the collection and processing of their data, + * including the association of such data with the visitation information + * Google Analytics collects from my site and/or app property." + * @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.analytics.admin.v1alpha.AcknowledgeUserDataCollectionResponse|AcknowledgeUserDataCollectionResponse}. + * 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/v1alpha/analytics_admin_service.acknowledge_user_data_collection.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_AcknowledgeUserDataCollection_async + */ acknowledgeUserDataCollection( - request?: protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionResponse, - protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionResponse, + ( + | protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest + | undefined + ), + {} | undefined, + ] + >; acknowledgeUserDataCollection( - request: protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionResponse, - protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionResponse, + | protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; acknowledgeUserDataCollection( - request: protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionResponse, - protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionResponse, + | protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; acknowledgeUserDataCollection( - request?: protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionResponse, - protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionResponse, - protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionResponse, - protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionResponse, + | protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionResponse, + ( + | protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest + | 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({ - 'property': request.property ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + property: request.property ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('acknowledgeUserDataCollection request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionResponse, - protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionResponse, + | protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('acknowledgeUserDataCollection response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.acknowledgeUserDataCollection(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionResponse, - protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest|undefined, - {}|undefined - ]) => { - this._log.info('acknowledgeUserDataCollection response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .acknowledgeUserDataCollection(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionResponse, + ( + | protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('acknowledgeUserDataCollection response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Looks up a single SKAdNetworkConversionValueSchema. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of SKAdNetwork conversion value schema to look - * up. Format: - * properties/{property}/dataStreams/{dataStream}/sKAdNetworkConversionValueSchema/{skadnetwork_conversion_value_schema} - * @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.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema|SKAdNetworkConversionValueSchema}. - * 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/v1alpha/analytics_admin_service.get_s_k_ad_network_conversion_value_schema.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetSKAdNetworkConversionValueSchema_async - */ + /** + * Looks up a single SKAdNetworkConversionValueSchema. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of SKAdNetwork conversion value schema to look + * up. Format: + * properties/{property}/dataStreams/{dataStream}/sKAdNetworkConversionValueSchema/{skadnetwork_conversion_value_schema} + * @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.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema|SKAdNetworkConversionValueSchema}. + * 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/v1alpha/analytics_admin_service.get_s_k_ad_network_conversion_value_schema.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetSKAdNetworkConversionValueSchema_async + */ getSKAdNetworkConversionValueSchema( - request?: protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, + ( + | protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest + | undefined + ), + {} | undefined, + ] + >; getSKAdNetworkConversionValueSchema( - request: protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, + | protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getSKAdNetworkConversionValueSchema( - request: protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, + | protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getSKAdNetworkConversionValueSchema( - request?: protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, + | protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, + ( + | protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest + | 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('getSKAdNetworkConversionValueSchema request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, + | protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('getSKAdNetworkConversionValueSchema response %j', response); + this._log.info( + 'getSKAdNetworkConversionValueSchema response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getSkAdNetworkConversionValueSchema(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest|undefined, - {}|undefined - ]) => { - this._log.info('getSKAdNetworkConversionValueSchema response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getSkAdNetworkConversionValueSchema(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, + ( + | protos.google.analytics.admin.v1alpha.IGetSKAdNetworkConversionValueSchemaRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'getSKAdNetworkConversionValueSchema response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a SKAdNetworkConversionValueSchema. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource where this schema will be created. - * Format: properties/{property}/dataStreams/{dataStream} - * @param {google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema} request.skadnetworkConversionValueSchema - * Required. SKAdNetwork conversion value schema 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.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema|SKAdNetworkConversionValueSchema}. - * 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/v1alpha/analytics_admin_service.create_s_k_ad_network_conversion_value_schema.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateSKAdNetworkConversionValueSchema_async - */ + /** + * Creates a SKAdNetworkConversionValueSchema. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource where this schema will be created. + * Format: properties/{property}/dataStreams/{dataStream} + * @param {google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema} request.skadnetworkConversionValueSchema + * Required. SKAdNetwork conversion value schema 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.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema|SKAdNetworkConversionValueSchema}. + * 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/v1alpha/analytics_admin_service.create_s_k_ad_network_conversion_value_schema.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateSKAdNetworkConversionValueSchema_async + */ createSKAdNetworkConversionValueSchema( - request?: protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, + ( + | protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest + | undefined + ), + {} | undefined, + ] + >; createSKAdNetworkConversionValueSchema( - request: protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, + | protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createSKAdNetworkConversionValueSchema( - request: protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, + | protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createSKAdNetworkConversionValueSchema( - request?: protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, + | protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, + ( + | protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest + | 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('createSKAdNetworkConversionValueSchema request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest|null|undefined, - {}|null|undefined>|undefined = callback + this._log.info( + 'createSKAdNetworkConversionValueSchema request %j', + request, + ); + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, + | protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('createSKAdNetworkConversionValueSchema response %j', response); + this._log.info( + 'createSKAdNetworkConversionValueSchema response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createSkAdNetworkConversionValueSchema(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest|undefined, - {}|undefined - ]) => { - this._log.info('createSKAdNetworkConversionValueSchema response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createSkAdNetworkConversionValueSchema(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, + ( + | protos.google.analytics.admin.v1alpha.ICreateSKAdNetworkConversionValueSchemaRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'createSKAdNetworkConversionValueSchema response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes target SKAdNetworkConversionValueSchema. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the SKAdNetworkConversionValueSchema to delete. - * Format: - * properties/{property}/dataStreams/{dataStream}/sKAdNetworkConversionValueSchema/{skadnetwork_conversion_value_schema} - * @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/v1alpha/analytics_admin_service.delete_s_k_ad_network_conversion_value_schema.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteSKAdNetworkConversionValueSchema_async - */ + /** + * Deletes target SKAdNetworkConversionValueSchema. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the SKAdNetworkConversionValueSchema to delete. + * Format: + * properties/{property}/dataStreams/{dataStream}/sKAdNetworkConversionValueSchema/{skadnetwork_conversion_value_schema} + * @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/v1alpha/analytics_admin_service.delete_s_k_ad_network_conversion_value_schema.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteSKAdNetworkConversionValueSchema_async + */ deleteSKAdNetworkConversionValueSchema( - request?: protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest + | undefined + ), + {} | undefined, + ] + >; deleteSKAdNetworkConversionValueSchema( - request: protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteSKAdNetworkConversionValueSchema( - request: protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteSKAdNetworkConversionValueSchema( - request?: protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest + | 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('deleteSKAdNetworkConversionValueSchema request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest|null|undefined, - {}|null|undefined>|undefined = callback + this._log.info( + 'deleteSKAdNetworkConversionValueSchema request %j', + request, + ); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('deleteSKAdNetworkConversionValueSchema response %j', response); + this._log.info( + 'deleteSKAdNetworkConversionValueSchema response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteSkAdNetworkConversionValueSchema(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteSKAdNetworkConversionValueSchema response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteSkAdNetworkConversionValueSchema(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteSKAdNetworkConversionValueSchemaRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'deleteSKAdNetworkConversionValueSchema response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a SKAdNetworkConversionValueSchema. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema} request.skadnetworkConversionValueSchema - * Required. SKAdNetwork conversion value schema to update. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Omitted fields will not 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.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema|SKAdNetworkConversionValueSchema}. - * 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/v1alpha/analytics_admin_service.update_s_k_ad_network_conversion_value_schema.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateSKAdNetworkConversionValueSchema_async - */ + /** + * Updates a SKAdNetworkConversionValueSchema. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema} request.skadnetworkConversionValueSchema + * Required. SKAdNetwork conversion value schema to update. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Omitted fields will not 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.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema|SKAdNetworkConversionValueSchema}. + * 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/v1alpha/analytics_admin_service.update_s_k_ad_network_conversion_value_schema.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateSKAdNetworkConversionValueSchema_async + */ updateSKAdNetworkConversionValueSchema( - request?: protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, + ( + | protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest + | undefined + ), + {} | undefined, + ] + >; updateSKAdNetworkConversionValueSchema( - request: protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, + | protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateSKAdNetworkConversionValueSchema( - request: protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, + | protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateSKAdNetworkConversionValueSchema( - request?: protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, + | protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, + ( + | protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest + | 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({ - 'skadnetwork_conversion_value_schema.name': request.skadnetworkConversionValueSchema!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'skadnetwork_conversion_value_schema.name': + request.skadnetworkConversionValueSchema!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - this._log.info('updateSKAdNetworkConversionValueSchema request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest|null|undefined, - {}|null|undefined>|undefined = callback + this._log.info( + 'updateSKAdNetworkConversionValueSchema request %j', + request, + ); + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, + | protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('updateSKAdNetworkConversionValueSchema response %j', response); + this._log.info( + 'updateSKAdNetworkConversionValueSchema response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateSkAdNetworkConversionValueSchema(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, - protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateSKAdNetworkConversionValueSchema response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateSkAdNetworkConversionValueSchema(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema, + ( + | protos.google.analytics.admin.v1alpha.IUpdateSKAdNetworkConversionValueSchemaRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'updateSKAdNetworkConversionValueSchema response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for Google Signals settings for a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the google signals settings to retrieve. - * Format: properties/{property}/googleSignalsSettings - * @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.analytics.admin.v1alpha.GoogleSignalsSettings|GoogleSignalsSettings}. - * 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/v1alpha/analytics_admin_service.get_google_signals_settings.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetGoogleSignalsSettings_async - */ + /** + * Lookup for Google Signals settings for a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the google signals settings to retrieve. + * Format: properties/{property}/googleSignalsSettings + * @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.analytics.admin.v1alpha.GoogleSignalsSettings|GoogleSignalsSettings}. + * 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/v1alpha/analytics_admin_service.get_google_signals_settings.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetGoogleSignalsSettings_async + */ getGoogleSignalsSettings( - request?: protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, - protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, + ( + | protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest + | undefined + ), + {} | undefined, + ] + >; getGoogleSignalsSettings( - request: protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, - protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, + | protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getGoogleSignalsSettings( - request: protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, - protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, + | protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getGoogleSignalsSettings( - request?: protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, - protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, - protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, - protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, + | protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, + ( + | protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest + | 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('getGoogleSignalsSettings request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, - protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, + | protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getGoogleSignalsSettings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getGoogleSignalsSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, - protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('getGoogleSignalsSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getGoogleSignalsSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, + ( + | protos.google.analytics.admin.v1alpha.IGetGoogleSignalsSettingsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getGoogleSignalsSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates Google Signals settings for a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.GoogleSignalsSettings} request.googleSignalsSettings - * Required. The settings to update. - * The `name` field is used to identify the settings to be updated. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Field names must be in snake - * case (e.g., "field_to_update"). Omitted fields will not be updated. To - * replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1alpha.GoogleSignalsSettings|GoogleSignalsSettings}. - * 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/v1alpha/analytics_admin_service.update_google_signals_settings.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateGoogleSignalsSettings_async - */ + /** + * Updates Google Signals settings for a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.GoogleSignalsSettings} request.googleSignalsSettings + * Required. The settings to update. + * The `name` field is used to identify the settings to be updated. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Field names must be in snake + * case (e.g., "field_to_update"). Omitted fields will not be updated. To + * replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1alpha.GoogleSignalsSettings|GoogleSignalsSettings}. + * 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/v1alpha/analytics_admin_service.update_google_signals_settings.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateGoogleSignalsSettings_async + */ updateGoogleSignalsSettings( - request?: protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, - protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, + ( + | protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest + | undefined + ), + {} | undefined, + ] + >; updateGoogleSignalsSettings( - request: protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, - protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, + | protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateGoogleSignalsSettings( - request: protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, - protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, + | protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateGoogleSignalsSettings( - request?: protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, - protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, - protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, - protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, + | protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, + ( + | protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest + | 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({ - 'google_signals_settings.name': request.googleSignalsSettings!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'google_signals_settings.name': + request.googleSignalsSettings!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateGoogleSignalsSettings request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, - protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, + | protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateGoogleSignalsSettings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateGoogleSignalsSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, - protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateGoogleSignalsSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateGoogleSignalsSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings, + ( + | protos.google.analytics.admin.v1alpha.IUpdateGoogleSignalsSettingsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateGoogleSignalsSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deprecated: Use `CreateKeyEvent` instead. - * Creates a conversion event with the specified attributes. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.ConversionEvent} request.conversionEvent - * Required. The conversion event to create. - * @param {string} request.parent - * Required. The resource name of the parent property where this conversion - * event will be created. Format: properties/123 - * @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.analytics.admin.v1alpha.ConversionEvent|ConversionEvent}. - * 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/v1alpha/analytics_admin_service.create_conversion_event.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateConversionEvent_async - * @deprecated CreateConversionEvent is deprecated and may be removed in a future version. - */ + /** + * Deprecated: Use `CreateKeyEvent` instead. + * Creates a conversion event with the specified attributes. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.ConversionEvent} request.conversionEvent + * Required. The conversion event to create. + * @param {string} request.parent + * Required. The resource name of the parent property where this conversion + * event will be created. Format: properties/123 + * @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.analytics.admin.v1alpha.ConversionEvent|ConversionEvent}. + * 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/v1alpha/analytics_admin_service.create_conversion_event.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateConversionEvent_async + * @deprecated CreateConversionEvent is deprecated and may be removed in a future version. + */ createConversionEvent( - request?: protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IConversionEvent, + ( + | protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest + | undefined + ), + {} | undefined, + ] + >; createConversionEvent( - request: protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IConversionEvent, + | protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createConversionEvent( - request: protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IConversionEvent, + | protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createConversionEvent( - request?: protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IConversionEvent, + | protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IConversionEvent, + ( + | protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest + | 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.warn('DEP$AnalyticsAdminService-$CreateConversionEvent','CreateConversionEvent is deprecated and may be removed in a future version.', 'DeprecationWarning'); + this.warn( + 'DEP$AnalyticsAdminService-$CreateConversionEvent', + 'CreateConversionEvent is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); this._log.info('createConversionEvent request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IConversionEvent, + | protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createConversionEvent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createConversionEvent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest|undefined, - {}|undefined - ]) => { - this._log.info('createConversionEvent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createConversionEvent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IConversionEvent, + ( + | protos.google.analytics.admin.v1alpha.ICreateConversionEventRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createConversionEvent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deprecated: Use `UpdateKeyEvent` instead. - * Updates a conversion event with the specified attributes. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.ConversionEvent} request.conversionEvent - * Required. The conversion event to update. - * The `name` field is used to identify the settings to be updated. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Field names must be in snake - * case (e.g., "field_to_update"). Omitted fields will not be updated. To - * replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1alpha.ConversionEvent|ConversionEvent}. - * 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/v1alpha/analytics_admin_service.update_conversion_event.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateConversionEvent_async - * @deprecated UpdateConversionEvent is deprecated and may be removed in a future version. - */ + /** + * Deprecated: Use `UpdateKeyEvent` instead. + * Updates a conversion event with the specified attributes. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.ConversionEvent} request.conversionEvent + * Required. The conversion event to update. + * The `name` field is used to identify the settings to be updated. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Field names must be in snake + * case (e.g., "field_to_update"). Omitted fields will not be updated. To + * replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1alpha.ConversionEvent|ConversionEvent}. + * 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/v1alpha/analytics_admin_service.update_conversion_event.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateConversionEvent_async + * @deprecated UpdateConversionEvent is deprecated and may be removed in a future version. + */ updateConversionEvent( - request?: protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IConversionEvent, + ( + | protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest + | undefined + ), + {} | undefined, + ] + >; updateConversionEvent( - request: protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IConversionEvent, + | protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateConversionEvent( - request: protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IConversionEvent, + | protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateConversionEvent( - request?: protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IConversionEvent, + | protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IConversionEvent, + ( + | protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest + | 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({ - 'conversion_event.name': request.conversionEvent!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'conversion_event.name': request.conversionEvent!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - this.warn('DEP$AnalyticsAdminService-$UpdateConversionEvent','UpdateConversionEvent is deprecated and may be removed in a future version.', 'DeprecationWarning'); + this.warn( + 'DEP$AnalyticsAdminService-$UpdateConversionEvent', + 'UpdateConversionEvent is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); this._log.info('updateConversionEvent request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IConversionEvent, + | protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateConversionEvent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateConversionEvent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateConversionEvent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateConversionEvent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IConversionEvent, + ( + | protos.google.analytics.admin.v1alpha.IUpdateConversionEventRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateConversionEvent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deprecated: Use `GetKeyEvent` instead. - * Retrieve a single conversion event. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the conversion event to retrieve. - * Format: properties/{property}/conversionEvents/{conversion_event} - * Example: "properties/123/conversionEvents/456" - * @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.analytics.admin.v1alpha.ConversionEvent|ConversionEvent}. - * 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/v1alpha/analytics_admin_service.get_conversion_event.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetConversionEvent_async - * @deprecated GetConversionEvent is deprecated and may be removed in a future version. - */ + /** + * Deprecated: Use `GetKeyEvent` instead. + * Retrieve a single conversion event. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the conversion event to retrieve. + * Format: properties/{property}/conversionEvents/{conversion_event} + * Example: "properties/123/conversionEvents/456" + * @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.analytics.admin.v1alpha.ConversionEvent|ConversionEvent}. + * 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/v1alpha/analytics_admin_service.get_conversion_event.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetConversionEvent_async + * @deprecated GetConversionEvent is deprecated and may be removed in a future version. + */ getConversionEvent( - request?: protos.google.analytics.admin.v1alpha.IGetConversionEventRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.IGetConversionEventRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetConversionEventRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IConversionEvent, + ( + | protos.google.analytics.admin.v1alpha.IGetConversionEventRequest + | undefined + ), + {} | undefined, + ] + >; getConversionEvent( - request: protos.google.analytics.admin.v1alpha.IGetConversionEventRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.IGetConversionEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetConversionEventRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IConversionEvent, + | protos.google.analytics.admin.v1alpha.IGetConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getConversionEvent( - request: protos.google.analytics.admin.v1alpha.IGetConversionEventRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.IGetConversionEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetConversionEventRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IConversionEvent, + | protos.google.analytics.admin.v1alpha.IGetConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getConversionEvent( - request?: protos.google.analytics.admin.v1alpha.IGetConversionEventRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.IGetConversionEventRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IGetConversionEventRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.IGetConversionEventRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.IGetConversionEventRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IConversionEvent, + | protos.google.analytics.admin.v1alpha.IGetConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IConversionEvent, + ( + | protos.google.analytics.admin.v1alpha.IGetConversionEventRequest + | 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.warn('DEP$AnalyticsAdminService-$GetConversionEvent','GetConversionEvent is deprecated and may be removed in a future version.', 'DeprecationWarning'); + this.warn( + 'DEP$AnalyticsAdminService-$GetConversionEvent', + 'GetConversionEvent is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); this._log.info('getConversionEvent request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.IGetConversionEventRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IConversionEvent, + | protos.google.analytics.admin.v1alpha.IGetConversionEventRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getConversionEvent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getConversionEvent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IConversionEvent, - protos.google.analytics.admin.v1alpha.IGetConversionEventRequest|undefined, - {}|undefined - ]) => { - this._log.info('getConversionEvent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getConversionEvent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IConversionEvent, + ( + | protos.google.analytics.admin.v1alpha.IGetConversionEventRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getConversionEvent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deprecated: Use `DeleteKeyEvent` instead. - * Deletes a conversion event in a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the conversion event to delete. - * Format: properties/{property}/conversionEvents/{conversion_event} - * Example: "properties/123/conversionEvents/456" - * @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/v1alpha/analytics_admin_service.delete_conversion_event.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteConversionEvent_async - * @deprecated DeleteConversionEvent is deprecated and may be removed in a future version. - */ + /** + * Deprecated: Use `DeleteKeyEvent` instead. + * Deletes a conversion event in a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the conversion event to delete. + * Format: properties/{property}/conversionEvents/{conversion_event} + * Example: "properties/123/conversionEvents/456" + * @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/v1alpha/analytics_admin_service.delete_conversion_event.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteConversionEvent_async + * @deprecated DeleteConversionEvent is deprecated and may be removed in a future version. + */ deleteConversionEvent( - request?: protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest + | undefined + ), + {} | undefined, + ] + >; deleteConversionEvent( - request: protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteConversionEvent( - request: protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteConversionEvent( - request?: protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest + | 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.warn('DEP$AnalyticsAdminService-$DeleteConversionEvent','DeleteConversionEvent is deprecated and may be removed in a future version.', 'DeprecationWarning'); + this.warn( + 'DEP$AnalyticsAdminService-$DeleteConversionEvent', + 'DeleteConversionEvent is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); this._log.info('deleteConversionEvent request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteConversionEvent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteConversionEvent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteConversionEvent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteConversionEvent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteConversionEventRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteConversionEvent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a Key Event. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.KeyEvent} request.keyEvent - * Required. The Key Event to create. - * @param {string} request.parent - * Required. The resource name of the parent property where this Key Event - * will be created. Format: properties/123 - * @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.analytics.admin.v1alpha.KeyEvent|KeyEvent}. - * 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/v1alpha/analytics_admin_service.create_key_event.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateKeyEvent_async - */ + /** + * Creates a Key Event. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.KeyEvent} request.keyEvent + * Required. The Key Event to create. + * @param {string} request.parent + * Required. The resource name of the parent property where this Key Event + * will be created. Format: properties/123 + * @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.analytics.admin.v1alpha.KeyEvent|KeyEvent}. + * 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/v1alpha/analytics_admin_service.create_key_event.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateKeyEvent_async + */ createKeyEvent( - request?: protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IKeyEvent, + protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest | undefined, + {} | undefined, + ] + >; createKeyEvent( - request: protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IKeyEvent, + | protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createKeyEvent( - request: protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IKeyEvent, + | protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createKeyEvent( - request?: protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IKeyEvent, + | protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IKeyEvent, + protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest | 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('createKeyEvent request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IKeyEvent, + | protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createKeyEvent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createKeyEvent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest|undefined, - {}|undefined - ]) => { - this._log.info('createKeyEvent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createKeyEvent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IKeyEvent, + ( + | protos.google.analytics.admin.v1alpha.ICreateKeyEventRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createKeyEvent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a Key Event. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.KeyEvent} request.keyEvent - * Required. The Key Event to update. - * The `name` field is used to identify the settings to be updated. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Field names must be in snake - * case (e.g., "field_to_update"). Omitted fields will not be updated. To - * replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1alpha.KeyEvent|KeyEvent}. - * 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/v1alpha/analytics_admin_service.update_key_event.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateKeyEvent_async - */ + /** + * Updates a Key Event. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.KeyEvent} request.keyEvent + * Required. The Key Event to update. + * The `name` field is used to identify the settings to be updated. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Field names must be in snake + * case (e.g., "field_to_update"). Omitted fields will not be updated. To + * replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1alpha.KeyEvent|KeyEvent}. + * 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/v1alpha/analytics_admin_service.update_key_event.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateKeyEvent_async + */ updateKeyEvent( - request?: protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IKeyEvent, + protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest | undefined, + {} | undefined, + ] + >; updateKeyEvent( - request: protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IKeyEvent, + | protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateKeyEvent( - request: protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IKeyEvent, + | protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateKeyEvent( - request?: protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IKeyEvent, + | protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IKeyEvent, + protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest | 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({ - 'key_event.name': request.keyEvent!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'key_event.name': request.keyEvent!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateKeyEvent request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IKeyEvent, + | protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateKeyEvent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateKeyEvent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateKeyEvent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateKeyEvent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IKeyEvent, + ( + | protos.google.analytics.admin.v1alpha.IUpdateKeyEventRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateKeyEvent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieve a single Key Event. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the Key Event to retrieve. - * Format: properties/{property}/keyEvents/{key_event} - * Example: "properties/123/keyEvents/456" - * @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.analytics.admin.v1alpha.KeyEvent|KeyEvent}. - * 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/v1alpha/analytics_admin_service.get_key_event.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetKeyEvent_async - */ + /** + * Retrieve a single Key Event. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Key Event to retrieve. + * Format: properties/{property}/keyEvents/{key_event} + * Example: "properties/123/keyEvents/456" + * @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.analytics.admin.v1alpha.KeyEvent|KeyEvent}. + * 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/v1alpha/analytics_admin_service.get_key_event.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetKeyEvent_async + */ getKeyEvent( - request?: protos.google.analytics.admin.v1alpha.IGetKeyEventRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.IGetKeyEventRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetKeyEventRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IKeyEvent, + protos.google.analytics.admin.v1alpha.IGetKeyEventRequest | undefined, + {} | undefined, + ] + >; getKeyEvent( - request: protos.google.analytics.admin.v1alpha.IGetKeyEventRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.IGetKeyEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetKeyEventRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IKeyEvent, + | protos.google.analytics.admin.v1alpha.IGetKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getKeyEvent( - request: protos.google.analytics.admin.v1alpha.IGetKeyEventRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.IGetKeyEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetKeyEventRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IKeyEvent, + | protos.google.analytics.admin.v1alpha.IGetKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getKeyEvent( - request?: protos.google.analytics.admin.v1alpha.IGetKeyEventRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IGetKeyEventRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.IGetKeyEventRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.IGetKeyEventRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.IGetKeyEventRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IKeyEvent, + | protos.google.analytics.admin.v1alpha.IGetKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IKeyEvent, + protos.google.analytics.admin.v1alpha.IGetKeyEventRequest | 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('getKeyEvent request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.IGetKeyEventRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IKeyEvent, + | protos.google.analytics.admin.v1alpha.IGetKeyEventRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getKeyEvent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getKeyEvent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IKeyEvent, - protos.google.analytics.admin.v1alpha.IGetKeyEventRequest|undefined, - {}|undefined - ]) => { - this._log.info('getKeyEvent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getKeyEvent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IKeyEvent, + protos.google.analytics.admin.v1alpha.IGetKeyEventRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getKeyEvent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a Key Event. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the Key Event to delete. - * Format: properties/{property}/keyEvents/{key_event} - * Example: "properties/123/keyEvents/456" - * @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/v1alpha/analytics_admin_service.delete_key_event.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteKeyEvent_async - */ + /** + * Deletes a Key Event. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Key Event to delete. + * Format: properties/{property}/keyEvents/{key_event} + * Example: "properties/123/keyEvents/456" + * @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/v1alpha/analytics_admin_service.delete_key_event.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteKeyEvent_async + */ deleteKeyEvent( - request?: protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest | undefined, + {} | undefined, + ] + >; deleteKeyEvent( - request: protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteKeyEvent( - request: protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteKeyEvent( - request?: protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest | 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('deleteKeyEvent request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteKeyEvent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteKeyEvent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteKeyEvent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteKeyEvent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteKeyEventRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteKeyEvent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Look up a single DisplayVideo360AdvertiserLink - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the DisplayVideo360AdvertiserLink to get. - * Example format: properties/1234/displayVideo360AdvertiserLink/5678 - * @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.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink|DisplayVideo360AdvertiserLink}. - * 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/v1alpha/analytics_admin_service.get_display_video360_advertiser_link.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetDisplayVideo360AdvertiserLink_async - */ + /** + * Look up a single DisplayVideo360AdvertiserLink + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the DisplayVideo360AdvertiserLink to get. + * Example format: properties/1234/displayVideo360AdvertiserLink/5678 + * @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.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink|DisplayVideo360AdvertiserLink}. + * 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/v1alpha/analytics_admin_service.get_display_video360_advertiser_link.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetDisplayVideo360AdvertiserLink_async + */ getDisplayVideo360AdvertiserLink( - request?: protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, + ( + | protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest + | undefined + ), + {} | undefined, + ] + >; getDisplayVideo360AdvertiserLink( - request: protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, + | protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDisplayVideo360AdvertiserLink( - request: protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, + | protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDisplayVideo360AdvertiserLink( - request?: protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, + | protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, + ( + | protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest + | 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('getDisplayVideo360AdvertiserLink request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, + | protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('getDisplayVideo360AdvertiserLink response %j', response); + this._log.info( + 'getDisplayVideo360AdvertiserLink response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getDisplayVideo360AdvertiserLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('getDisplayVideo360AdvertiserLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getDisplayVideo360AdvertiserLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, + ( + | protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'getDisplayVideo360AdvertiserLink response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a DisplayVideo360AdvertiserLink. - * This can only be utilized by users who have proper authorization both on - * the Google Analytics property and on the Display & Video 360 advertiser. - * Users who do not have access to the Display & Video 360 advertiser should - * instead seek to create a DisplayVideo360LinkProposal. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink} request.displayVideo_360AdvertiserLink - * Required. The DisplayVideo360AdvertiserLink 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.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink|DisplayVideo360AdvertiserLink}. - * 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/v1alpha/analytics_admin_service.create_display_video360_advertiser_link.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateDisplayVideo360AdvertiserLink_async - */ + /** + * Creates a DisplayVideo360AdvertiserLink. + * This can only be utilized by users who have proper authorization both on + * the Google Analytics property and on the Display & Video 360 advertiser. + * Users who do not have access to the Display & Video 360 advertiser should + * instead seek to create a DisplayVideo360LinkProposal. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink} request.displayVideo_360AdvertiserLink + * Required. The DisplayVideo360AdvertiserLink 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.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink|DisplayVideo360AdvertiserLink}. + * 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/v1alpha/analytics_admin_service.create_display_video360_advertiser_link.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateDisplayVideo360AdvertiserLink_async + */ createDisplayVideo360AdvertiserLink( - request?: protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, + ( + | protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest + | undefined + ), + {} | undefined, + ] + >; createDisplayVideo360AdvertiserLink( - request: protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, + | protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createDisplayVideo360AdvertiserLink( - request: protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, + | protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createDisplayVideo360AdvertiserLink( - request?: protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, + | protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, + ( + | protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest + | 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('createDisplayVideo360AdvertiserLink request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, + | protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('createDisplayVideo360AdvertiserLink response %j', response); + this._log.info( + 'createDisplayVideo360AdvertiserLink response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createDisplayVideo360AdvertiserLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('createDisplayVideo360AdvertiserLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createDisplayVideo360AdvertiserLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, + ( + | protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'createDisplayVideo360AdvertiserLink response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a DisplayVideo360AdvertiserLink on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the DisplayVideo360AdvertiserLink to delete. - * Example format: properties/1234/displayVideo360AdvertiserLinks/5678 - * @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/v1alpha/analytics_admin_service.delete_display_video360_advertiser_link.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteDisplayVideo360AdvertiserLink_async - */ + /** + * Deletes a DisplayVideo360AdvertiserLink on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the DisplayVideo360AdvertiserLink to delete. + * Example format: properties/1234/displayVideo360AdvertiserLinks/5678 + * @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/v1alpha/analytics_admin_service.delete_display_video360_advertiser_link.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteDisplayVideo360AdvertiserLink_async + */ deleteDisplayVideo360AdvertiserLink( - request?: protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest + | undefined + ), + {} | undefined, + ] + >; deleteDisplayVideo360AdvertiserLink( - request: protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteDisplayVideo360AdvertiserLink( - request: protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteDisplayVideo360AdvertiserLink( - request?: protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest + | 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('deleteDisplayVideo360AdvertiserLink request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('deleteDisplayVideo360AdvertiserLink response %j', response); + this._log.info( + 'deleteDisplayVideo360AdvertiserLink response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteDisplayVideo360AdvertiserLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteDisplayVideo360AdvertiserLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteDisplayVideo360AdvertiserLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'deleteDisplayVideo360AdvertiserLink response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a DisplayVideo360AdvertiserLink on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink} request.displayVideo_360AdvertiserLink - * The DisplayVideo360AdvertiserLink to update - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Omitted fields will not be - * updated. To replace the entire entity, use one path with the string "*" to - * match all fields. - * @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.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink|DisplayVideo360AdvertiserLink}. - * 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/v1alpha/analytics_admin_service.update_display_video360_advertiser_link.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateDisplayVideo360AdvertiserLink_async - */ + /** + * Updates a DisplayVideo360AdvertiserLink on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink} request.displayVideo_360AdvertiserLink + * The DisplayVideo360AdvertiserLink to update + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Omitted fields will not be + * updated. To replace the entire entity, use one path with the string "*" to + * match all fields. + * @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.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink|DisplayVideo360AdvertiserLink}. + * 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/v1alpha/analytics_admin_service.update_display_video360_advertiser_link.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateDisplayVideo360AdvertiserLink_async + */ updateDisplayVideo360AdvertiserLink( - request?: protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, + ( + | protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest + | undefined + ), + {} | undefined, + ] + >; updateDisplayVideo360AdvertiserLink( - request: protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, + | protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDisplayVideo360AdvertiserLink( - request: protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, + | protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDisplayVideo360AdvertiserLink( - request?: protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, + | protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, + ( + | protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest + | 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({ - 'display_video_360_advertiser_link.name': request.displayVideo_360AdvertiserLink!.name?.toString() ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'display_video_360_advertiser_link.name': + request.displayVideo_360AdvertiserLink!.name?.toString() ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateDisplayVideo360AdvertiserLink request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, + | protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('updateDisplayVideo360AdvertiserLink response %j', response); + this._log.info( + 'updateDisplayVideo360AdvertiserLink response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateDisplayVideo360AdvertiserLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, - protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateDisplayVideo360AdvertiserLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateDisplayVideo360AdvertiserLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink, + ( + | protos.google.analytics.admin.v1alpha.IUpdateDisplayVideo360AdvertiserLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'updateDisplayVideo360AdvertiserLink response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for a single DisplayVideo360AdvertiserLinkProposal. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the DisplayVideo360AdvertiserLinkProposal to get. - * Example format: properties/1234/displayVideo360AdvertiserLinkProposals/5678 - * @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.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal|DisplayVideo360AdvertiserLinkProposal}. - * 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/v1alpha/analytics_admin_service.get_display_video360_advertiser_link_proposal.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetDisplayVideo360AdvertiserLinkProposal_async - */ + /** + * Lookup for a single DisplayVideo360AdvertiserLinkProposal. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the DisplayVideo360AdvertiserLinkProposal to get. + * Example format: properties/1234/displayVideo360AdvertiserLinkProposals/5678 + * @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.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal|DisplayVideo360AdvertiserLinkProposal}. + * 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/v1alpha/analytics_admin_service.get_display_video360_advertiser_link_proposal.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetDisplayVideo360AdvertiserLinkProposal_async + */ getDisplayVideo360AdvertiserLinkProposal( - request?: protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, + ( + | protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest + | undefined + ), + {} | undefined, + ] + >; getDisplayVideo360AdvertiserLinkProposal( - request: protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, + | protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDisplayVideo360AdvertiserLinkProposal( - request: protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, + | protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDisplayVideo360AdvertiserLinkProposal( - request?: protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, + | protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, + ( + | protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest + | 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('getDisplayVideo360AdvertiserLinkProposal request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>|undefined = callback + this._log.info( + 'getDisplayVideo360AdvertiserLinkProposal request %j', + request, + ); + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, + | protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('getDisplayVideo360AdvertiserLinkProposal response %j', response); + this._log.info( + 'getDisplayVideo360AdvertiserLinkProposal response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getDisplayVideo360AdvertiserLinkProposal(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest|undefined, - {}|undefined - ]) => { - this._log.info('getDisplayVideo360AdvertiserLinkProposal response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getDisplayVideo360AdvertiserLinkProposal( + request, + options, + wrappedCallback, + ) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, + ( + | protos.google.analytics.admin.v1alpha.IGetDisplayVideo360AdvertiserLinkProposalRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'getDisplayVideo360AdvertiserLinkProposal response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a DisplayVideo360AdvertiserLinkProposal. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal} request.displayVideo_360AdvertiserLinkProposal - * Required. The DisplayVideo360AdvertiserLinkProposal 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.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal|DisplayVideo360AdvertiserLinkProposal}. - * 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/v1alpha/analytics_admin_service.create_display_video360_advertiser_link_proposal.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateDisplayVideo360AdvertiserLinkProposal_async - */ + /** + * Creates a DisplayVideo360AdvertiserLinkProposal. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal} request.displayVideo_360AdvertiserLinkProposal + * Required. The DisplayVideo360AdvertiserLinkProposal 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.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal|DisplayVideo360AdvertiserLinkProposal}. + * 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/v1alpha/analytics_admin_service.create_display_video360_advertiser_link_proposal.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateDisplayVideo360AdvertiserLinkProposal_async + */ createDisplayVideo360AdvertiserLinkProposal( - request?: protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, + ( + | protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest + | undefined + ), + {} | undefined, + ] + >; createDisplayVideo360AdvertiserLinkProposal( - request: protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, + | protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createDisplayVideo360AdvertiserLinkProposal( - request: protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, + | protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createDisplayVideo360AdvertiserLinkProposal( - request?: protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, + | protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, + ( + | protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest + | 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('createDisplayVideo360AdvertiserLinkProposal request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>|undefined = callback + this._log.info( + 'createDisplayVideo360AdvertiserLinkProposal request %j', + request, + ); + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, + | protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('createDisplayVideo360AdvertiserLinkProposal response %j', response); + this._log.info( + 'createDisplayVideo360AdvertiserLinkProposal response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createDisplayVideo360AdvertiserLinkProposal(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest|undefined, - {}|undefined - ]) => { - this._log.info('createDisplayVideo360AdvertiserLinkProposal response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createDisplayVideo360AdvertiserLinkProposal( + request, + options, + wrappedCallback, + ) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, + ( + | protos.google.analytics.admin.v1alpha.ICreateDisplayVideo360AdvertiserLinkProposalRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'createDisplayVideo360AdvertiserLinkProposal response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a DisplayVideo360AdvertiserLinkProposal on a property. - * This can only be used on cancelled proposals. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the DisplayVideo360AdvertiserLinkProposal to delete. - * Example format: properties/1234/displayVideo360AdvertiserLinkProposals/5678 - * @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/v1alpha/analytics_admin_service.delete_display_video360_advertiser_link_proposal.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteDisplayVideo360AdvertiserLinkProposal_async - */ + /** + * Deletes a DisplayVideo360AdvertiserLinkProposal on a property. + * This can only be used on cancelled proposals. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the DisplayVideo360AdvertiserLinkProposal to delete. + * Example format: properties/1234/displayVideo360AdvertiserLinkProposals/5678 + * @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/v1alpha/analytics_admin_service.delete_display_video360_advertiser_link_proposal.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteDisplayVideo360AdvertiserLinkProposal_async + */ deleteDisplayVideo360AdvertiserLinkProposal( - request?: protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest + | undefined + ), + {} | undefined, + ] + >; deleteDisplayVideo360AdvertiserLinkProposal( - request: protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteDisplayVideo360AdvertiserLinkProposal( - request: protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteDisplayVideo360AdvertiserLinkProposal( - request?: protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest + | 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('deleteDisplayVideo360AdvertiserLinkProposal request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>|undefined = callback + this._log.info( + 'deleteDisplayVideo360AdvertiserLinkProposal request %j', + request, + ); + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('deleteDisplayVideo360AdvertiserLinkProposal response %j', response); + this._log.info( + 'deleteDisplayVideo360AdvertiserLinkProposal response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteDisplayVideo360AdvertiserLinkProposal(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteDisplayVideo360AdvertiserLinkProposal response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteDisplayVideo360AdvertiserLinkProposal( + request, + options, + wrappedCallback, + ) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteDisplayVideo360AdvertiserLinkProposalRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'deleteDisplayVideo360AdvertiserLinkProposal response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Approves a DisplayVideo360AdvertiserLinkProposal. - * The DisplayVideo360AdvertiserLinkProposal will be deleted and a new - * DisplayVideo360AdvertiserLink will be created. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the DisplayVideo360AdvertiserLinkProposal to approve. - * Example format: properties/1234/displayVideo360AdvertiserLinkProposals/5678 - * @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.analytics.admin.v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalResponse|ApproveDisplayVideo360AdvertiserLinkProposalResponse}. - * 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/v1alpha/analytics_admin_service.approve_display_video360_advertiser_link_proposal.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ApproveDisplayVideo360AdvertiserLinkProposal_async - */ + /** + * Approves a DisplayVideo360AdvertiserLinkProposal. + * The DisplayVideo360AdvertiserLinkProposal will be deleted and a new + * DisplayVideo360AdvertiserLink will be created. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the DisplayVideo360AdvertiserLinkProposal to approve. + * Example format: properties/1234/displayVideo360AdvertiserLinkProposals/5678 + * @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.analytics.admin.v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalResponse|ApproveDisplayVideo360AdvertiserLinkProposalResponse}. + * 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/v1alpha/analytics_admin_service.approve_display_video360_advertiser_link_proposal.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ApproveDisplayVideo360AdvertiserLinkProposal_async + */ approveDisplayVideo360AdvertiserLinkProposal( - request?: protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalResponse, - protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalResponse, + ( + | protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest + | undefined + ), + {} | undefined, + ] + >; approveDisplayVideo360AdvertiserLinkProposal( - request: protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalResponse, - protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalResponse, + | protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + >, + ): void; approveDisplayVideo360AdvertiserLinkProposal( - request: protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalResponse, - protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalResponse, + | protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + >, + ): void; approveDisplayVideo360AdvertiserLinkProposal( - request?: protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalResponse, - protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalResponse, - protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalResponse, - protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalResponse, + | protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalResponse, + ( + | protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest + | 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('approveDisplayVideo360AdvertiserLinkProposal request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalResponse, - protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>|undefined = callback + this._log.info( + 'approveDisplayVideo360AdvertiserLinkProposal request %j', + request, + ); + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalResponse, + | protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('approveDisplayVideo360AdvertiserLinkProposal response %j', response); + this._log.info( + 'approveDisplayVideo360AdvertiserLinkProposal response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.approveDisplayVideo360AdvertiserLinkProposal(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalResponse, - protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest|undefined, - {}|undefined - ]) => { - this._log.info('approveDisplayVideo360AdvertiserLinkProposal response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .approveDisplayVideo360AdvertiserLinkProposal( + request, + options, + wrappedCallback, + ) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalResponse, + ( + | protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'approveDisplayVideo360AdvertiserLinkProposal response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Cancels a DisplayVideo360AdvertiserLinkProposal. - * Cancelling can mean either: - * - Declining a proposal initiated from Display & Video 360 - * - Withdrawing a proposal initiated from Google Analytics - * After being cancelled, a proposal will eventually be deleted automatically. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the DisplayVideo360AdvertiserLinkProposal to cancel. - * Example format: properties/1234/displayVideo360AdvertiserLinkProposals/5678 - * @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.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal|DisplayVideo360AdvertiserLinkProposal}. - * 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/v1alpha/analytics_admin_service.cancel_display_video360_advertiser_link_proposal.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CancelDisplayVideo360AdvertiserLinkProposal_async - */ + /** + * Cancels a DisplayVideo360AdvertiserLinkProposal. + * Cancelling can mean either: + * - Declining a proposal initiated from Display & Video 360 + * - Withdrawing a proposal initiated from Google Analytics + * After being cancelled, a proposal will eventually be deleted automatically. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the DisplayVideo360AdvertiserLinkProposal to cancel. + * Example format: properties/1234/displayVideo360AdvertiserLinkProposals/5678 + * @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.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal|DisplayVideo360AdvertiserLinkProposal}. + * 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/v1alpha/analytics_admin_service.cancel_display_video360_advertiser_link_proposal.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CancelDisplayVideo360AdvertiserLinkProposal_async + */ cancelDisplayVideo360AdvertiserLinkProposal( - request?: protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, + ( + | protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest + | undefined + ), + {} | undefined, + ] + >; cancelDisplayVideo360AdvertiserLinkProposal( - request: protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, + | protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + >, + ): void; cancelDisplayVideo360AdvertiserLinkProposal( - request: protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, + | protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + >, + ): void; cancelDisplayVideo360AdvertiserLinkProposal( - request?: protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, + | protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, + ( + | protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest + | 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('cancelDisplayVideo360AdvertiserLinkProposal request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest|null|undefined, - {}|null|undefined>|undefined = callback + this._log.info( + 'cancelDisplayVideo360AdvertiserLinkProposal request %j', + request, + ); + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, + | protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('cancelDisplayVideo360AdvertiserLinkProposal response %j', response); + this._log.info( + 'cancelDisplayVideo360AdvertiserLinkProposal response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.cancelDisplayVideo360AdvertiserLinkProposal(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, - protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest|undefined, - {}|undefined - ]) => { - this._log.info('cancelDisplayVideo360AdvertiserLinkProposal response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .cancelDisplayVideo360AdvertiserLinkProposal( + request, + options, + wrappedCallback, + ) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal, + ( + | protos.google.analytics.admin.v1alpha.ICancelDisplayVideo360AdvertiserLinkProposalRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'cancelDisplayVideo360AdvertiserLinkProposal response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a CustomDimension. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {google.analytics.admin.v1alpha.CustomDimension} request.customDimension - * Required. The CustomDimension 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.analytics.admin.v1alpha.CustomDimension|CustomDimension}. - * 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/v1alpha/analytics_admin_service.create_custom_dimension.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateCustomDimension_async - */ + /** + * Creates a CustomDimension. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {google.analytics.admin.v1alpha.CustomDimension} request.customDimension + * Required. The CustomDimension 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.analytics.admin.v1alpha.CustomDimension|CustomDimension}. + * 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/v1alpha/analytics_admin_service.create_custom_dimension.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateCustomDimension_async + */ createCustomDimension( - request?: protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICustomDimension, + ( + | protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest + | undefined + ), + {} | undefined, + ] + >; createCustomDimension( - request: protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.ICustomDimension, + | protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createCustomDimension( - request: protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.ICustomDimension, + | protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createCustomDimension( - request?: protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.ICustomDimension, + | protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICustomDimension, + ( + | protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest + | 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('createCustomDimension request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.ICustomDimension, + | protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createCustomDimension response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createCustomDimension(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest|undefined, - {}|undefined - ]) => { - this._log.info('createCustomDimension response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createCustomDimension(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.ICustomDimension, + ( + | protos.google.analytics.admin.v1alpha.ICreateCustomDimensionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createCustomDimension response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a CustomDimension on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.CustomDimension} request.customDimension - * The CustomDimension to update - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Omitted fields will not be - * updated. To replace the entire entity, use one path with the string "*" to - * match all fields. - * @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.analytics.admin.v1alpha.CustomDimension|CustomDimension}. - * 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/v1alpha/analytics_admin_service.update_custom_dimension.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateCustomDimension_async - */ + /** + * Updates a CustomDimension on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.CustomDimension} request.customDimension + * The CustomDimension to update + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Omitted fields will not be + * updated. To replace the entire entity, use one path with the string "*" to + * match all fields. + * @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.analytics.admin.v1alpha.CustomDimension|CustomDimension}. + * 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/v1alpha/analytics_admin_service.update_custom_dimension.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateCustomDimension_async + */ updateCustomDimension( - request?: protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICustomDimension, + ( + | protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest + | undefined + ), + {} | undefined, + ] + >; updateCustomDimension( - request: protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.ICustomDimension, + | protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCustomDimension( - request: protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.ICustomDimension, + | protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCustomDimension( - request?: protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.ICustomDimension, + | protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICustomDimension, + ( + | protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest + | 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({ - 'custom_dimension.name': request.customDimension!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'custom_dimension.name': request.customDimension!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateCustomDimension request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.ICustomDimension, + | protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateCustomDimension response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateCustomDimension(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateCustomDimension response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateCustomDimension(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.ICustomDimension, + ( + | protos.google.analytics.admin.v1alpha.IUpdateCustomDimensionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateCustomDimension response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Archives a CustomDimension on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the CustomDimension to archive. - * Example format: properties/1234/customDimensions/5678 - * @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/v1alpha/analytics_admin_service.archive_custom_dimension.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ArchiveCustomDimension_async - */ + /** + * Archives a CustomDimension on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the CustomDimension to archive. + * Example format: properties/1234/customDimensions/5678 + * @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/v1alpha/analytics_admin_service.archive_custom_dimension.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ArchiveCustomDimension_async + */ archiveCustomDimension( - request?: protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest + | undefined + ), + {} | undefined, + ] + >; archiveCustomDimension( - request: protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; archiveCustomDimension( - request: protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; archiveCustomDimension( - request?: protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest + | 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('archiveCustomDimension request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('archiveCustomDimension response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.archiveCustomDimension(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest|undefined, - {}|undefined - ]) => { - this._log.info('archiveCustomDimension response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .archiveCustomDimension(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IArchiveCustomDimensionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('archiveCustomDimension response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for a single CustomDimension. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the CustomDimension to get. - * Example format: properties/1234/customDimensions/5678 - * @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.analytics.admin.v1alpha.CustomDimension|CustomDimension}. - * 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/v1alpha/analytics_admin_service.get_custom_dimension.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetCustomDimension_async - */ + /** + * Lookup for a single CustomDimension. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the CustomDimension to get. + * Example format: properties/1234/customDimensions/5678 + * @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.analytics.admin.v1alpha.CustomDimension|CustomDimension}. + * 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/v1alpha/analytics_admin_service.get_custom_dimension.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetCustomDimension_async + */ getCustomDimension( - request?: protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICustomDimension, + ( + | protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest + | undefined + ), + {} | undefined, + ] + >; getCustomDimension( - request: protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.ICustomDimension, + | protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getCustomDimension( - request: protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.ICustomDimension, + | protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getCustomDimension( - request?: protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.ICustomDimension, + | protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICustomDimension, + ( + | protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest + | 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('getCustomDimension request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.ICustomDimension, + | protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getCustomDimension response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getCustomDimension(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.ICustomDimension, - protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest|undefined, - {}|undefined - ]) => { - this._log.info('getCustomDimension response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getCustomDimension(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.ICustomDimension, + ( + | protos.google.analytics.admin.v1alpha.IGetCustomDimensionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getCustomDimension response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a CustomMetric. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {google.analytics.admin.v1alpha.CustomMetric} request.customMetric - * Required. The CustomMetric 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.analytics.admin.v1alpha.CustomMetric|CustomMetric}. - * 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/v1alpha/analytics_admin_service.create_custom_metric.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateCustomMetric_async - */ + /** + * Creates a CustomMetric. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {google.analytics.admin.v1alpha.CustomMetric} request.customMetric + * Required. The CustomMetric 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.analytics.admin.v1alpha.CustomMetric|CustomMetric}. + * 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/v1alpha/analytics_admin_service.create_custom_metric.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateCustomMetric_async + */ createCustomMetric( - request?: protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICustomMetric, + ( + | protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest + | undefined + ), + {} | undefined, + ] + >; createCustomMetric( - request: protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.ICustomMetric, + | protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createCustomMetric( - request: protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.ICustomMetric, + | protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createCustomMetric( - request?: protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.ICustomMetric, + | protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICustomMetric, + ( + | protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest + | 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('createCustomMetric request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.ICustomMetric, + | protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createCustomMetric response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createCustomMetric(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest|undefined, - {}|undefined - ]) => { - this._log.info('createCustomMetric response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createCustomMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.ICustomMetric, + ( + | protos.google.analytics.admin.v1alpha.ICreateCustomMetricRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createCustomMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a CustomMetric on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.CustomMetric} request.customMetric - * The CustomMetric to update - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Omitted fields will not be - * updated. To replace the entire entity, use one path with the string "*" to - * match all fields. - * @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.analytics.admin.v1alpha.CustomMetric|CustomMetric}. - * 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/v1alpha/analytics_admin_service.update_custom_metric.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateCustomMetric_async - */ + /** + * Updates a CustomMetric on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.CustomMetric} request.customMetric + * The CustomMetric to update + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Omitted fields will not be + * updated. To replace the entire entity, use one path with the string "*" to + * match all fields. + * @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.analytics.admin.v1alpha.CustomMetric|CustomMetric}. + * 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/v1alpha/analytics_admin_service.update_custom_metric.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateCustomMetric_async + */ updateCustomMetric( - request?: protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICustomMetric, + ( + | protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest + | undefined + ), + {} | undefined, + ] + >; updateCustomMetric( - request: protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.ICustomMetric, + | protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCustomMetric( - request: protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.ICustomMetric, + | protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCustomMetric( - request?: protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.ICustomMetric, + | protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICustomMetric, + ( + | protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest + | 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({ - 'custom_metric.name': request.customMetric!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'custom_metric.name': request.customMetric!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateCustomMetric request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.ICustomMetric, + | protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateCustomMetric response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateCustomMetric(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateCustomMetric response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateCustomMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.ICustomMetric, + ( + | protos.google.analytics.admin.v1alpha.IUpdateCustomMetricRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateCustomMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Archives a CustomMetric on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the CustomMetric to archive. - * Example format: properties/1234/customMetrics/5678 - * @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/v1alpha/analytics_admin_service.archive_custom_metric.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ArchiveCustomMetric_async - */ + /** + * Archives a CustomMetric on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the CustomMetric to archive. + * Example format: properties/1234/customMetrics/5678 + * @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/v1alpha/analytics_admin_service.archive_custom_metric.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ArchiveCustomMetric_async + */ archiveCustomMetric( - request?: protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest + | undefined + ), + {} | undefined, + ] + >; archiveCustomMetric( - request: protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; archiveCustomMetric( - request: protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; archiveCustomMetric( - request?: protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest + | 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('archiveCustomMetric request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('archiveCustomMetric response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.archiveCustomMetric(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest|undefined, - {}|undefined - ]) => { - this._log.info('archiveCustomMetric response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .archiveCustomMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IArchiveCustomMetricRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('archiveCustomMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for a single CustomMetric. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the CustomMetric to get. - * Example format: properties/1234/customMetrics/5678 - * @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.analytics.admin.v1alpha.CustomMetric|CustomMetric}. - * 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/v1alpha/analytics_admin_service.get_custom_metric.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetCustomMetric_async - */ + /** + * Lookup for a single CustomMetric. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the CustomMetric to get. + * Example format: properties/1234/customMetrics/5678 + * @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.analytics.admin.v1alpha.CustomMetric|CustomMetric}. + * 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/v1alpha/analytics_admin_service.get_custom_metric.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetCustomMetric_async + */ getCustomMetric( - request?: protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICustomMetric, + protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest | undefined, + {} | undefined, + ] + >; getCustomMetric( - request: protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.ICustomMetric, + | protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getCustomMetric( - request: protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.ICustomMetric, + | protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getCustomMetric( - request?: protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.ICustomMetric, + | protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICustomMetric, + protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest | 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('getCustomMetric request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.ICustomMetric, + | protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getCustomMetric response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getCustomMetric(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.ICustomMetric, - protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest|undefined, - {}|undefined - ]) => { - this._log.info('getCustomMetric response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getCustomMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.ICustomMetric, + ( + | protos.google.analytics.admin.v1alpha.IGetCustomMetricRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getCustomMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns the singleton data retention settings for this property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the settings to lookup. - * Format: - * properties/{property}/dataRetentionSettings - * Example: "properties/1000/dataRetentionSettings" - * @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.analytics.admin.v1alpha.DataRetentionSettings|DataRetentionSettings}. - * 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/v1alpha/analytics_admin_service.get_data_retention_settings.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetDataRetentionSettings_async - */ + /** + * Returns the singleton data retention settings for this property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the settings to lookup. + * Format: + * properties/{property}/dataRetentionSettings + * Example: "properties/1000/dataRetentionSettings" + * @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.analytics.admin.v1alpha.DataRetentionSettings|DataRetentionSettings}. + * 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/v1alpha/analytics_admin_service.get_data_retention_settings.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetDataRetentionSettings_async + */ getDataRetentionSettings( - request?: protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IDataRetentionSettings, - protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDataRetentionSettings, + ( + | protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest + | undefined + ), + {} | undefined, + ] + >; getDataRetentionSettings( - request: protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDataRetentionSettings, - protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDataRetentionSettings, + | protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDataRetentionSettings( - request: protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDataRetentionSettings, - protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDataRetentionSettings, + | protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDataRetentionSettings( - request?: protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IDataRetentionSettings, - protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IDataRetentionSettings, - protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IDataRetentionSettings, - protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IDataRetentionSettings, + | protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDataRetentionSettings, + ( + | protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest + | 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('getDataRetentionSettings request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IDataRetentionSettings, - protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IDataRetentionSettings, + | protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getDataRetentionSettings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getDataRetentionSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IDataRetentionSettings, - protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('getDataRetentionSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getDataRetentionSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IDataRetentionSettings, + ( + | protos.google.analytics.admin.v1alpha.IGetDataRetentionSettingsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getDataRetentionSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the singleton data retention settings for this property. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.DataRetentionSettings} request.dataRetentionSettings - * Required. The settings to update. - * The `name` field is used to identify the settings to be updated. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Field names must be in snake - * case (e.g., "field_to_update"). Omitted fields will not be updated. To - * replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1alpha.DataRetentionSettings|DataRetentionSettings}. - * 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/v1alpha/analytics_admin_service.update_data_retention_settings.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateDataRetentionSettings_async - */ + /** + * Updates the singleton data retention settings for this property. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.DataRetentionSettings} request.dataRetentionSettings + * Required. The settings to update. + * The `name` field is used to identify the settings to be updated. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Field names must be in snake + * case (e.g., "field_to_update"). Omitted fields will not be updated. To + * replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1alpha.DataRetentionSettings|DataRetentionSettings}. + * 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/v1alpha/analytics_admin_service.update_data_retention_settings.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateDataRetentionSettings_async + */ updateDataRetentionSettings( - request?: protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IDataRetentionSettings, - protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDataRetentionSettings, + ( + | protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest + | undefined + ), + {} | undefined, + ] + >; updateDataRetentionSettings( - request: protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDataRetentionSettings, - protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDataRetentionSettings, + | protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDataRetentionSettings( - request: protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDataRetentionSettings, - protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDataRetentionSettings, + | protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDataRetentionSettings( - request?: protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IDataRetentionSettings, - protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IDataRetentionSettings, - protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IDataRetentionSettings, - protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IDataRetentionSettings, + | protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDataRetentionSettings, + ( + | protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest + | 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({ - 'data_retention_settings.name': request.dataRetentionSettings!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'data_retention_settings.name': + request.dataRetentionSettings!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateDataRetentionSettings request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IDataRetentionSettings, - protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IDataRetentionSettings, + | protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateDataRetentionSettings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateDataRetentionSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IDataRetentionSettings, - protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateDataRetentionSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateDataRetentionSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IDataRetentionSettings, + ( + | protos.google.analytics.admin.v1alpha.IUpdateDataRetentionSettingsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateDataRetentionSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a DataStream. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {google.analytics.admin.v1alpha.DataStream} request.dataStream - * Required. The DataStream 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.analytics.admin.v1alpha.DataStream|DataStream}. - * 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/v1alpha/analytics_admin_service.create_data_stream.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateDataStream_async - */ + /** + * Creates a DataStream. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {google.analytics.admin.v1alpha.DataStream} request.dataStream + * Required. The DataStream 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.analytics.admin.v1alpha.DataStream|DataStream}. + * 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/v1alpha/analytics_admin_service.create_data_stream.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateDataStream_async + */ createDataStream( - request?: protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDataStream, + ( + | protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest + | undefined + ), + {} | undefined, + ] + >; createDataStream( - request: protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDataStream, + | protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createDataStream( - request: protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDataStream, + | protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createDataStream( - request?: protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IDataStream, + | protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDataStream, + ( + | protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest + | 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('createDataStream request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IDataStream, + | protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createDataStream response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createDataStream(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest|undefined, - {}|undefined - ]) => { - this._log.info('createDataStream response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createDataStream(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IDataStream, + ( + | protos.google.analytics.admin.v1alpha.ICreateDataStreamRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createDataStream response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a DataStream on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the DataStream to delete. - * Example format: properties/1234/dataStreams/5678 - * @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/v1alpha/analytics_admin_service.delete_data_stream.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteDataStream_async - */ + /** + * Deletes a DataStream on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the DataStream to delete. + * Example format: properties/1234/dataStreams/5678 + * @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/v1alpha/analytics_admin_service.delete_data_stream.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteDataStream_async + */ deleteDataStream( - request?: protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest + | undefined + ), + {} | undefined, + ] + >; deleteDataStream( - request: protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteDataStream( - request: protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteDataStream( - request?: protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest + | 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('deleteDataStream request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteDataStream response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteDataStream(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteDataStream response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteDataStream(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteDataStreamRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteDataStream response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a DataStream on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.DataStream} request.dataStream - * The DataStream to update - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Omitted fields will not be - * updated. To replace the entire entity, use one path with the string "*" to - * match all fields. - * @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.analytics.admin.v1alpha.DataStream|DataStream}. - * 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/v1alpha/analytics_admin_service.update_data_stream.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateDataStream_async - */ + /** + * Updates a DataStream on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.DataStream} request.dataStream + * The DataStream to update + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Omitted fields will not be + * updated. To replace the entire entity, use one path with the string "*" to + * match all fields. + * @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.analytics.admin.v1alpha.DataStream|DataStream}. + * 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/v1alpha/analytics_admin_service.update_data_stream.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateDataStream_async + */ updateDataStream( - request?: protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDataStream, + ( + | protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest + | undefined + ), + {} | undefined, + ] + >; updateDataStream( - request: protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDataStream, + | protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDataStream( - request: protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDataStream, + | protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDataStream( - request?: protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IDataStream, + | protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDataStream, + ( + | protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest + | 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({ - 'data_stream.name': request.dataStream!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'data_stream.name': request.dataStream!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateDataStream request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IDataStream, + | protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateDataStream response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateDataStream(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateDataStream response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateDataStream(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IDataStream, + ( + | protos.google.analytics.admin.v1alpha.IUpdateDataStreamRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateDataStream response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for a single DataStream. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the DataStream to get. - * Example format: properties/1234/dataStreams/5678 - * @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.analytics.admin.v1alpha.DataStream|DataStream}. - * 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/v1alpha/analytics_admin_service.get_data_stream.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetDataStream_async - */ + /** + * Lookup for a single DataStream. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the DataStream to get. + * Example format: properties/1234/dataStreams/5678 + * @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.analytics.admin.v1alpha.DataStream|DataStream}. + * 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/v1alpha/analytics_admin_service.get_data_stream.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetDataStream_async + */ getDataStream( - request?: protos.google.analytics.admin.v1alpha.IGetDataStreamRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.IGetDataStreamRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetDataStreamRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDataStream, + protos.google.analytics.admin.v1alpha.IGetDataStreamRequest | undefined, + {} | undefined, + ] + >; getDataStream( - request: protos.google.analytics.admin.v1alpha.IGetDataStreamRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.IGetDataStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetDataStreamRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDataStream, + | protos.google.analytics.admin.v1alpha.IGetDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDataStream( - request: protos.google.analytics.admin.v1alpha.IGetDataStreamRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.IGetDataStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetDataStreamRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDataStream, + | protos.google.analytics.admin.v1alpha.IGetDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDataStream( - request?: protos.google.analytics.admin.v1alpha.IGetDataStreamRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.IGetDataStreamRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IGetDataStreamRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.IGetDataStreamRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.IGetDataStreamRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IDataStream, + | protos.google.analytics.admin.v1alpha.IGetDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDataStream, + protos.google.analytics.admin.v1alpha.IGetDataStreamRequest | 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('getDataStream request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.IGetDataStreamRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IDataStream, + | protos.google.analytics.admin.v1alpha.IGetDataStreamRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getDataStream response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getDataStream(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IDataStream, - protos.google.analytics.admin.v1alpha.IGetDataStreamRequest|undefined, - {}|undefined - ]) => { - this._log.info('getDataStream response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getDataStream(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IDataStream, + ( + | protos.google.analytics.admin.v1alpha.IGetDataStreamRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getDataStream response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for a single Audience. - * Audiences created before 2020 may not be supported. - * Default audiences will not show filter definitions. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the Audience to get. - * Example format: properties/1234/audiences/5678 - * @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.analytics.admin.v1alpha.Audience|Audience}. - * 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/v1alpha/analytics_admin_service.get_audience.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetAudience_async - */ + /** + * Lookup for a single Audience. + * Audiences created before 2020 may not be supported. + * Default audiences will not show filter definitions. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the Audience to get. + * Example format: properties/1234/audiences/5678 + * @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.analytics.admin.v1alpha.Audience|Audience}. + * 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/v1alpha/analytics_admin_service.get_audience.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetAudience_async + */ getAudience( - request?: protos.google.analytics.admin.v1alpha.IGetAudienceRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.IGetAudienceRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetAudienceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAudience, + protos.google.analytics.admin.v1alpha.IGetAudienceRequest | undefined, + {} | undefined, + ] + >; getAudience( - request: protos.google.analytics.admin.v1alpha.IGetAudienceRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.IGetAudienceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetAudienceRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAudience, + | protos.google.analytics.admin.v1alpha.IGetAudienceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAudience( - request: protos.google.analytics.admin.v1alpha.IGetAudienceRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.IGetAudienceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetAudienceRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAudience, + | protos.google.analytics.admin.v1alpha.IGetAudienceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAudience( - request?: protos.google.analytics.admin.v1alpha.IGetAudienceRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.IGetAudienceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IGetAudienceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.IGetAudienceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.IGetAudienceRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetAudienceRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IAudience, + | protos.google.analytics.admin.v1alpha.IGetAudienceRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAudience, + protos.google.analytics.admin.v1alpha.IGetAudienceRequest | 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('getAudience request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.IGetAudienceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IAudience, + | protos.google.analytics.admin.v1alpha.IGetAudienceRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getAudience response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getAudience(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.IGetAudienceRequest|undefined, - {}|undefined - ]) => { - this._log.info('getAudience response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getAudience(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IAudience, + protos.google.analytics.admin.v1alpha.IGetAudienceRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getAudience response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates an Audience. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {google.analytics.admin.v1alpha.Audience} request.audience - * Required. The audience 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.analytics.admin.v1alpha.Audience|Audience}. - * 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/v1alpha/analytics_admin_service.create_audience.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateAudience_async - */ + /** + * Creates an Audience. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {google.analytics.admin.v1alpha.Audience} request.audience + * Required. The audience 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.analytics.admin.v1alpha.Audience|Audience}. + * 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/v1alpha/analytics_admin_service.create_audience.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateAudience_async + */ createAudience( - request?: protos.google.analytics.admin.v1alpha.ICreateAudienceRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.ICreateAudienceRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateAudienceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAudience, + protos.google.analytics.admin.v1alpha.ICreateAudienceRequest | undefined, + {} | undefined, + ] + >; createAudience( - request: protos.google.analytics.admin.v1alpha.ICreateAudienceRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.ICreateAudienceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateAudienceRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAudience, + | protos.google.analytics.admin.v1alpha.ICreateAudienceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createAudience( - request: protos.google.analytics.admin.v1alpha.ICreateAudienceRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.ICreateAudienceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateAudienceRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAudience, + | protos.google.analytics.admin.v1alpha.ICreateAudienceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createAudience( - request?: protos.google.analytics.admin.v1alpha.ICreateAudienceRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.ICreateAudienceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateAudienceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.ICreateAudienceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.ICreateAudienceRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateAudienceRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IAudience, + | protos.google.analytics.admin.v1alpha.ICreateAudienceRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAudience, + protos.google.analytics.admin.v1alpha.ICreateAudienceRequest | 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('createAudience request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.ICreateAudienceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IAudience, + | protos.google.analytics.admin.v1alpha.ICreateAudienceRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createAudience response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createAudience(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.ICreateAudienceRequest|undefined, - {}|undefined - ]) => { - this._log.info('createAudience response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createAudience(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IAudience, + ( + | protos.google.analytics.admin.v1alpha.ICreateAudienceRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createAudience response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates an Audience on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.Audience} request.audience - * Required. The audience to update. - * The audience's `name` field is used to identify the audience to be updated. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Field names must be in snake - * case (e.g., "field_to_update"). Omitted fields will not be updated. To - * replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1alpha.Audience|Audience}. - * 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/v1alpha/analytics_admin_service.update_audience.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateAudience_async - */ + /** + * Updates an Audience on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.Audience} request.audience + * Required. The audience to update. + * The audience's `name` field is used to identify the audience to be updated. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Field names must be in snake + * case (e.g., "field_to_update"). Omitted fields will not be updated. To + * replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1alpha.Audience|Audience}. + * 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/v1alpha/analytics_admin_service.update_audience.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateAudience_async + */ updateAudience( - request?: protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAudience, + protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest | undefined, + {} | undefined, + ] + >; updateAudience( - request: protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAudience, + | protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateAudience( - request: protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAudience, + | protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateAudience( - request?: protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IAudience, + | protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAudience, + protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest | 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({ - 'audience.name': request.audience!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'audience.name': request.audience!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateAudience request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IAudience, + | protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateAudience response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateAudience(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IAudience, - protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateAudience response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateAudience(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IAudience, + ( + | protos.google.analytics.admin.v1alpha.IUpdateAudienceRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateAudience response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Archives an Audience on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Example format: properties/1234/audiences/5678 - * @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/v1alpha/analytics_admin_service.archive_audience.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ArchiveAudience_async - */ + /** + * Archives an Audience on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Example format: properties/1234/audiences/5678 + * @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/v1alpha/analytics_admin_service.archive_audience.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ArchiveAudience_async + */ archiveAudience( - request?: protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest | undefined, + {} | undefined, + ] + >; archiveAudience( - request: protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; archiveAudience( - request: protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; archiveAudience( - request?: protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest | 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('archiveAudience request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('archiveAudience response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.archiveAudience(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest|undefined, - {}|undefined - ]) => { - this._log.info('archiveAudience response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .archiveAudience(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IArchiveAudienceRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('archiveAudience response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Look up a single SearchAds360Link - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the SearchAds360Link to get. - * Example format: properties/1234/SearchAds360Link/5678 - * @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.analytics.admin.v1alpha.SearchAds360Link|SearchAds360Link}. - * 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/v1alpha/analytics_admin_service.get_search_ads360_link.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetSearchAds360Link_async - */ + /** + * Look up a single SearchAds360Link + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the SearchAds360Link to get. + * Example format: properties/1234/SearchAds360Link/5678 + * @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.analytics.admin.v1alpha.SearchAds360Link|SearchAds360Link}. + * 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/v1alpha/analytics_admin_service.get_search_ads360_link.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetSearchAds360Link_async + */ getSearchAds360Link( - request?: protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISearchAds360Link, + ( + | protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest + | undefined + ), + {} | undefined, + ] + >; getSearchAds360Link( - request: protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISearchAds360Link, + | protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getSearchAds360Link( - request: protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISearchAds360Link, + | protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getSearchAds360Link( - request?: protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.ISearchAds360Link, + | protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISearchAds360Link, + ( + | protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest + | 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('getSearchAds360Link request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.ISearchAds360Link, + | protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getSearchAds360Link response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getSearchAds360Link(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('getSearchAds360Link response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getSearchAds360Link(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.ISearchAds360Link, + ( + | protos.google.analytics.admin.v1alpha.IGetSearchAds360LinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getSearchAds360Link response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a SearchAds360Link. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {google.analytics.admin.v1alpha.SearchAds360Link} request.searchAds_360Link - * Required. The SearchAds360Link 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.analytics.admin.v1alpha.SearchAds360Link|SearchAds360Link}. - * 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/v1alpha/analytics_admin_service.create_search_ads360_link.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateSearchAds360Link_async - */ + /** + * Creates a SearchAds360Link. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {google.analytics.admin.v1alpha.SearchAds360Link} request.searchAds_360Link + * Required. The SearchAds360Link 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.analytics.admin.v1alpha.SearchAds360Link|SearchAds360Link}. + * 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/v1alpha/analytics_admin_service.create_search_ads360_link.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateSearchAds360Link_async + */ createSearchAds360Link( - request?: protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISearchAds360Link, + ( + | protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest + | undefined + ), + {} | undefined, + ] + >; createSearchAds360Link( - request: protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISearchAds360Link, + | protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createSearchAds360Link( - request: protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISearchAds360Link, + | protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createSearchAds360Link( - request?: protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.ISearchAds360Link, + | protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISearchAds360Link, + ( + | protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest + | 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('createSearchAds360Link request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.ISearchAds360Link, + | protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createSearchAds360Link response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createSearchAds360Link(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('createSearchAds360Link response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createSearchAds360Link(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.ISearchAds360Link, + ( + | protos.google.analytics.admin.v1alpha.ICreateSearchAds360LinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createSearchAds360Link response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a SearchAds360Link on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the SearchAds360Link to delete. - * Example format: properties/1234/SearchAds360Links/5678 - * @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/v1alpha/analytics_admin_service.delete_search_ads360_link.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteSearchAds360Link_async - */ + /** + * Deletes a SearchAds360Link on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the SearchAds360Link to delete. + * Example format: properties/1234/SearchAds360Links/5678 + * @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/v1alpha/analytics_admin_service.delete_search_ads360_link.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteSearchAds360Link_async + */ deleteSearchAds360Link( - request?: protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest + | undefined + ), + {} | undefined, + ] + >; deleteSearchAds360Link( - request: protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteSearchAds360Link( - request: protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteSearchAds360Link( - request?: protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest + | 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('deleteSearchAds360Link request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteSearchAds360Link response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteSearchAds360Link(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteSearchAds360Link response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteSearchAds360Link(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteSearchAds360LinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteSearchAds360Link response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a SearchAds360Link on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.SearchAds360Link} request.searchAds_360Link - * The SearchAds360Link to update - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Omitted fields will not be - * updated. To replace the entire entity, use one path with the string "*" to - * match all fields. - * @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.analytics.admin.v1alpha.SearchAds360Link|SearchAds360Link}. - * 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/v1alpha/analytics_admin_service.update_search_ads360_link.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateSearchAds360Link_async - */ + /** + * Updates a SearchAds360Link on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.SearchAds360Link} request.searchAds_360Link + * The SearchAds360Link to update + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Omitted fields will not be + * updated. To replace the entire entity, use one path with the string "*" to + * match all fields. + * @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.analytics.admin.v1alpha.SearchAds360Link|SearchAds360Link}. + * 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/v1alpha/analytics_admin_service.update_search_ads360_link.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateSearchAds360Link_async + */ updateSearchAds360Link( - request?: protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISearchAds360Link, + ( + | protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest + | undefined + ), + {} | undefined, + ] + >; updateSearchAds360Link( - request: protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISearchAds360Link, + | protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateSearchAds360Link( - request: protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISearchAds360Link, + | protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateSearchAds360Link( - request?: protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.ISearchAds360Link, + | protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISearchAds360Link, + ( + | protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest + | 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({ - 'search_ads_360_link.name': request.searchAds_360Link!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'search_ads_360_link.name': request.searchAds_360Link!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateSearchAds360Link request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.ISearchAds360Link, + | protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateSearchAds360Link response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateSearchAds360Link(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.ISearchAds360Link, - protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateSearchAds360Link response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateSearchAds360Link(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.ISearchAds360Link, + ( + | protos.google.analytics.admin.v1alpha.IUpdateSearchAds360LinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateSearchAds360Link response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for a AttributionSettings singleton. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the attribution settings to retrieve. - * Format: properties/{property}/attributionSettings - * @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.analytics.admin.v1alpha.AttributionSettings|AttributionSettings}. - * 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/v1alpha/analytics_admin_service.get_attribution_settings.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetAttributionSettings_async - */ + /** + * Lookup for a AttributionSettings singleton. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the attribution settings to retrieve. + * Format: properties/{property}/attributionSettings + * @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.analytics.admin.v1alpha.AttributionSettings|AttributionSettings}. + * 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/v1alpha/analytics_admin_service.get_attribution_settings.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetAttributionSettings_async + */ getAttributionSettings( - request?: protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IAttributionSettings, - protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAttributionSettings, + ( + | protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest + | undefined + ), + {} | undefined, + ] + >; getAttributionSettings( - request: protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAttributionSettings, - protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAttributionSettings, + | protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAttributionSettings( - request: protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAttributionSettings, - protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAttributionSettings, + | protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAttributionSettings( - request?: protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IAttributionSettings, - protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IAttributionSettings, - protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IAttributionSettings, - protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IAttributionSettings, + | protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAttributionSettings, + ( + | protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest + | 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('getAttributionSettings request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IAttributionSettings, - protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IAttributionSettings, + | protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getAttributionSettings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getAttributionSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IAttributionSettings, - protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('getAttributionSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getAttributionSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IAttributionSettings, + ( + | protos.google.analytics.admin.v1alpha.IGetAttributionSettingsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getAttributionSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates attribution settings on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.AttributionSettings} request.attributionSettings - * Required. The attribution settings to update. - * The `name` field is used to identify the settings to be updated. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Field names must be in snake - * case (e.g., "field_to_update"). Omitted fields will not be updated. To - * replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1alpha.AttributionSettings|AttributionSettings}. - * 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/v1alpha/analytics_admin_service.update_attribution_settings.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateAttributionSettings_async - */ + /** + * Updates attribution settings on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.AttributionSettings} request.attributionSettings + * Required. The attribution settings to update. + * The `name` field is used to identify the settings to be updated. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Field names must be in snake + * case (e.g., "field_to_update"). Omitted fields will not be updated. To + * replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1alpha.AttributionSettings|AttributionSettings}. + * 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/v1alpha/analytics_admin_service.update_attribution_settings.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateAttributionSettings_async + */ updateAttributionSettings( - request?: protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IAttributionSettings, - protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAttributionSettings, + ( + | protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest + | undefined + ), + {} | undefined, + ] + >; updateAttributionSettings( - request: protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAttributionSettings, - protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAttributionSettings, + | protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateAttributionSettings( - request: protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAttributionSettings, - protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAttributionSettings, + | protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateAttributionSettings( - request?: protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IAttributionSettings, - protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IAttributionSettings, - protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IAttributionSettings, - protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IAttributionSettings, + | protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAttributionSettings, + ( + | protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest + | 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({ - 'attribution_settings.name': request.attributionSettings!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'attribution_settings.name': request.attributionSettings!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateAttributionSettings request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IAttributionSettings, - protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IAttributionSettings, + | protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateAttributionSettings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateAttributionSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IAttributionSettings, - protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateAttributionSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateAttributionSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IAttributionSettings, + ( + | protos.google.analytics.admin.v1alpha.IUpdateAttributionSettingsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateAttributionSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns a customized report of data access records. The report provides - * records of each time a user reads Google Analytics reporting data. Access - * records are retained for up to 2 years. - * - * Data Access Reports can be requested for a property. Reports may be - * requested for any property, but dimensions that aren't related to quota can - * only be requested on Google Analytics 360 properties. This method is only - * available to Administrators. - * - * These data access records include GA UI Reporting, GA UI Explorations, - * GA Data API, and other products like Firebase & Admob that can retrieve - * data from Google Analytics through a linkage. These records don't include - * property configuration changes like adding a stream or changing a - * property's time zone. For configuration change history, see - * [searchChangeHistoryEvents](https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts/searchChangeHistoryEvents). - * - * To give your feedback on this API, complete the [Google Analytics Access - * Reports - * feedback](https://docs.google.com/forms/d/e/1FAIpQLSdmEBUrMzAEdiEKk5TV5dEHvDUZDRlgWYdQdAeSdtR4hVjEhw/viewform) - * form. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.entity - * The Data Access Report supports requesting at the property level or account - * level. If requested at the account level, Data Access Reports include all - * access for all properties under that account. - * - * To request at the property level, entity should be for example - * 'properties/123' if "123" is your Google Analytics property ID. To request - * at the account level, entity should be for example 'accounts/1234' if - * "1234" is your Google Analytics Account ID. - * @param {number[]} request.dimensions - * The dimensions requested and displayed in the response. Requests are - * allowed up to 9 dimensions. - * @param {number[]} request.metrics - * The metrics requested and displayed in the response. Requests are allowed - * up to 10 metrics. - * @param {number[]} request.dateRanges - * Date ranges of access records to read. If multiple date ranges are - * requested, each response row will contain a zero based date range index. If - * two date ranges overlap, the access records for the overlapping days is - * included in the response rows for both date ranges. Requests are allowed up - * to 2 date ranges. - * @param {google.analytics.admin.v1alpha.AccessFilterExpression} request.dimensionFilter - * Dimension filters let you restrict report response to specific - * dimension values which match the filter. For example, filtering on access - * records of a single user. To learn more, see [Fundamentals of Dimension - * Filters](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#dimension_filters) - * for examples. Metrics cannot be used in this filter. - * @param {google.analytics.admin.v1alpha.AccessFilterExpression} request.metricFilter - * Metric filters allow you to restrict report response to specific metric - * values which match the filter. Metric filters are applied after aggregating - * the report's rows, similar to SQL having-clause. Dimensions cannot be used - * in this filter. - * @param {number} request.offset - * The row count of the start row. The first row is counted as row 0. If - * offset is unspecified, it is treated as 0. If offset is zero, then this - * method will return the first page of results with `limit` entries. - * - * To learn more about this pagination parameter, see - * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). - * @param {number} request.limit - * The number of rows to return. If unspecified, 10,000 rows are returned. The - * API returns a maximum of 100,000 rows per request, no matter how many you - * ask for. `limit` must be positive. - * - * The API may return fewer rows than the requested `limit`, if there aren't - * as many remaining rows as the `limit`. For instance, there are fewer than - * 300 possible values for the dimension `country`, so when reporting on only - * `country`, you can't get more than 300 rows, even if you set `limit` to a - * higher value. - * - * To learn more about this pagination parameter, see - * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). - * @param {string} request.timeZone - * This request's time zone if specified. If unspecified, the property's time - * zone is used. The request's time zone is used to interpret the start & end - * dates of the report. - * - * Formatted as strings from the IANA Time Zone database - * (https://www.iana.org/time-zones); for example "America/New_York" or - * "Asia/Tokyo". - * @param {number[]} request.orderBys - * Specifies how rows are ordered in the response. - * @param {boolean} request.returnEntityQuota - * Toggles whether to return the current state of this Analytics Property's - * quota. Quota is returned in [AccessQuota](#AccessQuota). For account-level - * requests, this field must be false. - * @param {boolean} [request.includeAllUsers] - * Optional. Determines whether to include users who have never made an API - * call in the response. If true, all users with access to the specified - * property or account are included in the response, regardless of whether - * they have made an API call or not. If false, only the users who have made - * an API call will be included. - * @param {boolean} [request.expandGroups] - * Optional. Decides whether to return the users within user groups. This - * field works only when include_all_users is set to true. If true, it will - * return all users with access to the specified property or account. - * If false, only the users with direct access 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 {@link protos.google.analytics.admin.v1alpha.RunAccessReportResponse|RunAccessReportResponse}. - * 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/v1alpha/analytics_admin_service.run_access_report.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_RunAccessReport_async - */ + /** + * Returns a customized report of data access records. The report provides + * records of each time a user reads Google Analytics reporting data. Access + * records are retained for up to 2 years. + * + * Data Access Reports can be requested for a property. Reports may be + * requested for any property, but dimensions that aren't related to quota can + * only be requested on Google Analytics 360 properties. This method is only + * available to Administrators. + * + * These data access records include GA UI Reporting, GA UI Explorations, + * GA Data API, and other products like Firebase & Admob that can retrieve + * data from Google Analytics through a linkage. These records don't include + * property configuration changes like adding a stream or changing a + * property's time zone. For configuration change history, see + * [searchChangeHistoryEvents](https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts/searchChangeHistoryEvents). + * + * To give your feedback on this API, complete the [Google Analytics Access + * Reports + * feedback](https://docs.google.com/forms/d/e/1FAIpQLSdmEBUrMzAEdiEKk5TV5dEHvDUZDRlgWYdQdAeSdtR4hVjEhw/viewform) + * form. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.entity + * The Data Access Report supports requesting at the property level or account + * level. If requested at the account level, Data Access Reports include all + * access for all properties under that account. + * + * To request at the property level, entity should be for example + * 'properties/123' if "123" is your Google Analytics property ID. To request + * at the account level, entity should be for example 'accounts/1234' if + * "1234" is your Google Analytics Account ID. + * @param {number[]} request.dimensions + * The dimensions requested and displayed in the response. Requests are + * allowed up to 9 dimensions. + * @param {number[]} request.metrics + * The metrics requested and displayed in the response. Requests are allowed + * up to 10 metrics. + * @param {number[]} request.dateRanges + * Date ranges of access records to read. If multiple date ranges are + * requested, each response row will contain a zero based date range index. If + * two date ranges overlap, the access records for the overlapping days is + * included in the response rows for both date ranges. Requests are allowed up + * to 2 date ranges. + * @param {google.analytics.admin.v1alpha.AccessFilterExpression} request.dimensionFilter + * Dimension filters let you restrict report response to specific + * dimension values which match the filter. For example, filtering on access + * records of a single user. To learn more, see [Fundamentals of Dimension + * Filters](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#dimension_filters) + * for examples. Metrics cannot be used in this filter. + * @param {google.analytics.admin.v1alpha.AccessFilterExpression} request.metricFilter + * Metric filters allow you to restrict report response to specific metric + * values which match the filter. Metric filters are applied after aggregating + * the report's rows, similar to SQL having-clause. Dimensions cannot be used + * in this filter. + * @param {number} request.offset + * The row count of the start row. The first row is counted as row 0. If + * offset is unspecified, it is treated as 0. If offset is zero, then this + * method will return the first page of results with `limit` entries. + * + * To learn more about this pagination parameter, see + * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). + * @param {number} request.limit + * The number of rows to return. If unspecified, 10,000 rows are returned. The + * API returns a maximum of 100,000 rows per request, no matter how many you + * ask for. `limit` must be positive. + * + * The API may return fewer rows than the requested `limit`, if there aren't + * as many remaining rows as the `limit`. For instance, there are fewer than + * 300 possible values for the dimension `country`, so when reporting on only + * `country`, you can't get more than 300 rows, even if you set `limit` to a + * higher value. + * + * To learn more about this pagination parameter, see + * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). + * @param {string} request.timeZone + * This request's time zone if specified. If unspecified, the property's time + * zone is used. The request's time zone is used to interpret the start & end + * dates of the report. + * + * Formatted as strings from the IANA Time Zone database + * (https://www.iana.org/time-zones); for example "America/New_York" or + * "Asia/Tokyo". + * @param {number[]} request.orderBys + * Specifies how rows are ordered in the response. + * @param {boolean} request.returnEntityQuota + * Toggles whether to return the current state of this Analytics Property's + * quota. Quota is returned in [AccessQuota](#AccessQuota). For account-level + * requests, this field must be false. + * @param {boolean} [request.includeAllUsers] + * Optional. Determines whether to include users who have never made an API + * call in the response. If true, all users with access to the specified + * property or account are included in the response, regardless of whether + * they have made an API call or not. If false, only the users who have made + * an API call will be included. + * @param {boolean} [request.expandGroups] + * Optional. Decides whether to return the users within user groups. This + * field works only when include_all_users is set to true. If true, it will + * return all users with access to the specified property or account. + * If false, only the users with direct access 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 {@link protos.google.analytics.admin.v1alpha.RunAccessReportResponse|RunAccessReportResponse}. + * 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/v1alpha/analytics_admin_service.run_access_report.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_RunAccessReport_async + */ runAccessReport( - request?: protos.google.analytics.admin.v1alpha.IRunAccessReportRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IRunAccessReportResponse, - protos.google.analytics.admin.v1alpha.IRunAccessReportRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IRunAccessReportRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IRunAccessReportResponse, + protos.google.analytics.admin.v1alpha.IRunAccessReportRequest | undefined, + {} | undefined, + ] + >; runAccessReport( - request: protos.google.analytics.admin.v1alpha.IRunAccessReportRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IRunAccessReportResponse, - protos.google.analytics.admin.v1alpha.IRunAccessReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IRunAccessReportRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IRunAccessReportResponse, + | protos.google.analytics.admin.v1alpha.IRunAccessReportRequest + | null + | undefined, + {} | null | undefined + >, + ): void; runAccessReport( - request: protos.google.analytics.admin.v1alpha.IRunAccessReportRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IRunAccessReportResponse, - protos.google.analytics.admin.v1alpha.IRunAccessReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IRunAccessReportRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IRunAccessReportResponse, + | protos.google.analytics.admin.v1alpha.IRunAccessReportRequest + | null + | undefined, + {} | null | undefined + >, + ): void; runAccessReport( - request?: protos.google.analytics.admin.v1alpha.IRunAccessReportRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IRunAccessReportResponse, - protos.google.analytics.admin.v1alpha.IRunAccessReportRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IRunAccessReportRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IRunAccessReportResponse, - protos.google.analytics.admin.v1alpha.IRunAccessReportRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IRunAccessReportResponse, - protos.google.analytics.admin.v1alpha.IRunAccessReportRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IRunAccessReportRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IRunAccessReportResponse, + | protos.google.analytics.admin.v1alpha.IRunAccessReportRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IRunAccessReportResponse, + protos.google.analytics.admin.v1alpha.IRunAccessReportRequest | 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({ - 'entity': request.entity ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + entity: request.entity ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('runAccessReport request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IRunAccessReportResponse, - protos.google.analytics.admin.v1alpha.IRunAccessReportRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IRunAccessReportResponse, + | protos.google.analytics.admin.v1alpha.IRunAccessReportRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('runAccessReport response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.runAccessReport(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IRunAccessReportResponse, - protos.google.analytics.admin.v1alpha.IRunAccessReportRequest|undefined, - {}|undefined - ]) => { - this._log.info('runAccessReport response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .runAccessReport(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IRunAccessReportResponse, + ( + | protos.google.analytics.admin.v1alpha.IRunAccessReportRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('runAccessReport response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates an access binding on an account or property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Formats: - * - accounts/{account} - * - properties/{property} - * @param {google.analytics.admin.v1alpha.AccessBinding} request.accessBinding - * Required. The access binding 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.analytics.admin.v1alpha.AccessBinding|AccessBinding}. - * 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/v1alpha/analytics_admin_service.create_access_binding.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateAccessBinding_async - */ + /** + * Creates an access binding on an account or property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Formats: + * - accounts/{account} + * - properties/{property} + * @param {google.analytics.admin.v1alpha.AccessBinding} request.accessBinding + * Required. The access binding 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.analytics.admin.v1alpha.AccessBinding|AccessBinding}. + * 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/v1alpha/analytics_admin_service.create_access_binding.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateAccessBinding_async + */ createAccessBinding( - request?: protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAccessBinding, + ( + | protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest + | undefined + ), + {} | undefined, + ] + >; createAccessBinding( - request: protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAccessBinding, + | protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createAccessBinding( - request: protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAccessBinding, + | protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createAccessBinding( - request?: protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IAccessBinding, + | protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAccessBinding, + ( + | protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest + | 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('createAccessBinding request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IAccessBinding, + | protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createAccessBinding response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createAccessBinding(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest|undefined, - {}|undefined - ]) => { - this._log.info('createAccessBinding response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createAccessBinding(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IAccessBinding, + ( + | protos.google.analytics.admin.v1alpha.ICreateAccessBindingRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createAccessBinding response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets information about an access binding. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the access binding to retrieve. - * Formats: - * - accounts/{account}/accessBindings/{accessBinding} - * - properties/{property}/accessBindings/{accessBinding} - * @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.analytics.admin.v1alpha.AccessBinding|AccessBinding}. - * 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/v1alpha/analytics_admin_service.get_access_binding.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetAccessBinding_async - */ + /** + * Gets information about an access binding. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the access binding to retrieve. + * Formats: + * - accounts/{account}/accessBindings/{accessBinding} + * - properties/{property}/accessBindings/{accessBinding} + * @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.analytics.admin.v1alpha.AccessBinding|AccessBinding}. + * 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/v1alpha/analytics_admin_service.get_access_binding.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetAccessBinding_async + */ getAccessBinding( - request?: protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAccessBinding, + ( + | protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest + | undefined + ), + {} | undefined, + ] + >; getAccessBinding( - request: protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAccessBinding, + | protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAccessBinding( - request: protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAccessBinding, + | protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAccessBinding( - request?: protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IAccessBinding, + | protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAccessBinding, + ( + | protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest + | 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('getAccessBinding request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IAccessBinding, + | protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getAccessBinding response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getAccessBinding(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest|undefined, - {}|undefined - ]) => { - this._log.info('getAccessBinding response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getAccessBinding(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IAccessBinding, + ( + | protos.google.analytics.admin.v1alpha.IGetAccessBindingRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getAccessBinding response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates an access binding on an account or property. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.AccessBinding} request.accessBinding - * Required. The access binding to update. - * @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.analytics.admin.v1alpha.AccessBinding|AccessBinding}. - * 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/v1alpha/analytics_admin_service.update_access_binding.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateAccessBinding_async - */ + /** + * Updates an access binding on an account or property. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.AccessBinding} request.accessBinding + * Required. The access binding to update. + * @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.analytics.admin.v1alpha.AccessBinding|AccessBinding}. + * 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/v1alpha/analytics_admin_service.update_access_binding.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateAccessBinding_async + */ updateAccessBinding( - request?: protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAccessBinding, + ( + | protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest + | undefined + ), + {} | undefined, + ] + >; updateAccessBinding( - request: protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAccessBinding, + | protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateAccessBinding( - request: protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAccessBinding, + | protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateAccessBinding( - request?: protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IAccessBinding, + | protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAccessBinding, + ( + | protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest + | 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({ - 'access_binding.name': request.accessBinding!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'access_binding.name': request.accessBinding!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateAccessBinding request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IAccessBinding, + | protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateAccessBinding response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateAccessBinding(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IAccessBinding, - protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateAccessBinding response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateAccessBinding(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IAccessBinding, + ( + | protos.google.analytics.admin.v1alpha.IUpdateAccessBindingRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateAccessBinding response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes an access binding on an account or property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Formats: - * - accounts/{account}/accessBindings/{accessBinding} - * - properties/{property}/accessBindings/{accessBinding} - * @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/v1alpha/analytics_admin_service.delete_access_binding.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteAccessBinding_async - */ + /** + * Deletes an access binding on an account or property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Formats: + * - accounts/{account}/accessBindings/{accessBinding} + * - properties/{property}/accessBindings/{accessBinding} + * @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/v1alpha/analytics_admin_service.delete_access_binding.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteAccessBinding_async + */ deleteAccessBinding( - request?: protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest + | undefined + ), + {} | undefined, + ] + >; deleteAccessBinding( - request: protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteAccessBinding( - request: protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteAccessBinding( - request?: protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest + | 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('deleteAccessBinding request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteAccessBinding response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteAccessBinding(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteAccessBinding response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteAccessBinding(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteAccessBindingRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteAccessBinding response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates information about multiple access bindings to an account or - * property. - * - * This method is transactional. If any AccessBinding cannot be created, none - * of the AccessBindings will be created. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The account or property that owns the access bindings. The parent - * field in the CreateAccessBindingRequest messages must either be empty or - * match this field. Formats: - * - accounts/{account} - * - properties/{property} - * @param {number[]} request.requests - * Required. The requests specifying the access bindings to create. - * A maximum of 1000 access bindings can be created in a batch. - * @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.analytics.admin.v1alpha.BatchCreateAccessBindingsResponse|BatchCreateAccessBindingsResponse}. - * 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/v1alpha/analytics_admin_service.batch_create_access_bindings.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_BatchCreateAccessBindings_async - */ + /** + * Creates information about multiple access bindings to an account or + * property. + * + * This method is transactional. If any AccessBinding cannot be created, none + * of the AccessBindings will be created. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account or property that owns the access bindings. The parent + * field in the CreateAccessBindingRequest messages must either be empty or + * match this field. Formats: + * - accounts/{account} + * - properties/{property} + * @param {number[]} request.requests + * Required. The requests specifying the access bindings to create. + * A maximum of 1000 access bindings can be created in a batch. + * @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.analytics.admin.v1alpha.BatchCreateAccessBindingsResponse|BatchCreateAccessBindingsResponse}. + * 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/v1alpha/analytics_admin_service.batch_create_access_bindings.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_BatchCreateAccessBindings_async + */ batchCreateAccessBindings( - request?: protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsResponse, + ( + | protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest + | undefined + ), + {} | undefined, + ] + >; batchCreateAccessBindings( - request: protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsResponse, + | protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchCreateAccessBindings( - request: protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsResponse, + | protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchCreateAccessBindings( - request?: protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsResponse, + | protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsResponse, + ( + | protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest + | 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('batchCreateAccessBindings request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsResponse, + | protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchCreateAccessBindings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.batchCreateAccessBindings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('batchCreateAccessBindings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchCreateAccessBindings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsResponse, + ( + | protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchCreateAccessBindings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets information about multiple access bindings to an account or property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The account or property that owns the access bindings. The parent - * of all provided values for the 'names' field must match this field. - * Formats: - * - accounts/{account} - * - properties/{property} - * @param {string[]} request.names - * Required. The names of the access bindings to retrieve. - * A maximum of 1000 access bindings can be retrieved in a batch. - * Formats: - * - accounts/{account}/accessBindings/{accessBinding} - * - properties/{property}/accessBindings/{accessBinding} - * @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.analytics.admin.v1alpha.BatchGetAccessBindingsResponse|BatchGetAccessBindingsResponse}. - * 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/v1alpha/analytics_admin_service.batch_get_access_bindings.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_BatchGetAccessBindings_async - */ + /** + * Gets information about multiple access bindings to an account or property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account or property that owns the access bindings. The parent + * of all provided values for the 'names' field must match this field. + * Formats: + * - accounts/{account} + * - properties/{property} + * @param {string[]} request.names + * Required. The names of the access bindings to retrieve. + * A maximum of 1000 access bindings can be retrieved in a batch. + * Formats: + * - accounts/{account}/accessBindings/{accessBinding} + * - properties/{property}/accessBindings/{accessBinding} + * @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.analytics.admin.v1alpha.BatchGetAccessBindingsResponse|BatchGetAccessBindingsResponse}. + * 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/v1alpha/analytics_admin_service.batch_get_access_bindings.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_BatchGetAccessBindings_async + */ batchGetAccessBindings( - request?: protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsResponse, + ( + | protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest + | undefined + ), + {} | undefined, + ] + >; batchGetAccessBindings( - request: protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsResponse, + | protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchGetAccessBindings( - request: protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsResponse, + | protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchGetAccessBindings( - request?: protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsResponse, + | protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsResponse, + ( + | protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest + | 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('batchGetAccessBindings request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsResponse, + | protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchGetAccessBindings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.batchGetAccessBindings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('batchGetAccessBindings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchGetAccessBindings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsResponse, + ( + | protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchGetAccessBindings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates information about multiple access bindings to an account or - * property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The account or property that owns the access bindings. The parent - * of all provided AccessBinding in UpdateAccessBindingRequest messages must - * match this field. - * Formats: - * - accounts/{account} - * - properties/{property} - * @param {number[]} request.requests - * Required. The requests specifying the access bindings to update. - * A maximum of 1000 access bindings can be updated in a batch. - * @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.analytics.admin.v1alpha.BatchUpdateAccessBindingsResponse|BatchUpdateAccessBindingsResponse}. - * 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/v1alpha/analytics_admin_service.batch_update_access_bindings.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_BatchUpdateAccessBindings_async - */ + /** + * Updates information about multiple access bindings to an account or + * property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account or property that owns the access bindings. The parent + * of all provided AccessBinding in UpdateAccessBindingRequest messages must + * match this field. + * Formats: + * - accounts/{account} + * - properties/{property} + * @param {number[]} request.requests + * Required. The requests specifying the access bindings to update. + * A maximum of 1000 access bindings can be updated in a batch. + * @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.analytics.admin.v1alpha.BatchUpdateAccessBindingsResponse|BatchUpdateAccessBindingsResponse}. + * 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/v1alpha/analytics_admin_service.batch_update_access_bindings.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_BatchUpdateAccessBindings_async + */ batchUpdateAccessBindings( - request?: protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsResponse, + ( + | protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest + | undefined + ), + {} | undefined, + ] + >; batchUpdateAccessBindings( - request: protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsResponse, + | protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchUpdateAccessBindings( - request: protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsResponse, + | protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchUpdateAccessBindings( - request?: protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsResponse, + | protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsResponse, + ( + | protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest + | 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('batchUpdateAccessBindings request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsResponse, + | protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchUpdateAccessBindings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.batchUpdateAccessBindings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsResponse, - protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('batchUpdateAccessBindings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchUpdateAccessBindings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsResponse, + ( + | protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchUpdateAccessBindings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes information about multiple users' links to an account or property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The account or property that owns the access bindings. The parent - * of all provided values for the 'names' field in DeleteAccessBindingRequest - * messages must match this field. Formats: - * - accounts/{account} - * - properties/{property} - * @param {number[]} request.requests - * Required. The requests specifying the access bindings to delete. - * A maximum of 1000 access bindings can be deleted in a batch. - * @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/v1alpha/analytics_admin_service.batch_delete_access_bindings.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_BatchDeleteAccessBindings_async - */ + /** + * Deletes information about multiple users' links to an account or property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The account or property that owns the access bindings. The parent + * of all provided values for the 'names' field in DeleteAccessBindingRequest + * messages must match this field. Formats: + * - accounts/{account} + * - properties/{property} + * @param {number[]} request.requests + * Required. The requests specifying the access bindings to delete. + * A maximum of 1000 access bindings can be deleted in a batch. + * @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/v1alpha/analytics_admin_service.batch_delete_access_bindings.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_BatchDeleteAccessBindings_async + */ batchDeleteAccessBindings( - request?: protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest + | undefined + ), + {} | undefined, + ] + >; batchDeleteAccessBindings( - request: protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchDeleteAccessBindings( - request: protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchDeleteAccessBindings( - request?: protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest + | 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('batchDeleteAccessBindings request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchDeleteAccessBindings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.batchDeleteAccessBindings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('batchDeleteAccessBindings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchDeleteAccessBindings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IBatchDeleteAccessBindingsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchDeleteAccessBindings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for a single ExpandedDataSet. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the ExpandedDataSet to get. - * Example format: properties/1234/expandedDataSets/5678 - * @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.analytics.admin.v1alpha.ExpandedDataSet|ExpandedDataSet}. - * 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/v1alpha/analytics_admin_service.get_expanded_data_set.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetExpandedDataSet_async - */ + /** + * Lookup for a single ExpandedDataSet. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the ExpandedDataSet to get. + * Example format: properties/1234/expandedDataSets/5678 + * @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.analytics.admin.v1alpha.ExpandedDataSet|ExpandedDataSet}. + * 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/v1alpha/analytics_admin_service.get_expanded_data_set.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetExpandedDataSet_async + */ getExpandedDataSet( - request?: protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IExpandedDataSet, + ( + | protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest + | undefined + ), + {} | undefined, + ] + >; getExpandedDataSet( - request: protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IExpandedDataSet, + | protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getExpandedDataSet( - request: protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IExpandedDataSet, + | protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getExpandedDataSet( - request?: protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IExpandedDataSet, + | protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IExpandedDataSet, + ( + | protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest + | 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('getExpandedDataSet request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IExpandedDataSet, + | protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getExpandedDataSet response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getExpandedDataSet(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest|undefined, - {}|undefined - ]) => { - this._log.info('getExpandedDataSet response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getExpandedDataSet(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IExpandedDataSet, + ( + | protos.google.analytics.admin.v1alpha.IGetExpandedDataSetRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getExpandedDataSet response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a ExpandedDataSet. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {google.analytics.admin.v1alpha.ExpandedDataSet} request.expandedDataSet - * Required. The ExpandedDataSet 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.analytics.admin.v1alpha.ExpandedDataSet|ExpandedDataSet}. - * 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/v1alpha/analytics_admin_service.create_expanded_data_set.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateExpandedDataSet_async - */ + /** + * Creates a ExpandedDataSet. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {google.analytics.admin.v1alpha.ExpandedDataSet} request.expandedDataSet + * Required. The ExpandedDataSet 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.analytics.admin.v1alpha.ExpandedDataSet|ExpandedDataSet}. + * 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/v1alpha/analytics_admin_service.create_expanded_data_set.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateExpandedDataSet_async + */ createExpandedDataSet( - request?: protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IExpandedDataSet, + ( + | protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest + | undefined + ), + {} | undefined, + ] + >; createExpandedDataSet( - request: protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IExpandedDataSet, + | protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createExpandedDataSet( - request: protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IExpandedDataSet, + | protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createExpandedDataSet( - request?: protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IExpandedDataSet, + | protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IExpandedDataSet, + ( + | protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest + | 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('createExpandedDataSet request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IExpandedDataSet, + | protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createExpandedDataSet response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createExpandedDataSet(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest|undefined, - {}|undefined - ]) => { - this._log.info('createExpandedDataSet response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createExpandedDataSet(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IExpandedDataSet, + ( + | protos.google.analytics.admin.v1alpha.ICreateExpandedDataSetRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createExpandedDataSet response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a ExpandedDataSet on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.ExpandedDataSet} request.expandedDataSet - * Required. The ExpandedDataSet to update. - * The resource's `name` field is used to identify the ExpandedDataSet to be - * updated. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Field names must be in snake - * case (e.g., "field_to_update"). Omitted fields will not be updated. To - * replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1alpha.ExpandedDataSet|ExpandedDataSet}. - * 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/v1alpha/analytics_admin_service.update_expanded_data_set.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateExpandedDataSet_async - */ + /** + * Updates a ExpandedDataSet on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.ExpandedDataSet} request.expandedDataSet + * Required. The ExpandedDataSet to update. + * The resource's `name` field is used to identify the ExpandedDataSet to be + * updated. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Field names must be in snake + * case (e.g., "field_to_update"). Omitted fields will not be updated. To + * replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1alpha.ExpandedDataSet|ExpandedDataSet}. + * 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/v1alpha/analytics_admin_service.update_expanded_data_set.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateExpandedDataSet_async + */ updateExpandedDataSet( - request?: protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IExpandedDataSet, + ( + | protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest + | undefined + ), + {} | undefined, + ] + >; updateExpandedDataSet( - request: protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IExpandedDataSet, + | protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateExpandedDataSet( - request: protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IExpandedDataSet, + | protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateExpandedDataSet( - request?: protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IExpandedDataSet, + | protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IExpandedDataSet, + ( + | protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest + | 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({ - 'expanded_data_set.name': request.expandedDataSet!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'expanded_data_set.name': request.expandedDataSet!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateExpandedDataSet request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IExpandedDataSet, + | protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateExpandedDataSet response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateExpandedDataSet(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IExpandedDataSet, - protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateExpandedDataSet response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateExpandedDataSet(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IExpandedDataSet, + ( + | protos.google.analytics.admin.v1alpha.IUpdateExpandedDataSetRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateExpandedDataSet response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a ExpandedDataSet on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Example format: properties/1234/expandedDataSets/5678 - * @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/v1alpha/analytics_admin_service.delete_expanded_data_set.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteExpandedDataSet_async - */ + /** + * Deletes a ExpandedDataSet on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Example format: properties/1234/expandedDataSets/5678 + * @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/v1alpha/analytics_admin_service.delete_expanded_data_set.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteExpandedDataSet_async + */ deleteExpandedDataSet( - request?: protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest + | undefined + ), + {} | undefined, + ] + >; deleteExpandedDataSet( - request: protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteExpandedDataSet( - request: protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteExpandedDataSet( - request?: protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest + | 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('deleteExpandedDataSet request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteExpandedDataSet response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteExpandedDataSet(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteExpandedDataSet response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteExpandedDataSet(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteExpandedDataSetRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteExpandedDataSet response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for a single ChannelGroup. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The ChannelGroup to get. - * Example format: properties/1234/channelGroups/5678 - * @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.analytics.admin.v1alpha.ChannelGroup|ChannelGroup}. - * 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/v1alpha/analytics_admin_service.get_channel_group.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetChannelGroup_async - */ + /** + * Lookup for a single ChannelGroup. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The ChannelGroup to get. + * Example format: properties/1234/channelGroups/5678 + * @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.analytics.admin.v1alpha.ChannelGroup|ChannelGroup}. + * 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/v1alpha/analytics_admin_service.get_channel_group.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetChannelGroup_async + */ getChannelGroup( - request?: protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IChannelGroup, + protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest | undefined, + {} | undefined, + ] + >; getChannelGroup( - request: protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IChannelGroup, + | protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getChannelGroup( - request: protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IChannelGroup, + | protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getChannelGroup( - request?: protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IChannelGroup, + | protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IChannelGroup, + protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest | 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('getChannelGroup request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IChannelGroup, + | protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getChannelGroup response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getChannelGroup(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest|undefined, - {}|undefined - ]) => { - this._log.info('getChannelGroup response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getChannelGroup(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IChannelGroup, + ( + | protos.google.analytics.admin.v1alpha.IGetChannelGroupRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getChannelGroup response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a ChannelGroup. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The property for which to create a ChannelGroup. - * Example format: properties/1234 - * @param {google.analytics.admin.v1alpha.ChannelGroup} request.channelGroup - * Required. The ChannelGroup 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.analytics.admin.v1alpha.ChannelGroup|ChannelGroup}. - * 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/v1alpha/analytics_admin_service.create_channel_group.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateChannelGroup_async - */ + /** + * Creates a ChannelGroup. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The property for which to create a ChannelGroup. + * Example format: properties/1234 + * @param {google.analytics.admin.v1alpha.ChannelGroup} request.channelGroup + * Required. The ChannelGroup 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.analytics.admin.v1alpha.ChannelGroup|ChannelGroup}. + * 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/v1alpha/analytics_admin_service.create_channel_group.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateChannelGroup_async + */ createChannelGroup( - request?: protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IChannelGroup, + ( + | protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest + | undefined + ), + {} | undefined, + ] + >; createChannelGroup( - request: protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IChannelGroup, + | protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createChannelGroup( - request: protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IChannelGroup, + | protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createChannelGroup( - request?: protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IChannelGroup, + | protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IChannelGroup, + ( + | protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest + | 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('createChannelGroup request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IChannelGroup, + | protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createChannelGroup response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createChannelGroup(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest|undefined, - {}|undefined - ]) => { - this._log.info('createChannelGroup response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createChannelGroup(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IChannelGroup, + ( + | protos.google.analytics.admin.v1alpha.ICreateChannelGroupRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createChannelGroup response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a ChannelGroup. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.ChannelGroup} request.channelGroup - * Required. The ChannelGroup to update. - * The resource's `name` field is used to identify the ChannelGroup to be - * updated. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Field names must be in snake - * case (e.g., "field_to_update"). Omitted fields will not be updated. To - * replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1alpha.ChannelGroup|ChannelGroup}. - * 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/v1alpha/analytics_admin_service.update_channel_group.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateChannelGroup_async - */ + /** + * Updates a ChannelGroup. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.ChannelGroup} request.channelGroup + * Required. The ChannelGroup to update. + * The resource's `name` field is used to identify the ChannelGroup to be + * updated. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Field names must be in snake + * case (e.g., "field_to_update"). Omitted fields will not be updated. To + * replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1alpha.ChannelGroup|ChannelGroup}. + * 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/v1alpha/analytics_admin_service.update_channel_group.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateChannelGroup_async + */ updateChannelGroup( - request?: protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IChannelGroup, + ( + | protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest + | undefined + ), + {} | undefined, + ] + >; updateChannelGroup( - request: protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IChannelGroup, + | protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateChannelGroup( - request: protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IChannelGroup, + | protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateChannelGroup( - request?: protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IChannelGroup, + | protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IChannelGroup, + ( + | protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest + | 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({ - 'channel_group.name': request.channelGroup!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'channel_group.name': request.channelGroup!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateChannelGroup request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IChannelGroup, + | protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateChannelGroup response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateChannelGroup(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IChannelGroup, - protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateChannelGroup response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateChannelGroup(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IChannelGroup, + ( + | protos.google.analytics.admin.v1alpha.IUpdateChannelGroupRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateChannelGroup response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a ChannelGroup on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The ChannelGroup to delete. - * Example format: properties/1234/channelGroups/5678 - * @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/v1alpha/analytics_admin_service.delete_channel_group.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteChannelGroup_async - */ + /** + * Deletes a ChannelGroup on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The ChannelGroup to delete. + * Example format: properties/1234/channelGroups/5678 + * @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/v1alpha/analytics_admin_service.delete_channel_group.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteChannelGroup_async + */ deleteChannelGroup( - request?: protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest + | undefined + ), + {} | undefined, + ] + >; deleteChannelGroup( - request: protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteChannelGroup( - request: protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteChannelGroup( - request?: protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest + | 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('deleteChannelGroup request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteChannelGroup response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteChannelGroup(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteChannelGroup response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteChannelGroup(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteChannelGroupRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteChannelGroup response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a BigQueryLink. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {google.analytics.admin.v1alpha.BigQueryLink} request.bigqueryLink - * Required. The BigQueryLink 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.analytics.admin.v1alpha.BigQueryLink|BigQueryLink}. - * 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/v1alpha/analytics_admin_service.create_big_query_link.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateBigQueryLink_async - */ + /** + * Creates a BigQueryLink. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {google.analytics.admin.v1alpha.BigQueryLink} request.bigqueryLink + * Required. The BigQueryLink 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.analytics.admin.v1alpha.BigQueryLink|BigQueryLink}. + * 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/v1alpha/analytics_admin_service.create_big_query_link.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateBigQueryLink_async + */ createBigQueryLink( - request?: protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IBigQueryLink, + ( + | protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest + | undefined + ), + {} | undefined, + ] + >; createBigQueryLink( - request: protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IBigQueryLink, + | protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createBigQueryLink( - request: protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IBigQueryLink, + | protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createBigQueryLink( - request?: protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IBigQueryLink, + | protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IBigQueryLink, + ( + | protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest + | 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('createBigQueryLink request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IBigQueryLink, + | protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createBigQueryLink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createBigQueryLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('createBigQueryLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createBigQueryLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IBigQueryLink, + ( + | protos.google.analytics.admin.v1alpha.ICreateBigQueryLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createBigQueryLink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for a single BigQuery Link. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the BigQuery link to lookup. - * Format: properties/{property_id}/bigQueryLinks/{bigquery_link_id} - * Example: properties/123/bigQueryLinks/456 - * @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.analytics.admin.v1alpha.BigQueryLink|BigQueryLink}. - * 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/v1alpha/analytics_admin_service.get_big_query_link.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetBigQueryLink_async - */ + /** + * Lookup for a single BigQuery Link. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the BigQuery link to lookup. + * Format: properties/{property_id}/bigQueryLinks/{bigquery_link_id} + * Example: properties/123/bigQueryLinks/456 + * @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.analytics.admin.v1alpha.BigQueryLink|BigQueryLink}. + * 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/v1alpha/analytics_admin_service.get_big_query_link.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetBigQueryLink_async + */ getBigQueryLink( - request?: protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IBigQueryLink, + protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest | undefined, + {} | undefined, + ] + >; getBigQueryLink( - request: protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IBigQueryLink, + | protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getBigQueryLink( - request: protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IBigQueryLink, + | protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getBigQueryLink( - request?: protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IBigQueryLink, + | protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IBigQueryLink, + protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest | 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('getBigQueryLink request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IBigQueryLink, + | protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getBigQueryLink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getBigQueryLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('getBigQueryLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getBigQueryLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IBigQueryLink, + ( + | protos.google.analytics.admin.v1alpha.IGetBigQueryLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getBigQueryLink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a BigQueryLink on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The BigQueryLink to delete. - * Example format: properties/1234/bigQueryLinks/5678 - * @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/v1alpha/analytics_admin_service.delete_big_query_link.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteBigQueryLink_async - */ + /** + * Deletes a BigQueryLink on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The BigQueryLink to delete. + * Example format: properties/1234/bigQueryLinks/5678 + * @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/v1alpha/analytics_admin_service.delete_big_query_link.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteBigQueryLink_async + */ deleteBigQueryLink( - request?: protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest + | undefined + ), + {} | undefined, + ] + >; deleteBigQueryLink( - request: protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteBigQueryLink( - request: protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteBigQueryLink( - request?: protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest + | 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('deleteBigQueryLink request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteBigQueryLink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteBigQueryLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteBigQueryLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteBigQueryLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteBigQueryLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteBigQueryLink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a BigQueryLink. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.BigQueryLink} request.bigqueryLink - * Required. The settings to update. - * The `name` field is used to identify the settings to be updated. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Field names must be in snake - * case (e.g., "field_to_update"). Omitted fields will not be updated. To - * replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1alpha.BigQueryLink|BigQueryLink}. - * 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/v1alpha/analytics_admin_service.update_big_query_link.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateBigQueryLink_async - */ + /** + * Updates a BigQueryLink. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.BigQueryLink} request.bigqueryLink + * Required. The settings to update. + * The `name` field is used to identify the settings to be updated. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Field names must be in snake + * case (e.g., "field_to_update"). Omitted fields will not be updated. To + * replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1alpha.BigQueryLink|BigQueryLink}. + * 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/v1alpha/analytics_admin_service.update_big_query_link.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateBigQueryLink_async + */ updateBigQueryLink( - request?: protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IBigQueryLink, + ( + | protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest + | undefined + ), + {} | undefined, + ] + >; updateBigQueryLink( - request: protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IBigQueryLink, + | protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateBigQueryLink( - request: protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IBigQueryLink, + | protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateBigQueryLink( - request?: protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IBigQueryLink, + | protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IBigQueryLink, + ( + | protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest + | 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({ - 'bigquery_link.name': request.bigqueryLink!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'bigquery_link.name': request.bigqueryLink!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateBigQueryLink request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IBigQueryLink, + | protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateBigQueryLink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateBigQueryLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IBigQueryLink, - protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateBigQueryLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateBigQueryLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IBigQueryLink, + ( + | protos.google.analytics.admin.v1alpha.IUpdateBigQueryLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateBigQueryLink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns the enhanced measurement settings for this data stream. - * Note that the stream must enable enhanced measurement for these settings to - * take effect. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the settings to lookup. - * Format: - * properties/{property}/dataStreams/{data_stream}/enhancedMeasurementSettings - * Example: "properties/1000/dataStreams/2000/enhancedMeasurementSettings" - * @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.analytics.admin.v1alpha.EnhancedMeasurementSettings|EnhancedMeasurementSettings}. - * 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/v1alpha/analytics_admin_service.get_enhanced_measurement_settings.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetEnhancedMeasurementSettings_async - */ + /** + * Returns the enhanced measurement settings for this data stream. + * Note that the stream must enable enhanced measurement for these settings to + * take effect. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the settings to lookup. + * Format: + * properties/{property}/dataStreams/{data_stream}/enhancedMeasurementSettings + * Example: "properties/1000/dataStreams/2000/enhancedMeasurementSettings" + * @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.analytics.admin.v1alpha.EnhancedMeasurementSettings|EnhancedMeasurementSettings}. + * 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/v1alpha/analytics_admin_service.get_enhanced_measurement_settings.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetEnhancedMeasurementSettings_async + */ getEnhancedMeasurementSettings( - request?: protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, - protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, + ( + | protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest + | undefined + ), + {} | undefined, + ] + >; getEnhancedMeasurementSettings( - request: protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, - protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, + | protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getEnhancedMeasurementSettings( - request: protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, - protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, + | protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getEnhancedMeasurementSettings( - request?: protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, - protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, - protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, - protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, + | protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, + ( + | protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest + | 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('getEnhancedMeasurementSettings request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, - protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, + | protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('getEnhancedMeasurementSettings response %j', response); + this._log.info( + 'getEnhancedMeasurementSettings response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getEnhancedMeasurementSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, - protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('getEnhancedMeasurementSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getEnhancedMeasurementSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, + ( + | protos.google.analytics.admin.v1alpha.IGetEnhancedMeasurementSettingsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'getEnhancedMeasurementSettings response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the enhanced measurement settings for this data stream. - * Note that the stream must enable enhanced measurement for these settings to - * take effect. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.EnhancedMeasurementSettings} request.enhancedMeasurementSettings - * Required. The settings to update. - * The `name` field is used to identify the settings to be updated. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Field names must be in snake - * case (e.g., "field_to_update"). Omitted fields will not be updated. To - * replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1alpha.EnhancedMeasurementSettings|EnhancedMeasurementSettings}. - * 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/v1alpha/analytics_admin_service.update_enhanced_measurement_settings.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateEnhancedMeasurementSettings_async - */ + /** + * Updates the enhanced measurement settings for this data stream. + * Note that the stream must enable enhanced measurement for these settings to + * take effect. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.EnhancedMeasurementSettings} request.enhancedMeasurementSettings + * Required. The settings to update. + * The `name` field is used to identify the settings to be updated. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Field names must be in snake + * case (e.g., "field_to_update"). Omitted fields will not be updated. To + * replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1alpha.EnhancedMeasurementSettings|EnhancedMeasurementSettings}. + * 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/v1alpha/analytics_admin_service.update_enhanced_measurement_settings.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateEnhancedMeasurementSettings_async + */ updateEnhancedMeasurementSettings( - request?: protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, - protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, + ( + | protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest + | undefined + ), + {} | undefined, + ] + >; updateEnhancedMeasurementSettings( - request: protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, - protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, + | protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateEnhancedMeasurementSettings( - request: protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, - protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, + | protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateEnhancedMeasurementSettings( - request?: protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, - protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, - protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, - protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, + | protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, + ( + | protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest + | 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({ - 'enhanced_measurement_settings.name': request.enhancedMeasurementSettings!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'enhanced_measurement_settings.name': + request.enhancedMeasurementSettings!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateEnhancedMeasurementSettings request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, - protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, + | protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('updateEnhancedMeasurementSettings response %j', response); + this._log.info( + 'updateEnhancedMeasurementSettings response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateEnhancedMeasurementSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, - protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateEnhancedMeasurementSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateEnhancedMeasurementSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings, + ( + | protos.google.analytics.admin.v1alpha.IUpdateEnhancedMeasurementSettingsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'updateEnhancedMeasurementSettings response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Looks up a single AdSenseLink. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Unique identifier for the AdSense Link requested. - * Format: properties/{propertyId}/adSenseLinks/{linkId} - * Example: properties/1234/adSenseLinks/5678 - * @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.analytics.admin.v1alpha.AdSenseLink|AdSenseLink}. - * 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/v1alpha/analytics_admin_service.get_ad_sense_link.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetAdSenseLink_async - */ + /** + * Looks up a single AdSenseLink. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Unique identifier for the AdSense Link requested. + * Format: properties/{propertyId}/adSenseLinks/{linkId} + * Example: properties/1234/adSenseLinks/5678 + * @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.analytics.admin.v1alpha.AdSenseLink|AdSenseLink}. + * 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/v1alpha/analytics_admin_service.get_ad_sense_link.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetAdSenseLink_async + */ getAdSenseLink( - request?: protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IAdSenseLink, - protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAdSenseLink, + protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest | undefined, + {} | undefined, + ] + >; getAdSenseLink( - request: protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAdSenseLink, - protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAdSenseLink, + | protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAdSenseLink( - request: protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAdSenseLink, - protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAdSenseLink, + | protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAdSenseLink( - request?: protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IAdSenseLink, - protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IAdSenseLink, - protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IAdSenseLink, - protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IAdSenseLink, + | protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAdSenseLink, + protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest | 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('getAdSenseLink request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IAdSenseLink, - protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IAdSenseLink, + | protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getAdSenseLink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getAdSenseLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IAdSenseLink, - protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('getAdSenseLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getAdSenseLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IAdSenseLink, + ( + | protos.google.analytics.admin.v1alpha.IGetAdSenseLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getAdSenseLink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates an AdSenseLink. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The property for which to create an AdSense Link. - * Format: properties/{propertyId} - * Example: properties/1234 - * @param {google.analytics.admin.v1alpha.AdSenseLink} request.adsenseLink - * Required. The AdSense Link 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.analytics.admin.v1alpha.AdSenseLink|AdSenseLink}. - * 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/v1alpha/analytics_admin_service.create_ad_sense_link.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateAdSenseLink_async - */ + /** + * Creates an AdSenseLink. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The property for which to create an AdSense Link. + * Format: properties/{propertyId} + * Example: properties/1234 + * @param {google.analytics.admin.v1alpha.AdSenseLink} request.adsenseLink + * Required. The AdSense Link 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.analytics.admin.v1alpha.AdSenseLink|AdSenseLink}. + * 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/v1alpha/analytics_admin_service.create_ad_sense_link.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateAdSenseLink_async + */ createAdSenseLink( - request?: protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IAdSenseLink, - protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAdSenseLink, + ( + | protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest + | undefined + ), + {} | undefined, + ] + >; createAdSenseLink( - request: protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAdSenseLink, - protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAdSenseLink, + | protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createAdSenseLink( - request: protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IAdSenseLink, - protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IAdSenseLink, + | protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createAdSenseLink( - request?: protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IAdSenseLink, - protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IAdSenseLink, - protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IAdSenseLink, - protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IAdSenseLink, + | protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAdSenseLink, + ( + | protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest + | 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('createAdSenseLink request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IAdSenseLink, - protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IAdSenseLink, + | protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createAdSenseLink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createAdSenseLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IAdSenseLink, - protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('createAdSenseLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createAdSenseLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IAdSenseLink, + ( + | protos.google.analytics.admin.v1alpha.ICreateAdSenseLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createAdSenseLink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes an AdSenseLink. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Unique identifier for the AdSense Link to be deleted. - * Format: properties/{propertyId}/adSenseLinks/{linkId} - * Example: properties/1234/adSenseLinks/5678 - * @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/v1alpha/analytics_admin_service.delete_ad_sense_link.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteAdSenseLink_async - */ + /** + * Deletes an AdSenseLink. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Unique identifier for the AdSense Link to be deleted. + * Format: properties/{propertyId}/adSenseLinks/{linkId} + * Example: properties/1234/adSenseLinks/5678 + * @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/v1alpha/analytics_admin_service.delete_ad_sense_link.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteAdSenseLink_async + */ deleteAdSenseLink( - request?: protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest + | undefined + ), + {} | undefined, + ] + >; deleteAdSenseLink( - request: protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteAdSenseLink( - request: protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteAdSenseLink( - request?: protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest + | 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('deleteAdSenseLink request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteAdSenseLink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteAdSenseLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteAdSenseLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteAdSenseLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteAdSenseLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteAdSenseLink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for a single EventCreateRule. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the EventCreateRule to get. - * Example format: properties/123/dataStreams/456/eventCreateRules/789 - * @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.analytics.admin.v1alpha.EventCreateRule|EventCreateRule}. - * 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/v1alpha/analytics_admin_service.get_event_create_rule.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetEventCreateRule_async - */ + /** + * Lookup for a single EventCreateRule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the EventCreateRule to get. + * Example format: properties/123/dataStreams/456/eventCreateRules/789 + * @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.analytics.admin.v1alpha.EventCreateRule|EventCreateRule}. + * 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/v1alpha/analytics_admin_service.get_event_create_rule.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetEventCreateRule_async + */ getEventCreateRule( - request?: protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IEventCreateRule, + ( + | protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest + | undefined + ), + {} | undefined, + ] + >; getEventCreateRule( - request: protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IEventCreateRule, + | protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getEventCreateRule( - request: protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IEventCreateRule, + | protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getEventCreateRule( - request?: protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IEventCreateRule, + | protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IEventCreateRule, + ( + | protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest + | 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('getEventCreateRule request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IEventCreateRule, + | protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getEventCreateRule response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getEventCreateRule(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest|undefined, - {}|undefined - ]) => { - this._log.info('getEventCreateRule response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getEventCreateRule(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IEventCreateRule, + ( + | protos.google.analytics.admin.v1alpha.IGetEventCreateRuleRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getEventCreateRule response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates an EventCreateRule. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/123/dataStreams/456 - * @param {google.analytics.admin.v1alpha.EventCreateRule} request.eventCreateRule - * Required. The EventCreateRule 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.analytics.admin.v1alpha.EventCreateRule|EventCreateRule}. - * 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/v1alpha/analytics_admin_service.create_event_create_rule.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateEventCreateRule_async - */ + /** + * Creates an EventCreateRule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/123/dataStreams/456 + * @param {google.analytics.admin.v1alpha.EventCreateRule} request.eventCreateRule + * Required. The EventCreateRule 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.analytics.admin.v1alpha.EventCreateRule|EventCreateRule}. + * 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/v1alpha/analytics_admin_service.create_event_create_rule.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateEventCreateRule_async + */ createEventCreateRule( - request?: protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IEventCreateRule, + ( + | protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest + | undefined + ), + {} | undefined, + ] + >; createEventCreateRule( - request: protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IEventCreateRule, + | protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createEventCreateRule( - request: protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IEventCreateRule, + | protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createEventCreateRule( - request?: protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IEventCreateRule, + | protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IEventCreateRule, + ( + | protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest + | 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('createEventCreateRule request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IEventCreateRule, + | protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createEventCreateRule response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createEventCreateRule(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest|undefined, - {}|undefined - ]) => { - this._log.info('createEventCreateRule response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createEventCreateRule(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IEventCreateRule, + ( + | protos.google.analytics.admin.v1alpha.ICreateEventCreateRuleRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createEventCreateRule response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates an EventCreateRule. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.EventCreateRule} request.eventCreateRule - * Required. The EventCreateRule to update. - * The resource's `name` field is used to identify the EventCreateRule to be - * updated. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Field names must be in snake - * case (e.g., "field_to_update"). Omitted fields will not be updated. To - * replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1alpha.EventCreateRule|EventCreateRule}. - * 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/v1alpha/analytics_admin_service.update_event_create_rule.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateEventCreateRule_async - */ + /** + * Updates an EventCreateRule. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.EventCreateRule} request.eventCreateRule + * Required. The EventCreateRule to update. + * The resource's `name` field is used to identify the EventCreateRule to be + * updated. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Field names must be in snake + * case (e.g., "field_to_update"). Omitted fields will not be updated. To + * replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1alpha.EventCreateRule|EventCreateRule}. + * 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/v1alpha/analytics_admin_service.update_event_create_rule.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateEventCreateRule_async + */ updateEventCreateRule( - request?: protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IEventCreateRule, + ( + | protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest + | undefined + ), + {} | undefined, + ] + >; updateEventCreateRule( - request: protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IEventCreateRule, + | protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateEventCreateRule( - request: protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IEventCreateRule, + | protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateEventCreateRule( - request?: protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IEventCreateRule, + | protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IEventCreateRule, + ( + | protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest + | 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({ - 'event_create_rule.name': request.eventCreateRule!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'event_create_rule.name': request.eventCreateRule!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateEventCreateRule request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IEventCreateRule, + | protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateEventCreateRule response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateEventCreateRule(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IEventCreateRule, - protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateEventCreateRule response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateEventCreateRule(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IEventCreateRule, + ( + | protos.google.analytics.admin.v1alpha.IUpdateEventCreateRuleRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateEventCreateRule response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes an EventCreateRule. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Example format: - * properties/123/dataStreams/456/eventCreateRules/789 - * @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/v1alpha/analytics_admin_service.delete_event_create_rule.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteEventCreateRule_async - */ + /** + * Deletes an EventCreateRule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Example format: + * properties/123/dataStreams/456/eventCreateRules/789 + * @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/v1alpha/analytics_admin_service.delete_event_create_rule.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteEventCreateRule_async + */ deleteEventCreateRule( - request?: protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest + | undefined + ), + {} | undefined, + ] + >; deleteEventCreateRule( - request: protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteEventCreateRule( - request: protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteEventCreateRule( - request?: protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest + | 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('deleteEventCreateRule request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteEventCreateRule response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteEventCreateRule(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteEventCreateRule response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteEventCreateRule(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteEventCreateRuleRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteEventCreateRule response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for a single EventEditRule. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the EventEditRule to get. - * Example format: properties/123/dataStreams/456/eventEditRules/789 - * @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.analytics.admin.v1alpha.EventEditRule|EventEditRule}. - * 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/v1alpha/analytics_admin_service.get_event_edit_rule.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetEventEditRule_async - */ + /** + * Lookup for a single EventEditRule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the EventEditRule to get. + * Example format: properties/123/dataStreams/456/eventEditRules/789 + * @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.analytics.admin.v1alpha.EventEditRule|EventEditRule}. + * 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/v1alpha/analytics_admin_service.get_event_edit_rule.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetEventEditRule_async + */ getEventEditRule( - request?: protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IEventEditRule, + ( + | protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest + | undefined + ), + {} | undefined, + ] + >; getEventEditRule( - request: protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IEventEditRule, + | protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getEventEditRule( - request: protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IEventEditRule, + | protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getEventEditRule( - request?: protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IEventEditRule, + | protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IEventEditRule, + ( + | protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest + | 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('getEventEditRule request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IEventEditRule, + | protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getEventEditRule response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getEventEditRule(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest|undefined, - {}|undefined - ]) => { - this._log.info('getEventEditRule response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getEventEditRule(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IEventEditRule, + ( + | protos.google.analytics.admin.v1alpha.IGetEventEditRuleRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getEventEditRule response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates an EventEditRule. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/123/dataStreams/456 - * @param {google.analytics.admin.v1alpha.EventEditRule} request.eventEditRule - * Required. The EventEditRule 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.analytics.admin.v1alpha.EventEditRule|EventEditRule}. - * 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/v1alpha/analytics_admin_service.create_event_edit_rule.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateEventEditRule_async - */ + /** + * Creates an EventEditRule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/123/dataStreams/456 + * @param {google.analytics.admin.v1alpha.EventEditRule} request.eventEditRule + * Required. The EventEditRule 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.analytics.admin.v1alpha.EventEditRule|EventEditRule}. + * 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/v1alpha/analytics_admin_service.create_event_edit_rule.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateEventEditRule_async + */ createEventEditRule( - request?: protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IEventEditRule, + ( + | protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest + | undefined + ), + {} | undefined, + ] + >; createEventEditRule( - request: protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IEventEditRule, + | protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createEventEditRule( - request: protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IEventEditRule, + | protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createEventEditRule( - request?: protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IEventEditRule, + | protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IEventEditRule, + ( + | protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest + | 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('createEventEditRule request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IEventEditRule, + | protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createEventEditRule response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createEventEditRule(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest|undefined, - {}|undefined - ]) => { - this._log.info('createEventEditRule response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createEventEditRule(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IEventEditRule, + ( + | protos.google.analytics.admin.v1alpha.ICreateEventEditRuleRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createEventEditRule response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates an EventEditRule. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.EventEditRule} request.eventEditRule - * Required. The EventEditRule to update. - * The resource's `name` field is used to identify the EventEditRule to be - * updated. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Field names must be in snake - * case (e.g., "field_to_update"). Omitted fields will not be updated. To - * replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1alpha.EventEditRule|EventEditRule}. - * 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/v1alpha/analytics_admin_service.update_event_edit_rule.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateEventEditRule_async - */ + /** + * Updates an EventEditRule. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.EventEditRule} request.eventEditRule + * Required. The EventEditRule to update. + * The resource's `name` field is used to identify the EventEditRule to be + * updated. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Field names must be in snake + * case (e.g., "field_to_update"). Omitted fields will not be updated. To + * replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1alpha.EventEditRule|EventEditRule}. + * 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/v1alpha/analytics_admin_service.update_event_edit_rule.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateEventEditRule_async + */ updateEventEditRule( - request?: protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IEventEditRule, + ( + | protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest + | undefined + ), + {} | undefined, + ] + >; updateEventEditRule( - request: protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IEventEditRule, + | protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateEventEditRule( - request: protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IEventEditRule, + | protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateEventEditRule( - request?: protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IEventEditRule, + | protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IEventEditRule, + ( + | protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest + | 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({ - 'event_edit_rule.name': request.eventEditRule!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'event_edit_rule.name': request.eventEditRule!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateEventEditRule request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IEventEditRule, + | protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateEventEditRule response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateEventEditRule(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IEventEditRule, - protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateEventEditRule response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateEventEditRule(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IEventEditRule, + ( + | protos.google.analytics.admin.v1alpha.IUpdateEventEditRuleRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateEventEditRule response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes an EventEditRule. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Example format: properties/123/dataStreams/456/eventEditRules/789 - * @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/v1alpha/analytics_admin_service.delete_event_edit_rule.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteEventEditRule_async - */ + /** + * Deletes an EventEditRule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Example format: properties/123/dataStreams/456/eventEditRules/789 + * @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/v1alpha/analytics_admin_service.delete_event_edit_rule.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteEventEditRule_async + */ deleteEventEditRule( - request?: protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest + | undefined + ), + {} | undefined, + ] + >; deleteEventEditRule( - request: protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteEventEditRule( - request: protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteEventEditRule( - request?: protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest + | 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('deleteEventEditRule request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteEventEditRule response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteEventEditRule(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteEventEditRule response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteEventEditRule(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteEventEditRuleRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteEventEditRule response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Changes the processing order of event edit rules on the specified stream. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/123/dataStreams/456 - * @param {string[]} request.eventEditRules - * Required. EventEditRule resource names for the specified data stream, in - * the needed processing order. All EventEditRules for the stream must be - * present in the list. - * @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/v1alpha/analytics_admin_service.reorder_event_edit_rules.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ReorderEventEditRules_async - */ + /** + * Changes the processing order of event edit rules on the specified stream. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/123/dataStreams/456 + * @param {string[]} request.eventEditRules + * Required. EventEditRule resource names for the specified data stream, in + * the needed processing order. All EventEditRules for the stream must be + * present in the list. + * @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/v1alpha/analytics_admin_service.reorder_event_edit_rules.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ReorderEventEditRules_async + */ reorderEventEditRules( - request?: protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest + | undefined + ), + {} | undefined, + ] + >; reorderEventEditRules( - request: protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest + | null + | undefined, + {} | null | undefined + >, + ): void; reorderEventEditRules( - request: protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest + | null + | undefined, + {} | null | undefined + >, + ): void; reorderEventEditRules( - request?: protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest + | 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('reorderEventEditRules request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('reorderEventEditRules response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.reorderEventEditRules(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest|undefined, - {}|undefined - ]) => { - this._log.info('reorderEventEditRules response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .reorderEventEditRules(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IReorderEventEditRulesRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('reorderEventEditRules response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a DataRedactionSettings on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.DataRedactionSettings} request.dataRedactionSettings - * Required. The settings to update. - * The `name` field is used to identify the settings to be updated. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Field names must be in snake - * case (e.g., "field_to_update"). Omitted fields will not be updated. To - * replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1alpha.DataRedactionSettings|DataRedactionSettings}. - * 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/v1alpha/analytics_admin_service.update_data_redaction_settings.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateDataRedactionSettings_async - */ + /** + * Updates a DataRedactionSettings on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.DataRedactionSettings} request.dataRedactionSettings + * Required. The settings to update. + * The `name` field is used to identify the settings to be updated. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Field names must be in snake + * case (e.g., "field_to_update"). Omitted fields will not be updated. To + * replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1alpha.DataRedactionSettings|DataRedactionSettings}. + * 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/v1alpha/analytics_admin_service.update_data_redaction_settings.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateDataRedactionSettings_async + */ updateDataRedactionSettings( - request?: protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IDataRedactionSettings, - protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDataRedactionSettings, + ( + | protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest + | undefined + ), + {} | undefined, + ] + >; updateDataRedactionSettings( - request: protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDataRedactionSettings, - protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDataRedactionSettings, + | protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDataRedactionSettings( - request: protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDataRedactionSettings, - protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDataRedactionSettings, + | protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDataRedactionSettings( - request?: protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IDataRedactionSettings, - protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IDataRedactionSettings, - protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IDataRedactionSettings, - protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IDataRedactionSettings, + | protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDataRedactionSettings, + ( + | protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest + | 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({ - 'data_redaction_settings.name': request.dataRedactionSettings!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'data_redaction_settings.name': + request.dataRedactionSettings!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateDataRedactionSettings request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IDataRedactionSettings, - protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IDataRedactionSettings, + | protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateDataRedactionSettings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateDataRedactionSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IDataRedactionSettings, - protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateDataRedactionSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateDataRedactionSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IDataRedactionSettings, + ( + | protos.google.analytics.admin.v1alpha.IUpdateDataRedactionSettingsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateDataRedactionSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for a single DataRedactionSettings. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the settings to lookup. - * Format: - * properties/{property}/dataStreams/{data_stream}/dataRedactionSettings - * Example: "properties/1000/dataStreams/2000/dataRedactionSettings" - * @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.analytics.admin.v1alpha.DataRedactionSettings|DataRedactionSettings}. - * 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/v1alpha/analytics_admin_service.get_data_redaction_settings.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetDataRedactionSettings_async - */ + /** + * Lookup for a single DataRedactionSettings. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the settings to lookup. + * Format: + * properties/{property}/dataStreams/{data_stream}/dataRedactionSettings + * Example: "properties/1000/dataStreams/2000/dataRedactionSettings" + * @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.analytics.admin.v1alpha.DataRedactionSettings|DataRedactionSettings}. + * 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/v1alpha/analytics_admin_service.get_data_redaction_settings.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetDataRedactionSettings_async + */ getDataRedactionSettings( - request?: protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IDataRedactionSettings, - protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDataRedactionSettings, + ( + | protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest + | undefined + ), + {} | undefined, + ] + >; getDataRedactionSettings( - request: protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDataRedactionSettings, - protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDataRedactionSettings, + | protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDataRedactionSettings( - request: protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IDataRedactionSettings, - protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IDataRedactionSettings, + | protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDataRedactionSettings( - request?: protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.IDataRedactionSettings, - protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IDataRedactionSettings, - protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IDataRedactionSettings, - protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IDataRedactionSettings, + | protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDataRedactionSettings, + ( + | protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest + | 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('getDataRedactionSettings request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IDataRedactionSettings, - protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IDataRedactionSettings, + | protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getDataRedactionSettings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getDataRedactionSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IDataRedactionSettings, - protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('getDataRedactionSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getDataRedactionSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IDataRedactionSettings, + ( + | protos.google.analytics.admin.v1alpha.IGetDataRedactionSettingsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getDataRedactionSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for a single CalculatedMetric. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the CalculatedMetric to get. - * Format: properties/{property_id}/calculatedMetrics/{calculated_metric_id} - * Example: properties/1234/calculatedMetrics/Metric01 - * @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.analytics.admin.v1alpha.CalculatedMetric|CalculatedMetric}. - * 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/v1alpha/analytics_admin_service.get_calculated_metric.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetCalculatedMetric_async - */ + /** + * Lookup for a single CalculatedMetric. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the CalculatedMetric to get. + * Format: properties/{property_id}/calculatedMetrics/{calculated_metric_id} + * Example: properties/1234/calculatedMetrics/Metric01 + * @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.analytics.admin.v1alpha.CalculatedMetric|CalculatedMetric}. + * 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/v1alpha/analytics_admin_service.get_calculated_metric.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetCalculatedMetric_async + */ getCalculatedMetric( - request?: protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICalculatedMetric, + ( + | protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest + | undefined + ), + {} | undefined, + ] + >; getCalculatedMetric( - request: protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.ICalculatedMetric, + | protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getCalculatedMetric( - request: protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.ICalculatedMetric, + | protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getCalculatedMetric( - request?: protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.ICalculatedMetric, + | protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICalculatedMetric, + ( + | protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest + | 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('getCalculatedMetric request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.ICalculatedMetric, + | protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getCalculatedMetric response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getCalculatedMetric(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest|undefined, - {}|undefined - ]) => { - this._log.info('getCalculatedMetric response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getCalculatedMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.ICalculatedMetric, + ( + | protos.google.analytics.admin.v1alpha.IGetCalculatedMetricRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getCalculatedMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a CalculatedMetric. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Format: properties/{property_id} - * Example: properties/1234 - * @param {string} request.calculatedMetricId - * Required. The ID to use for the calculated metric which will become the - * final component of the calculated metric's resource name. - * - * This value should be 1-80 characters and valid characters are - * /[a-zA-Z0-9_]/, no spaces allowed. calculated_metric_id must be unique - * between all calculated metrics under a property. The calculated_metric_id - * is used when referencing this calculated metric from external APIs, for - * example, "calcMetric:{calculated_metric_id}". - * @param {google.analytics.admin.v1alpha.CalculatedMetric} request.calculatedMetric - * Required. The CalculatedMetric 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.analytics.admin.v1alpha.CalculatedMetric|CalculatedMetric}. - * 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/v1alpha/analytics_admin_service.create_calculated_metric.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateCalculatedMetric_async - */ + /** + * Creates a CalculatedMetric. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Format: properties/{property_id} + * Example: properties/1234 + * @param {string} request.calculatedMetricId + * Required. The ID to use for the calculated metric which will become the + * final component of the calculated metric's resource name. + * + * This value should be 1-80 characters and valid characters are + * /[a-zA-Z0-9_]/, no spaces allowed. calculated_metric_id must be unique + * between all calculated metrics under a property. The calculated_metric_id + * is used when referencing this calculated metric from external APIs, for + * example, "calcMetric:{calculated_metric_id}". + * @param {google.analytics.admin.v1alpha.CalculatedMetric} request.calculatedMetric + * Required. The CalculatedMetric 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.analytics.admin.v1alpha.CalculatedMetric|CalculatedMetric}. + * 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/v1alpha/analytics_admin_service.create_calculated_metric.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateCalculatedMetric_async + */ createCalculatedMetric( - request?: protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICalculatedMetric, + ( + | protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest + | undefined + ), + {} | undefined, + ] + >; createCalculatedMetric( - request: protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.ICalculatedMetric, + | protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createCalculatedMetric( - request: protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.ICalculatedMetric, + | protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createCalculatedMetric( - request?: protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.ICalculatedMetric, + | protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICalculatedMetric, + ( + | protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest + | 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('createCalculatedMetric request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.ICalculatedMetric, + | protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createCalculatedMetric response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createCalculatedMetric(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest|undefined, - {}|undefined - ]) => { - this._log.info('createCalculatedMetric response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createCalculatedMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.ICalculatedMetric, + ( + | protos.google.analytics.admin.v1alpha.ICreateCalculatedMetricRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createCalculatedMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a CalculatedMetric on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.CalculatedMetric} request.calculatedMetric - * Required. The CalculatedMetric to update - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Omitted fields will not be - * updated. To replace the entire entity, use one path with the string "*" to - * match all fields. - * @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.analytics.admin.v1alpha.CalculatedMetric|CalculatedMetric}. - * 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/v1alpha/analytics_admin_service.update_calculated_metric.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateCalculatedMetric_async - */ + /** + * Updates a CalculatedMetric on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.CalculatedMetric} request.calculatedMetric + * Required. The CalculatedMetric to update + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Omitted fields will not be + * updated. To replace the entire entity, use one path with the string "*" to + * match all fields. + * @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.analytics.admin.v1alpha.CalculatedMetric|CalculatedMetric}. + * 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/v1alpha/analytics_admin_service.update_calculated_metric.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateCalculatedMetric_async + */ updateCalculatedMetric( - request?: protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICalculatedMetric, + ( + | protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest + | undefined + ), + {} | undefined, + ] + >; updateCalculatedMetric( - request: protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.ICalculatedMetric, + | protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCalculatedMetric( - request: protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.ICalculatedMetric, + | protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCalculatedMetric( - request?: protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.ICalculatedMetric, + | protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICalculatedMetric, + ( + | protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest + | 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({ - 'calculated_metric.name': request.calculatedMetric!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'calculated_metric.name': request.calculatedMetric!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateCalculatedMetric request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.ICalculatedMetric, + | protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateCalculatedMetric response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateCalculatedMetric(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.ICalculatedMetric, - protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateCalculatedMetric response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateCalculatedMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.ICalculatedMetric, + ( + | protos.google.analytics.admin.v1alpha.IUpdateCalculatedMetricRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateCalculatedMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a CalculatedMetric on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the CalculatedMetric to delete. - * Format: properties/{property_id}/calculatedMetrics/{calculated_metric_id} - * Example: properties/1234/calculatedMetrics/Metric01 - * @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/v1alpha/analytics_admin_service.delete_calculated_metric.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteCalculatedMetric_async - */ + /** + * Deletes a CalculatedMetric on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the CalculatedMetric to delete. + * Format: properties/{property_id}/calculatedMetrics/{calculated_metric_id} + * Example: properties/1234/calculatedMetrics/Metric01 + * @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/v1alpha/analytics_admin_service.delete_calculated_metric.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteCalculatedMetric_async + */ deleteCalculatedMetric( - request?: protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest + | undefined + ), + {} | undefined, + ] + >; deleteCalculatedMetric( - request: protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteCalculatedMetric( - request: protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteCalculatedMetric( - request?: protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest + | 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('deleteCalculatedMetric request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteCalculatedMetric response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteCalculatedMetric(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteCalculatedMetric response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteCalculatedMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteCalculatedMetricRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteCalculatedMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Create a roll-up property and all roll-up property source links. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.Property} request.rollupProperty - * Required. The roll-up property to create. - * @param {string[]} [request.sourceProperties] - * Optional. The resource names of properties that will be sources to the - * created roll-up property. - * @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.analytics.admin.v1alpha.CreateRollupPropertyResponse|CreateRollupPropertyResponse}. - * 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/v1alpha/analytics_admin_service.create_rollup_property.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateRollupProperty_async - */ + /** + * Create a roll-up property and all roll-up property source links. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.Property} request.rollupProperty + * Required. The roll-up property to create. + * @param {string[]} [request.sourceProperties] + * Optional. The resource names of properties that will be sources to the + * created roll-up property. + * @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.analytics.admin.v1alpha.CreateRollupPropertyResponse|CreateRollupPropertyResponse}. + * 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/v1alpha/analytics_admin_service.create_rollup_property.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateRollupProperty_async + */ createRollupProperty( - request?: protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ICreateRollupPropertyResponse, - protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICreateRollupPropertyResponse, + ( + | protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest + | undefined + ), + {} | undefined, + ] + >; createRollupProperty( - request: protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.ICreateRollupPropertyResponse, - protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.ICreateRollupPropertyResponse, + | protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createRollupProperty( - request: protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.ICreateRollupPropertyResponse, - protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.ICreateRollupPropertyResponse, + | protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createRollupProperty( - request?: protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.ICreateRollupPropertyResponse, - protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.ICreateRollupPropertyResponse, - protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.ICreateRollupPropertyResponse, - protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.ICreateRollupPropertyResponse, + | protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICreateRollupPropertyResponse, + ( + | protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest + | 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 || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createRollupProperty request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.ICreateRollupPropertyResponse, - protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.ICreateRollupPropertyResponse, + | protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createRollupProperty response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createRollupProperty(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.ICreateRollupPropertyResponse, - protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest|undefined, - {}|undefined - ]) => { - this._log.info('createRollupProperty response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createRollupProperty(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.ICreateRollupPropertyResponse, + ( + | protos.google.analytics.admin.v1alpha.ICreateRollupPropertyRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createRollupProperty response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for a single roll-up property source Link. - * Only roll-up properties can have source links, so this method will throw an - * error if used on other types of properties. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the roll-up property source link to lookup. - * Format: - * properties/{property_id}/rollupPropertySourceLinks/{rollup_property_source_link_id} - * Example: properties/123/rollupPropertySourceLinks/456 - * @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.analytics.admin.v1alpha.RollupPropertySourceLink|RollupPropertySourceLink}. - * 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/v1alpha/analytics_admin_service.get_rollup_property_source_link.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetRollupPropertySourceLink_async - */ + /** + * Lookup for a single roll-up property source Link. + * Only roll-up properties can have source links, so this method will throw an + * error if used on other types of properties. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the roll-up property source link to lookup. + * Format: + * properties/{property_id}/rollupPropertySourceLinks/{rollup_property_source_link_id} + * Example: properties/123/rollupPropertySourceLinks/456 + * @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.analytics.admin.v1alpha.RollupPropertySourceLink|RollupPropertySourceLink}. + * 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/v1alpha/analytics_admin_service.get_rollup_property_source_link.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetRollupPropertySourceLink_async + */ getRollupPropertySourceLink( - request?: protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, - protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, + ( + | protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest + | undefined + ), + {} | undefined, + ] + >; getRollupPropertySourceLink( - request: protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, - protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, + | protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getRollupPropertySourceLink( - request: protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, - protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, + | protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getRollupPropertySourceLink( - request?: protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, - protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, - protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, - protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, + | protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, + ( + | protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest + | 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('getRollupPropertySourceLink request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, - protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, + | protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getRollupPropertySourceLink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getRollupPropertySourceLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, - protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('getRollupPropertySourceLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getRollupPropertySourceLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, + ( + | protos.google.analytics.admin.v1alpha.IGetRollupPropertySourceLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getRollupPropertySourceLink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a roll-up property source link. - * Only roll-up properties can have source links, so this method will throw an - * error if used on other types of properties. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Format: properties/{property_id} - * Example: properties/1234 - * @param {google.analytics.admin.v1alpha.RollupPropertySourceLink} request.rollupPropertySourceLink - * Required. The roll-up property source link 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.analytics.admin.v1alpha.RollupPropertySourceLink|RollupPropertySourceLink}. - * 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/v1alpha/analytics_admin_service.create_rollup_property_source_link.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateRollupPropertySourceLink_async - */ + /** + * Creates a roll-up property source link. + * Only roll-up properties can have source links, so this method will throw an + * error if used on other types of properties. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Format: properties/{property_id} + * Example: properties/1234 + * @param {google.analytics.admin.v1alpha.RollupPropertySourceLink} request.rollupPropertySourceLink + * Required. The roll-up property source link 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.analytics.admin.v1alpha.RollupPropertySourceLink|RollupPropertySourceLink}. + * 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/v1alpha/analytics_admin_service.create_rollup_property_source_link.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateRollupPropertySourceLink_async + */ createRollupPropertySourceLink( - request?: protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, - protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, + ( + | protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest + | undefined + ), + {} | undefined, + ] + >; createRollupPropertySourceLink( - request: protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, - protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, + | protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createRollupPropertySourceLink( - request: protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, - protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, + | protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createRollupPropertySourceLink( - request?: protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, - protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, - protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, - protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, + | protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, + ( + | protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest + | 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('createRollupPropertySourceLink request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, - protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, + | protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('createRollupPropertySourceLink response %j', response); + this._log.info( + 'createRollupPropertySourceLink response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createRollupPropertySourceLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, - protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('createRollupPropertySourceLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createRollupPropertySourceLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink, + ( + | protos.google.analytics.admin.v1alpha.ICreateRollupPropertySourceLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'createRollupPropertySourceLink response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a roll-up property source link. - * Only roll-up properties can have source links, so this method will throw an - * error if used on other types of properties. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Format: - * properties/{property_id}/rollupPropertySourceLinks/{rollup_property_source_link_id} - * Example: properties/1234/rollupPropertySourceLinks/5678 - * @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/v1alpha/analytics_admin_service.delete_rollup_property_source_link.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteRollupPropertySourceLink_async - */ + /** + * Deletes a roll-up property source link. + * Only roll-up properties can have source links, so this method will throw an + * error if used on other types of properties. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Format: + * properties/{property_id}/rollupPropertySourceLinks/{rollup_property_source_link_id} + * Example: properties/1234/rollupPropertySourceLinks/5678 + * @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/v1alpha/analytics_admin_service.delete_rollup_property_source_link.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteRollupPropertySourceLink_async + */ deleteRollupPropertySourceLink( - request?: protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest + | undefined + ), + {} | undefined, + ] + >; deleteRollupPropertySourceLink( - request: protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteRollupPropertySourceLink( - request: protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteRollupPropertySourceLink( - request?: protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest + | 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('deleteRollupPropertySourceLink request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('deleteRollupPropertySourceLink response %j', response); + this._log.info( + 'deleteRollupPropertySourceLink response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteRollupPropertySourceLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteRollupPropertySourceLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteRollupPropertySourceLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteRollupPropertySourceLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'deleteRollupPropertySourceLink response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Create a subproperty and a subproperty event filter that applies to the - * created subproperty. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.Property} request.subproperty - * Required. The subproperty to create. - * @param {google.analytics.admin.v1alpha.SubpropertyEventFilter} [request.subpropertyEventFilter] - * Optional. The subproperty event filter to create on an ordinary property. - * @param {google.analytics.admin.v1alpha.SubpropertySyncConfig.SynchronizationMode} [request.customDimensionAndMetricSynchronizationMode] - * Optional. The subproperty feature synchronization mode for Custom - * Dimensions and Metrics - * @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.analytics.admin.v1alpha.ProvisionSubpropertyResponse|ProvisionSubpropertyResponse}. - * 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/v1alpha/analytics_admin_service.provision_subproperty.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ProvisionSubproperty_async - */ + /** + * Create a subproperty and a subproperty event filter that applies to the + * created subproperty. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.Property} request.subproperty + * Required. The subproperty to create. + * @param {google.analytics.admin.v1alpha.SubpropertyEventFilter} [request.subpropertyEventFilter] + * Optional. The subproperty event filter to create on an ordinary property. + * @param {google.analytics.admin.v1alpha.SubpropertySyncConfig.SynchronizationMode} [request.customDimensionAndMetricSynchronizationMode] + * Optional. The subproperty feature synchronization mode for Custom + * Dimensions and Metrics + * @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.analytics.admin.v1alpha.ProvisionSubpropertyResponse|ProvisionSubpropertyResponse}. + * 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/v1alpha/analytics_admin_service.provision_subproperty.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ProvisionSubproperty_async + */ provisionSubproperty( - request?: protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IProvisionSubpropertyResponse, - protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IProvisionSubpropertyResponse, + ( + | protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest + | undefined + ), + {} | undefined, + ] + >; provisionSubproperty( - request: protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IProvisionSubpropertyResponse, - protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IProvisionSubpropertyResponse, + | protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; provisionSubproperty( - request: protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IProvisionSubpropertyResponse, - protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IProvisionSubpropertyResponse, + | protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; provisionSubproperty( - request?: protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IProvisionSubpropertyResponse, - protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IProvisionSubpropertyResponse, - protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IProvisionSubpropertyResponse, - protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IProvisionSubpropertyResponse, + | protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IProvisionSubpropertyResponse, + ( + | protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest + | 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 || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('provisionSubproperty request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IProvisionSubpropertyResponse, - protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IProvisionSubpropertyResponse, + | protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('provisionSubproperty response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.provisionSubproperty(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IProvisionSubpropertyResponse, - protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest|undefined, - {}|undefined - ]) => { - this._log.info('provisionSubproperty response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .provisionSubproperty(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IProvisionSubpropertyResponse, + ( + | protos.google.analytics.admin.v1alpha.IProvisionSubpropertyRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('provisionSubproperty response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a subproperty Event Filter. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The ordinary property for which to create a subproperty event - * filter. Format: properties/property_id Example: properties/123 - * @param {google.analytics.admin.v1alpha.SubpropertyEventFilter} request.subpropertyEventFilter - * Required. The subproperty event filter 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.analytics.admin.v1alpha.SubpropertyEventFilter|SubpropertyEventFilter}. - * 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/v1alpha/analytics_admin_service.create_subproperty_event_filter.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateSubpropertyEventFilter_async - */ + /** + * Creates a subproperty Event Filter. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The ordinary property for which to create a subproperty event + * filter. Format: properties/property_id Example: properties/123 + * @param {google.analytics.admin.v1alpha.SubpropertyEventFilter} request.subpropertyEventFilter + * Required. The subproperty event filter 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.analytics.admin.v1alpha.SubpropertyEventFilter|SubpropertyEventFilter}. + * 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/v1alpha/analytics_admin_service.create_subproperty_event_filter.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateSubpropertyEventFilter_async + */ createSubpropertyEventFilter( - request?: protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, + ( + | protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest + | undefined + ), + {} | undefined, + ] + >; createSubpropertyEventFilter( - request: protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, + | protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createSubpropertyEventFilter( - request: protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, + | protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createSubpropertyEventFilter( - request?: protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, + | protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, + ( + | protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest + | 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('createSubpropertyEventFilter request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, + | protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createSubpropertyEventFilter response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createSubpropertyEventFilter(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest|undefined, - {}|undefined - ]) => { - this._log.info('createSubpropertyEventFilter response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createSubpropertyEventFilter(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, + ( + | protos.google.analytics.admin.v1alpha.ICreateSubpropertyEventFilterRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createSubpropertyEventFilter response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for a single subproperty Event Filter. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the subproperty event filter to lookup. - * Format: - * properties/property_id/subpropertyEventFilters/subproperty_event_filter - * Example: properties/123/subpropertyEventFilters/456 - * @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.analytics.admin.v1alpha.SubpropertyEventFilter|SubpropertyEventFilter}. - * 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/v1alpha/analytics_admin_service.get_subproperty_event_filter.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetSubpropertyEventFilter_async - */ + /** + * Lookup for a single subproperty Event Filter. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the subproperty event filter to lookup. + * Format: + * properties/property_id/subpropertyEventFilters/subproperty_event_filter + * Example: properties/123/subpropertyEventFilters/456 + * @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.analytics.admin.v1alpha.SubpropertyEventFilter|SubpropertyEventFilter}. + * 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/v1alpha/analytics_admin_service.get_subproperty_event_filter.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetSubpropertyEventFilter_async + */ getSubpropertyEventFilter( - request?: protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, + ( + | protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest + | undefined + ), + {} | undefined, + ] + >; getSubpropertyEventFilter( - request: protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, + | protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getSubpropertyEventFilter( - request: protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, + | protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getSubpropertyEventFilter( - request?: protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, + | protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, + ( + | protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest + | 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('getSubpropertyEventFilter request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, + | protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getSubpropertyEventFilter response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getSubpropertyEventFilter(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest|undefined, - {}|undefined - ]) => { - this._log.info('getSubpropertyEventFilter response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getSubpropertyEventFilter(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, + ( + | protos.google.analytics.admin.v1alpha.IGetSubpropertyEventFilterRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getSubpropertyEventFilter response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a subproperty Event Filter. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.SubpropertyEventFilter} request.subpropertyEventFilter - * Required. The subproperty event filter to update. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to update. Field names must be in snake case - * (for example, "field_to_update"). Omitted fields will not be updated. To - * replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1alpha.SubpropertyEventFilter|SubpropertyEventFilter}. - * 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/v1alpha/analytics_admin_service.update_subproperty_event_filter.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateSubpropertyEventFilter_async - */ + /** + * Updates a subproperty Event Filter. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.SubpropertyEventFilter} request.subpropertyEventFilter + * Required. The subproperty event filter to update. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to update. Field names must be in snake case + * (for example, "field_to_update"). Omitted fields will not be updated. To + * replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1alpha.SubpropertyEventFilter|SubpropertyEventFilter}. + * 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/v1alpha/analytics_admin_service.update_subproperty_event_filter.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateSubpropertyEventFilter_async + */ updateSubpropertyEventFilter( - request?: protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, + ( + | protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest + | undefined + ), + {} | undefined, + ] + >; updateSubpropertyEventFilter( - request: protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, + | protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateSubpropertyEventFilter( - request: protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, + | protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateSubpropertyEventFilter( - request?: protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, + | protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, + ( + | protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest + | 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({ - 'subproperty_event_filter.name': request.subpropertyEventFilter!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'subproperty_event_filter.name': + request.subpropertyEventFilter!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateSubpropertyEventFilter request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, + | protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateSubpropertyEventFilter response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateSubpropertyEventFilter(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, - protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateSubpropertyEventFilter response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateSubpropertyEventFilter(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter, + ( + | protos.google.analytics.admin.v1alpha.IUpdateSubpropertyEventFilterRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateSubpropertyEventFilter response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a subproperty event filter. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the subproperty event filter to delete. - * Format: - * properties/property_id/subpropertyEventFilters/subproperty_event_filter - * Example: properties/123/subpropertyEventFilters/456 - * @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/v1alpha/analytics_admin_service.delete_subproperty_event_filter.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteSubpropertyEventFilter_async - */ + /** + * Deletes a subproperty event filter. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the subproperty event filter to delete. + * Format: + * properties/property_id/subpropertyEventFilters/subproperty_event_filter + * Example: properties/123/subpropertyEventFilters/456 + * @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/v1alpha/analytics_admin_service.delete_subproperty_event_filter.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteSubpropertyEventFilter_async + */ deleteSubpropertyEventFilter( - request?: protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest + | undefined + ), + {} | undefined, + ] + >; deleteSubpropertyEventFilter( - request: protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteSubpropertyEventFilter( - request: protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteSubpropertyEventFilter( - request?: protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest + | 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('deleteSubpropertyEventFilter request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteSubpropertyEventFilter response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteSubpropertyEventFilter(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteSubpropertyEventFilter response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteSubpropertyEventFilter(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteSubpropertyEventFilterRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteSubpropertyEventFilter response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a Reporting Data Annotation. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The property for which to create a Reporting Data Annotation. - * Format: properties/property_id - * Example: properties/123 - * @param {google.analytics.admin.v1alpha.ReportingDataAnnotation} request.reportingDataAnnotation - * Required. The Reporting Data Annotation 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.analytics.admin.v1alpha.ReportingDataAnnotation|ReportingDataAnnotation}. - * 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/v1alpha/analytics_admin_service.create_reporting_data_annotation.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateReportingDataAnnotation_async - */ + /** + * Creates a Reporting Data Annotation. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The property for which to create a Reporting Data Annotation. + * Format: properties/property_id + * Example: properties/123 + * @param {google.analytics.admin.v1alpha.ReportingDataAnnotation} request.reportingDataAnnotation + * Required. The Reporting Data Annotation 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.analytics.admin.v1alpha.ReportingDataAnnotation|ReportingDataAnnotation}. + * 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/v1alpha/analytics_admin_service.create_reporting_data_annotation.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateReportingDataAnnotation_async + */ createReportingDataAnnotation( - request?: protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, + ( + | protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest + | undefined + ), + {} | undefined, + ] + >; createReportingDataAnnotation( - request: protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, + | protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createReportingDataAnnotation( - request: protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, + | protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createReportingDataAnnotation( - request?: protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, + | protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, + ( + | protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest + | 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('createReportingDataAnnotation request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, + | protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createReportingDataAnnotation response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createReportingDataAnnotation(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest|undefined, - {}|undefined - ]) => { - this._log.info('createReportingDataAnnotation response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createReportingDataAnnotation(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, + ( + | protos.google.analytics.admin.v1alpha.ICreateReportingDataAnnotationRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createReportingDataAnnotation response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup a single Reporting Data Annotation. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the Reporting Data Annotation to lookup. - * Format: - * properties/property_id/reportingDataAnnotations/reportingDataAnnotation - * Example: properties/123/reportingDataAnnotations/456 - * @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.analytics.admin.v1alpha.ReportingDataAnnotation|ReportingDataAnnotation}. - * 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/v1alpha/analytics_admin_service.get_reporting_data_annotation.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetReportingDataAnnotation_async - */ + /** + * Lookup a single Reporting Data Annotation. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the Reporting Data Annotation to lookup. + * Format: + * properties/property_id/reportingDataAnnotations/reportingDataAnnotation + * Example: properties/123/reportingDataAnnotations/456 + * @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.analytics.admin.v1alpha.ReportingDataAnnotation|ReportingDataAnnotation}. + * 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/v1alpha/analytics_admin_service.get_reporting_data_annotation.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetReportingDataAnnotation_async + */ getReportingDataAnnotation( - request?: protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, + ( + | protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest + | undefined + ), + {} | undefined, + ] + >; getReportingDataAnnotation( - request: protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, + | protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getReportingDataAnnotation( - request: protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, + | protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getReportingDataAnnotation( - request?: protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, + | protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, + ( + | protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest + | 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('getReportingDataAnnotation request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, + | protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getReportingDataAnnotation response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getReportingDataAnnotation(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest|undefined, - {}|undefined - ]) => { - this._log.info('getReportingDataAnnotation response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getReportingDataAnnotation(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, + ( + | protos.google.analytics.admin.v1alpha.IGetReportingDataAnnotationRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getReportingDataAnnotation response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a Reporting Data Annotation. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.ReportingDataAnnotation} request.reportingDataAnnotation - * Required. The Reporting Data Annotation to update. - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. The list of fields to update. Field names must be in snake case - * (for example, "field_to_update"). Omitted fields will not be updated. To - * replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1alpha.ReportingDataAnnotation|ReportingDataAnnotation}. - * 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/v1alpha/analytics_admin_service.update_reporting_data_annotation.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateReportingDataAnnotation_async - */ + /** + * Updates a Reporting Data Annotation. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.ReportingDataAnnotation} request.reportingDataAnnotation + * Required. The Reporting Data Annotation to update. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. The list of fields to update. Field names must be in snake case + * (for example, "field_to_update"). Omitted fields will not be updated. To + * replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1alpha.ReportingDataAnnotation|ReportingDataAnnotation}. + * 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/v1alpha/analytics_admin_service.update_reporting_data_annotation.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateReportingDataAnnotation_async + */ updateReportingDataAnnotation( - request?: protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, + ( + | protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest + | undefined + ), + {} | undefined, + ] + >; updateReportingDataAnnotation( - request: protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, + | protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateReportingDataAnnotation( - request: protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, + | protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateReportingDataAnnotation( - request?: protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, + | protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, + ( + | protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest + | 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({ - 'reporting_data_annotation.name': request.reportingDataAnnotation!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'reporting_data_annotation.name': + request.reportingDataAnnotation!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateReportingDataAnnotation request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, + | protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateReportingDataAnnotation response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateReportingDataAnnotation(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, - protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateReportingDataAnnotation response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateReportingDataAnnotation(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation, + ( + | protos.google.analytics.admin.v1alpha.IUpdateReportingDataAnnotationRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateReportingDataAnnotation response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a Reporting Data Annotation. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the Reporting Data Annotation to delete. - * Format: - * properties/property_id/reportingDataAnnotations/reporting_data_annotation - * Example: properties/123/reportingDataAnnotations/456 - * @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/v1alpha/analytics_admin_service.delete_reporting_data_annotation.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteReportingDataAnnotation_async - */ + /** + * Deletes a Reporting Data Annotation. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the Reporting Data Annotation to delete. + * Format: + * properties/property_id/reportingDataAnnotations/reporting_data_annotation + * Example: properties/123/reportingDataAnnotations/456 + * @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/v1alpha/analytics_admin_service.delete_reporting_data_annotation.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteReportingDataAnnotation_async + */ deleteReportingDataAnnotation( - request?: protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest + | undefined + ), + {} | undefined, + ] + >; deleteReportingDataAnnotation( - request: protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteReportingDataAnnotation( - request: protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteReportingDataAnnotation( - request?: protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest + | 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('deleteReportingDataAnnotation request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteReportingDataAnnotation response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteReportingDataAnnotation(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteReportingDataAnnotation response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteReportingDataAnnotation(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1alpha.IDeleteReportingDataAnnotationRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteReportingDataAnnotation response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Submits a request for user deletion for a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.userId - * Google Analytics [user - * ID](https://firebase.google.com/docs/analytics/userid). - * @param {string} request.clientId - * Google Analytics [client - * ID](https://support.google.com/analytics/answer/11593727). - * @param {string} request.appInstanceId - * Firebase [application instance - * ID](https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.html#getAppInstanceId). - * @param {string} request.userProvidedData - * [User-provided - * data](https://support.google.com/analytics/answer/14077171). May contain - * either one email address or one phone number. - * - * Email addresses should be normalized as such: - * - * * lowercase - * * remove periods before @ for gmail.com/googlemail.com addresses - * * remove all spaces - * - * Phone numbers should be normalized as such: - * - * * remove all non digit characters - * * add + prefix - * @param {string} request.name - * Required. The name of the property to submit user deletion for. - * @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.analytics.admin.v1alpha.SubmitUserDeletionResponse|SubmitUserDeletionResponse}. - * 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/v1alpha/analytics_admin_service.submit_user_deletion.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_SubmitUserDeletion_async - */ + /** + * Submits a request for user deletion for a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.userId + * Google Analytics [user + * ID](https://firebase.google.com/docs/analytics/userid). + * @param {string} request.clientId + * Google Analytics [client + * ID](https://support.google.com/analytics/answer/11593727). + * @param {string} request.appInstanceId + * Firebase [application instance + * ID](https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.html#getAppInstanceId). + * @param {string} request.userProvidedData + * [User-provided + * data](https://support.google.com/analytics/answer/14077171). May contain + * either one email address or one phone number. + * + * Email addresses should be normalized as such: + * + * * lowercase + * * remove periods before @ for gmail.com/googlemail.com addresses + * * remove all spaces + * + * Phone numbers should be normalized as such: + * + * * remove all non digit characters + * * add + prefix + * @param {string} request.name + * Required. The name of the property to submit user deletion for. + * @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.analytics.admin.v1alpha.SubmitUserDeletionResponse|SubmitUserDeletionResponse}. + * 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/v1alpha/analytics_admin_service.submit_user_deletion.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_SubmitUserDeletion_async + */ submitUserDeletion( - request?: protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ISubmitUserDeletionResponse, - protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISubmitUserDeletionResponse, + ( + | protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest + | undefined + ), + {} | undefined, + ] + >; submitUserDeletion( - request: protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISubmitUserDeletionResponse, - protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISubmitUserDeletionResponse, + | protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; submitUserDeletion( - request: protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISubmitUserDeletionResponse, - protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISubmitUserDeletionResponse, + | protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; submitUserDeletion( - request?: protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.ISubmitUserDeletionResponse, - protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.ISubmitUserDeletionResponse, - protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.ISubmitUserDeletionResponse, - protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.ISubmitUserDeletionResponse, + | protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISubmitUserDeletionResponse, + ( + | protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest + | 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('submitUserDeletion request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.ISubmitUserDeletionResponse, - protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.ISubmitUserDeletionResponse, + | protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('submitUserDeletion response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.submitUserDeletion(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.ISubmitUserDeletionResponse, - protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest|undefined, - {}|undefined - ]) => { - this._log.info('submitUserDeletion response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .submitUserDeletion(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.ISubmitUserDeletionResponse, + ( + | protos.google.analytics.admin.v1alpha.ISubmitUserDeletionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('submitUserDeletion response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a `SubpropertySyncConfig`. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1alpha.SubpropertySyncConfig} request.subpropertySyncConfig - * Required. The `SubpropertySyncConfig` to update. - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. The list of fields to update. Field names must be in snake case - * (for example, "field_to_update"). Omitted fields will not be updated. To - * replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1alpha.SubpropertySyncConfig|SubpropertySyncConfig}. - * 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/v1alpha/analytics_admin_service.update_subproperty_sync_config.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateSubpropertySyncConfig_async - */ + /** + * Updates a `SubpropertySyncConfig`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1alpha.SubpropertySyncConfig} request.subpropertySyncConfig + * Required. The `SubpropertySyncConfig` to update. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. The list of fields to update. Field names must be in snake case + * (for example, "field_to_update"). Omitted fields will not be updated. To + * replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1alpha.SubpropertySyncConfig|SubpropertySyncConfig}. + * 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/v1alpha/analytics_admin_service.update_subproperty_sync_config.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_UpdateSubpropertySyncConfig_async + */ updateSubpropertySyncConfig( - request?: protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, - protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, + ( + | protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest + | undefined + ), + {} | undefined, + ] + >; updateSubpropertySyncConfig( - request: protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, - protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, + | protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateSubpropertySyncConfig( - request: protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, - protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, + | protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateSubpropertySyncConfig( - request?: protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, - protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, - protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, - protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, + | protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, + ( + | protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest + | 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({ - 'subproperty_sync_config.name': request.subpropertySyncConfig!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'subproperty_sync_config.name': + request.subpropertySyncConfig!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateSubpropertySyncConfig request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, - protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, + | protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateSubpropertySyncConfig response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateSubpropertySyncConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, - protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateSubpropertySyncConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateSubpropertySyncConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, + ( + | protos.google.analytics.admin.v1alpha.IUpdateSubpropertySyncConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateSubpropertySyncConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for a single `SubpropertySyncConfig`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Resource name of the SubpropertySyncConfig to lookup. - * Format: - * properties/{ordinary_property_id}/subpropertySyncConfigs/{subproperty_id} - * Example: properties/1234/subpropertySyncConfigs/5678 - * @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.analytics.admin.v1alpha.SubpropertySyncConfig|SubpropertySyncConfig}. - * 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/v1alpha/analytics_admin_service.get_subproperty_sync_config.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetSubpropertySyncConfig_async - */ + /** + * Lookup for a single `SubpropertySyncConfig`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Resource name of the SubpropertySyncConfig to lookup. + * Format: + * properties/{ordinary_property_id}/subpropertySyncConfigs/{subproperty_id} + * Example: properties/1234/subpropertySyncConfigs/5678 + * @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.analytics.admin.v1alpha.SubpropertySyncConfig|SubpropertySyncConfig}. + * 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/v1alpha/analytics_admin_service.get_subproperty_sync_config.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetSubpropertySyncConfig_async + */ getSubpropertySyncConfig( - request?: protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, - protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, + ( + | protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest + | undefined + ), + {} | undefined, + ] + >; getSubpropertySyncConfig( - request: protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, - protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, + | protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getSubpropertySyncConfig( - request: protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, - protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, + | protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getSubpropertySyncConfig( - request?: protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, - protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, - protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, - protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, + | protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, + ( + | protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest + | 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('getSubpropertySyncConfig request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, - protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, + | protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getSubpropertySyncConfig response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getSubpropertySyncConfig(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, - protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest|undefined, - {}|undefined - ]) => { - this._log.info('getSubpropertySyncConfig response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getSubpropertySyncConfig(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig, + ( + | protos.google.analytics.admin.v1alpha.IGetSubpropertySyncConfigRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getSubpropertySyncConfig response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns the reporting identity settings for this property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the settings to lookup. - * Format: - * properties/{property}/reportingIdentitySettings - * Example: "properties/1000/reportingIdentitySettings" - * @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.analytics.admin.v1alpha.ReportingIdentitySettings|ReportingIdentitySettings}. - * 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/v1alpha/analytics_admin_service.get_reporting_identity_settings.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetReportingIdentitySettings_async - */ + /** + * Returns the reporting identity settings for this property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the settings to lookup. + * Format: + * properties/{property}/reportingIdentitySettings + * Example: "properties/1000/reportingIdentitySettings" + * @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.analytics.admin.v1alpha.ReportingIdentitySettings|ReportingIdentitySettings}. + * 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/v1alpha/analytics_admin_service.get_reporting_identity_settings.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetReportingIdentitySettings_async + */ getReportingIdentitySettings( - request?: protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IReportingIdentitySettings, - protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IReportingIdentitySettings, + ( + | protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest + | undefined + ), + {} | undefined, + ] + >; getReportingIdentitySettings( - request: protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IReportingIdentitySettings, - protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IReportingIdentitySettings, + | protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getReportingIdentitySettings( - request: protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IReportingIdentitySettings, - protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IReportingIdentitySettings, + | protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getReportingIdentitySettings( - request?: protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IReportingIdentitySettings, - protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IReportingIdentitySettings, - protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IReportingIdentitySettings, - protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IReportingIdentitySettings, + | protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IReportingIdentitySettings, + ( + | protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest + | 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('getReportingIdentitySettings request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IReportingIdentitySettings, - protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IReportingIdentitySettings, + | protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getReportingIdentitySettings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getReportingIdentitySettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IReportingIdentitySettings, - protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('getReportingIdentitySettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getReportingIdentitySettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IReportingIdentitySettings, + ( + | protos.google.analytics.admin.v1alpha.IGetReportingIdentitySettingsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getReportingIdentitySettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Looks up settings related to user-provided data for a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the user provided data settings to retrieve. - * Format: properties/{property}/userProvidedDataSettings - * @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.analytics.admin.v1alpha.UserProvidedDataSettings|UserProvidedDataSettings}. - * 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/v1alpha/analytics_admin_service.get_user_provided_data_settings.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetUserProvidedDataSettings_async - */ + /** + * Looks up settings related to user-provided data for a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the user provided data settings to retrieve. + * Format: properties/{property}/userProvidedDataSettings + * @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.analytics.admin.v1alpha.UserProvidedDataSettings|UserProvidedDataSettings}. + * 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/v1alpha/analytics_admin_service.get_user_provided_data_settings.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_GetUserProvidedDataSettings_async + */ getUserProvidedDataSettings( - request?: protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IUserProvidedDataSettings, - protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IUserProvidedDataSettings, + ( + | protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest + | undefined + ), + {} | undefined, + ] + >; getUserProvidedDataSettings( - request: protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1alpha.IUserProvidedDataSettings, - protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1alpha.IUserProvidedDataSettings, + | protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getUserProvidedDataSettings( - request: protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest, - callback: Callback< - protos.google.analytics.admin.v1alpha.IUserProvidedDataSettings, - protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest, + callback: Callback< + protos.google.analytics.admin.v1alpha.IUserProvidedDataSettings, + | protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getUserProvidedDataSettings( - request?: protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1alpha.IUserProvidedDataSettings, - protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1alpha.IUserProvidedDataSettings, - protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1alpha.IUserProvidedDataSettings, - protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1alpha.IUserProvidedDataSettings, + | protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IUserProvidedDataSettings, + ( + | protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest + | 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('getUserProvidedDataSettings request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1alpha.IUserProvidedDataSettings, - protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1alpha.IUserProvidedDataSettings, + | protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getUserProvidedDataSettings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getUserProvidedDataSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1alpha.IUserProvidedDataSettings, - protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('getUserProvidedDataSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getUserProvidedDataSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1alpha.IUserProvidedDataSettings, + ( + | protos.google.analytics.admin.v1alpha.IGetUserProvidedDataSettingsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getUserProvidedDataSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Returns all accounts accessible by the caller. - * - * Note that these accounts might not currently have GA properties. - * Soft-deleted (ie: "trashed") accounts are excluded by default. - * Returns an empty list if no relevant accounts are found. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListAccounts` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListAccounts` must - * match the call that provided the page token. - * @param {boolean} request.showDeleted - * Whether to include soft-deleted (ie: "trashed") Accounts in the - * results. Accounts can be inspected to determine whether they are deleted or - * not. - * @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.analytics.admin.v1alpha.Account|Account}. - * 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 `listAccountsAsync()` - * 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. - */ + /** + * Returns all accounts accessible by the caller. + * + * Note that these accounts might not currently have GA properties. + * Soft-deleted (ie: "trashed") accounts are excluded by default. + * Returns an empty list if no relevant accounts are found. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListAccounts` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListAccounts` must + * match the call that provided the page token. + * @param {boolean} request.showDeleted + * Whether to include soft-deleted (ie: "trashed") Accounts in the + * results. Accounts can be inspected to determine whether they are deleted or + * not. + * @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.analytics.admin.v1alpha.Account|Account}. + * 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 `listAccountsAsync()` + * 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. + */ listAccounts( - request?: protos.google.analytics.admin.v1alpha.IListAccountsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IAccount[], - protos.google.analytics.admin.v1alpha.IListAccountsRequest|null, - protos.google.analytics.admin.v1alpha.IListAccountsResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListAccountsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAccount[], + protos.google.analytics.admin.v1alpha.IListAccountsRequest | null, + protos.google.analytics.admin.v1alpha.IListAccountsResponse, + ] + >; listAccounts( - request: protos.google.analytics.admin.v1alpha.IListAccountsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListAccountsRequest, - protos.google.analytics.admin.v1alpha.IListAccountsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAccount>): void; + request: protos.google.analytics.admin.v1alpha.IListAccountsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListAccountsRequest, + | protos.google.analytics.admin.v1alpha.IListAccountsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAccount + >, + ): void; listAccounts( - request: protos.google.analytics.admin.v1alpha.IListAccountsRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListAccountsRequest, - protos.google.analytics.admin.v1alpha.IListAccountsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAccount>): void; + request: protos.google.analytics.admin.v1alpha.IListAccountsRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListAccountsRequest, + | protos.google.analytics.admin.v1alpha.IListAccountsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAccount + >, + ): void; listAccounts( - request?: protos.google.analytics.admin.v1alpha.IListAccountsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.admin.v1alpha.IListAccountsRequest, - protos.google.analytics.admin.v1alpha.IListAccountsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAccount>, - callback?: PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListAccountsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListAccountsRequest, - protos.google.analytics.admin.v1alpha.IListAccountsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAccount>): - Promise<[ - protos.google.analytics.admin.v1alpha.IAccount[], - protos.google.analytics.admin.v1alpha.IListAccountsRequest|null, - protos.google.analytics.admin.v1alpha.IListAccountsResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListAccountsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAccount + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListAccountsRequest, + | protos.google.analytics.admin.v1alpha.IListAccountsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAccount + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAccount[], + protos.google.analytics.admin.v1alpha.IListAccountsRequest | null, + protos.google.analytics.admin.v1alpha.IListAccountsResponse, + ] + > | 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 || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListAccountsRequest, - protos.google.analytics.admin.v1alpha.IListAccountsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAccount>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListAccountsRequest, + | protos.google.analytics.admin.v1alpha.IListAccountsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAccount + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listAccounts values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -12995,194 +19544,226 @@ export class AnalyticsAdminServiceClient { this._log.info('listAccounts request %j', request); return this.innerApiCalls .listAccounts(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.IAccount[], - protos.google.analytics.admin.v1alpha.IListAccountsRequest|null, - protos.google.analytics.admin.v1alpha.IListAccountsResponse - ]) => { - this._log.info('listAccounts values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.IAccount[], + protos.google.analytics.admin.v1alpha.IListAccountsRequest | null, + protos.google.analytics.admin.v1alpha.IListAccountsResponse, + ]) => { + this._log.info('listAccounts values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listAccounts`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListAccounts` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListAccounts` must - * match the call that provided the page token. - * @param {boolean} request.showDeleted - * Whether to include soft-deleted (ie: "trashed") Accounts in the - * results. Accounts can be inspected to determine whether they are deleted or - * not. - * @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.analytics.admin.v1alpha.Account|Account} 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 `listAccountsAsync()` - * 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 `listAccounts`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListAccounts` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListAccounts` must + * match the call that provided the page token. + * @param {boolean} request.showDeleted + * Whether to include soft-deleted (ie: "trashed") Accounts in the + * results. Accounts can be inspected to determine whether they are deleted or + * not. + * @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.analytics.admin.v1alpha.Account|Account} 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 `listAccountsAsync()` + * 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. + */ listAccountsStream( - request?: protos.google.analytics.admin.v1alpha.IListAccountsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListAccountsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listAccounts']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listAccounts stream %j', request); return this.descriptors.page.listAccounts.createStream( this.innerApiCalls.listAccounts as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listAccounts`, 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 {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListAccounts` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListAccounts` must - * match the call that provided the page token. - * @param {boolean} request.showDeleted - * Whether to include soft-deleted (ie: "trashed") Accounts in the - * results. Accounts can be inspected to determine whether they are deleted or - * not. - * @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.analytics.admin.v1alpha.Account|Account}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_accounts.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListAccounts_async - */ + /** + * Equivalent to `listAccounts`, 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 {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListAccounts` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListAccounts` must + * match the call that provided the page token. + * @param {boolean} request.showDeleted + * Whether to include soft-deleted (ie: "trashed") Accounts in the + * results. Accounts can be inspected to determine whether they are deleted or + * not. + * @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.analytics.admin.v1alpha.Account|Account}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_accounts.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListAccounts_async + */ listAccountsAsync( - request?: protos.google.analytics.admin.v1alpha.IListAccountsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListAccountsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listAccounts']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listAccounts iterate %j', request); return this.descriptors.page.listAccounts.asyncIterate( this.innerApiCalls['listAccounts'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Returns summaries of all accounts accessible by the caller. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of AccountSummary resources to return. The - * service may return fewer than this value, even if there are additional - * pages. If unspecified, at most 50 resources will be returned. The maximum - * value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListAccountSummaries` - * call. Provide this to retrieve the subsequent page. When paginating, all - * other parameters provided to `ListAccountSummaries` must match the call - * that provided the page token. - * @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.analytics.admin.v1alpha.AccountSummary|AccountSummary}. - * 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 `listAccountSummariesAsync()` - * 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. - */ + /** + * Returns summaries of all accounts accessible by the caller. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of AccountSummary resources to return. The + * service may return fewer than this value, even if there are additional + * pages. If unspecified, at most 50 resources will be returned. The maximum + * value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListAccountSummaries` + * call. Provide this to retrieve the subsequent page. When paginating, all + * other parameters provided to `ListAccountSummaries` must match the call + * that provided the page token. + * @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.analytics.admin.v1alpha.AccountSummary|AccountSummary}. + * 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 `listAccountSummariesAsync()` + * 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. + */ listAccountSummaries( - request?: protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IAccountSummary[], - protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest|null, - protos.google.analytics.admin.v1alpha.IListAccountSummariesResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAccountSummary[], + protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest | null, + protos.google.analytics.admin.v1alpha.IListAccountSummariesResponse, + ] + >; listAccountSummaries( - request: protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest, - protos.google.analytics.admin.v1alpha.IListAccountSummariesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAccountSummary>): void; + request: protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest, + | protos.google.analytics.admin.v1alpha.IListAccountSummariesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAccountSummary + >, + ): void; listAccountSummaries( - request: protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest, - protos.google.analytics.admin.v1alpha.IListAccountSummariesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAccountSummary>): void; + request: protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest, + | protos.google.analytics.admin.v1alpha.IListAccountSummariesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAccountSummary + >, + ): void; listAccountSummaries( - request?: protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest, - protos.google.analytics.admin.v1alpha.IListAccountSummariesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAccountSummary>, - callback?: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest, - protos.google.analytics.admin.v1alpha.IListAccountSummariesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAccountSummary>): - Promise<[ - protos.google.analytics.admin.v1alpha.IAccountSummary[], - protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest|null, - protos.google.analytics.admin.v1alpha.IListAccountSummariesResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListAccountSummariesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAccountSummary + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest, + | protos.google.analytics.admin.v1alpha.IListAccountSummariesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAccountSummary + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAccountSummary[], + protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest | null, + protos.google.analytics.admin.v1alpha.IListAccountSummariesResponse, + ] + > | 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 || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest, - protos.google.analytics.admin.v1alpha.IListAccountSummariesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAccountSummary>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest, + | protos.google.analytics.admin.v1alpha.IListAccountSummariesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAccountSummary + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listAccountSummaries values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -13191,211 +19772,243 @@ export class AnalyticsAdminServiceClient { this._log.info('listAccountSummaries request %j', request); return this.innerApiCalls .listAccountSummaries(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.IAccountSummary[], - protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest|null, - protos.google.analytics.admin.v1alpha.IListAccountSummariesResponse - ]) => { - this._log.info('listAccountSummaries values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.IAccountSummary[], + protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest | null, + protos.google.analytics.admin.v1alpha.IListAccountSummariesResponse, + ]) => { + this._log.info('listAccountSummaries values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listAccountSummaries`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} [request.pageSize] - * Optional. The maximum number of AccountSummary resources to return. The - * service may return fewer than this value, even if there are additional - * pages. If unspecified, at most 50 resources will be returned. The maximum - * value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListAccountSummaries` - * call. Provide this to retrieve the subsequent page. When paginating, all - * other parameters provided to `ListAccountSummaries` must match the call - * that provided the page token. - * @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.analytics.admin.v1alpha.AccountSummary|AccountSummary} 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 `listAccountSummariesAsync()` - * 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 `listAccountSummaries`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} [request.pageSize] + * Optional. The maximum number of AccountSummary resources to return. The + * service may return fewer than this value, even if there are additional + * pages. If unspecified, at most 50 resources will be returned. The maximum + * value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListAccountSummaries` + * call. Provide this to retrieve the subsequent page. When paginating, all + * other parameters provided to `ListAccountSummaries` must match the call + * that provided the page token. + * @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.analytics.admin.v1alpha.AccountSummary|AccountSummary} 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 `listAccountSummariesAsync()` + * 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. + */ listAccountSummariesStream( - request?: protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listAccountSummaries']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listAccountSummaries stream %j', request); return this.descriptors.page.listAccountSummaries.createStream( this.innerApiCalls.listAccountSummaries as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listAccountSummaries`, 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 {number} [request.pageSize] - * Optional. The maximum number of AccountSummary resources to return. The - * service may return fewer than this value, even if there are additional - * pages. If unspecified, at most 50 resources will be returned. The maximum - * value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListAccountSummaries` - * call. Provide this to retrieve the subsequent page. When paginating, all - * other parameters provided to `ListAccountSummaries` must match the call - * that provided the 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 protos.google.analytics.admin.v1alpha.AccountSummary|AccountSummary}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_account_summaries.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListAccountSummaries_async - */ + /** + * Equivalent to `listAccountSummaries`, 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 {number} [request.pageSize] + * Optional. The maximum number of AccountSummary resources to return. The + * service may return fewer than this value, even if there are additional + * pages. If unspecified, at most 50 resources will be returned. The maximum + * value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListAccountSummaries` + * call. Provide this to retrieve the subsequent page. When paginating, all + * other parameters provided to `ListAccountSummaries` must match the call + * that provided the 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 protos.google.analytics.admin.v1alpha.AccountSummary|AccountSummary}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_account_summaries.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListAccountSummaries_async + */ listAccountSummariesAsync( - request?: protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListAccountSummariesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listAccountSummaries']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listAccountSummaries iterate %j', request); return this.descriptors.page.listAccountSummaries.asyncIterate( this.innerApiCalls['listAccountSummaries'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Returns child Properties under the specified parent Account. - * - * Properties will be excluded if the caller does not have access. - * Soft-deleted (ie: "trashed") properties are excluded by default. - * Returns an empty list if no relevant properties are found. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.filter - * Required. An expression for filtering the results of the request. - * Fields eligible for filtering are: - * `parent:`(The resource name of the parent account/property) or - * `ancestor:`(The resource name of the parent account) or - * `firebase_project:`(The id or number of the linked firebase project). - * Some examples of filters: - * - * ``` - * | Filter | Description | - * |-----------------------------|-------------------------------------------| - * | parent:accounts/123 | The account with account id: 123. | - * | parent:properties/123 | The property with property id: 123. | - * | ancestor:accounts/123 | The account with account id: 123. | - * | firebase_project:project-id | The firebase project with id: project-id. | - * | firebase_project:123 | The firebase project with number: 123. | - * ``` - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListProperties` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListProperties` must - * match the call that provided the page token. - * @param {boolean} request.showDeleted - * Whether to include soft-deleted (ie: "trashed") Properties in the - * results. Properties can be inspected to determine whether they are deleted - * or not. - * @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.analytics.admin.v1alpha.Property|Property}. - * 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 `listPropertiesAsync()` - * 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. - */ + /** + * Returns child Properties under the specified parent Account. + * + * Properties will be excluded if the caller does not have access. + * Soft-deleted (ie: "trashed") properties are excluded by default. + * Returns an empty list if no relevant properties are found. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * Required. An expression for filtering the results of the request. + * Fields eligible for filtering are: + * `parent:`(The resource name of the parent account/property) or + * `ancestor:`(The resource name of the parent account) or + * `firebase_project:`(The id or number of the linked firebase project). + * Some examples of filters: + * + * ``` + * | Filter | Description | + * |-----------------------------|-------------------------------------------| + * | parent:accounts/123 | The account with account id: 123. | + * | parent:properties/123 | The property with property id: 123. | + * | ancestor:accounts/123 | The account with account id: 123. | + * | firebase_project:project-id | The firebase project with id: project-id. | + * | firebase_project:123 | The firebase project with number: 123. | + * ``` + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListProperties` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListProperties` must + * match the call that provided the page token. + * @param {boolean} request.showDeleted + * Whether to include soft-deleted (ie: "trashed") Properties in the + * results. Properties can be inspected to determine whether they are deleted + * or not. + * @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.analytics.admin.v1alpha.Property|Property}. + * 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 `listPropertiesAsync()` + * 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. + */ listProperties( - request?: protos.google.analytics.admin.v1alpha.IListPropertiesRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IProperty[], - protos.google.analytics.admin.v1alpha.IListPropertiesRequest|null, - protos.google.analytics.admin.v1alpha.IListPropertiesResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListPropertiesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IProperty[], + protos.google.analytics.admin.v1alpha.IListPropertiesRequest | null, + protos.google.analytics.admin.v1alpha.IListPropertiesResponse, + ] + >; listProperties( - request: protos.google.analytics.admin.v1alpha.IListPropertiesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListPropertiesRequest, - protos.google.analytics.admin.v1alpha.IListPropertiesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IProperty>): void; + request: protos.google.analytics.admin.v1alpha.IListPropertiesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListPropertiesRequest, + | protos.google.analytics.admin.v1alpha.IListPropertiesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IProperty + >, + ): void; listProperties( - request: protos.google.analytics.admin.v1alpha.IListPropertiesRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListPropertiesRequest, - protos.google.analytics.admin.v1alpha.IListPropertiesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IProperty>): void; + request: protos.google.analytics.admin.v1alpha.IListPropertiesRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListPropertiesRequest, + | protos.google.analytics.admin.v1alpha.IListPropertiesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IProperty + >, + ): void; listProperties( - request?: protos.google.analytics.admin.v1alpha.IListPropertiesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.admin.v1alpha.IListPropertiesRequest, - protos.google.analytics.admin.v1alpha.IListPropertiesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IProperty>, - callback?: PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListPropertiesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListPropertiesRequest, - protos.google.analytics.admin.v1alpha.IListPropertiesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IProperty>): - Promise<[ - protos.google.analytics.admin.v1alpha.IProperty[], - protos.google.analytics.admin.v1alpha.IListPropertiesRequest|null, - protos.google.analytics.admin.v1alpha.IListPropertiesResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListPropertiesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IProperty + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListPropertiesRequest, + | protos.google.analytics.admin.v1alpha.IListPropertiesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IProperty + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IProperty[], + protos.google.analytics.admin.v1alpha.IListPropertiesRequest | null, + protos.google.analytics.admin.v1alpha.IListPropertiesResponse, + ] + > | 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 || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListPropertiesRequest, - protos.google.analytics.admin.v1alpha.IListPropertiesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IProperty>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListPropertiesRequest, + | protos.google.analytics.admin.v1alpha.IListPropertiesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IProperty + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listProperties values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -13404,238 +20017,269 @@ export class AnalyticsAdminServiceClient { this._log.info('listProperties request %j', request); return this.innerApiCalls .listProperties(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.IProperty[], - protos.google.analytics.admin.v1alpha.IListPropertiesRequest|null, - protos.google.analytics.admin.v1alpha.IListPropertiesResponse - ]) => { - this._log.info('listProperties values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.IProperty[], + protos.google.analytics.admin.v1alpha.IListPropertiesRequest | null, + protos.google.analytics.admin.v1alpha.IListPropertiesResponse, + ]) => { + this._log.info('listProperties values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listProperties`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.filter - * Required. An expression for filtering the results of the request. - * Fields eligible for filtering are: - * `parent:`(The resource name of the parent account/property) or - * `ancestor:`(The resource name of the parent account) or - * `firebase_project:`(The id or number of the linked firebase project). - * Some examples of filters: - * - * ``` - * | Filter | Description | - * |-----------------------------|-------------------------------------------| - * | parent:accounts/123 | The account with account id: 123. | - * | parent:properties/123 | The property with property id: 123. | - * | ancestor:accounts/123 | The account with account id: 123. | - * | firebase_project:project-id | The firebase project with id: project-id. | - * | firebase_project:123 | The firebase project with number: 123. | - * ``` - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListProperties` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListProperties` must - * match the call that provided the page token. - * @param {boolean} request.showDeleted - * Whether to include soft-deleted (ie: "trashed") Properties in the - * results. Properties can be inspected to determine whether they are deleted - * or not. - * @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.analytics.admin.v1alpha.Property|Property} 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 `listPropertiesAsync()` - * 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 `listProperties`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * Required. An expression for filtering the results of the request. + * Fields eligible for filtering are: + * `parent:`(The resource name of the parent account/property) or + * `ancestor:`(The resource name of the parent account) or + * `firebase_project:`(The id or number of the linked firebase project). + * Some examples of filters: + * + * ``` + * | Filter | Description | + * |-----------------------------|-------------------------------------------| + * | parent:accounts/123 | The account with account id: 123. | + * | parent:properties/123 | The property with property id: 123. | + * | ancestor:accounts/123 | The account with account id: 123. | + * | firebase_project:project-id | The firebase project with id: project-id. | + * | firebase_project:123 | The firebase project with number: 123. | + * ``` + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListProperties` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListProperties` must + * match the call that provided the page token. + * @param {boolean} request.showDeleted + * Whether to include soft-deleted (ie: "trashed") Properties in the + * results. Properties can be inspected to determine whether they are deleted + * or not. + * @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.analytics.admin.v1alpha.Property|Property} 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 `listPropertiesAsync()` + * 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. + */ listPropertiesStream( - request?: protos.google.analytics.admin.v1alpha.IListPropertiesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListPropertiesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listProperties']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listProperties stream %j', request); return this.descriptors.page.listProperties.createStream( this.innerApiCalls.listProperties as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listProperties`, 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.filter - * Required. An expression for filtering the results of the request. - * Fields eligible for filtering are: - * `parent:`(The resource name of the parent account/property) or - * `ancestor:`(The resource name of the parent account) or - * `firebase_project:`(The id or number of the linked firebase project). - * Some examples of filters: - * - * ``` - * | Filter | Description | - * |-----------------------------|-------------------------------------------| - * | parent:accounts/123 | The account with account id: 123. | - * | parent:properties/123 | The property with property id: 123. | - * | ancestor:accounts/123 | The account with account id: 123. | - * | firebase_project:project-id | The firebase project with id: project-id. | - * | firebase_project:123 | The firebase project with number: 123. | - * ``` - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListProperties` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListProperties` must - * match the call that provided the page token. - * @param {boolean} request.showDeleted - * Whether to include soft-deleted (ie: "trashed") Properties in the - * results. Properties can be inspected to determine whether they are deleted - * or not. - * @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.analytics.admin.v1alpha.Property|Property}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_properties.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListProperties_async - */ + /** + * Equivalent to `listProperties`, 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.filter + * Required. An expression for filtering the results of the request. + * Fields eligible for filtering are: + * `parent:`(The resource name of the parent account/property) or + * `ancestor:`(The resource name of the parent account) or + * `firebase_project:`(The id or number of the linked firebase project). + * Some examples of filters: + * + * ``` + * | Filter | Description | + * |-----------------------------|-------------------------------------------| + * | parent:accounts/123 | The account with account id: 123. | + * | parent:properties/123 | The property with property id: 123. | + * | ancestor:accounts/123 | The account with account id: 123. | + * | firebase_project:project-id | The firebase project with id: project-id. | + * | firebase_project:123 | The firebase project with number: 123. | + * ``` + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListProperties` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListProperties` must + * match the call that provided the page token. + * @param {boolean} request.showDeleted + * Whether to include soft-deleted (ie: "trashed") Properties in the + * results. Properties can be inspected to determine whether they are deleted + * or not. + * @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.analytics.admin.v1alpha.Property|Property}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_properties.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListProperties_async + */ listPropertiesAsync( - request?: protos.google.analytics.admin.v1alpha.IListPropertiesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListPropertiesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listProperties']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listProperties iterate %j', request); return this.descriptors.page.listProperties.asyncIterate( this.innerApiCalls['listProperties'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists FirebaseLinks on a property. - * Properties can have at most one FirebaseLink. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Format: properties/{property_id} - * - * Example: `properties/1234` - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListFirebaseLinks` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListFirebaseLinks` must - * match the call that provided the page token. - * @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.analytics.admin.v1alpha.FirebaseLink|FirebaseLink}. - * 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 `listFirebaseLinksAsync()` - * 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 FirebaseLinks on a property. + * Properties can have at most one FirebaseLink. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Format: properties/{property_id} + * + * Example: `properties/1234` + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListFirebaseLinks` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListFirebaseLinks` must + * match the call that provided the page token. + * @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.analytics.admin.v1alpha.FirebaseLink|FirebaseLink}. + * 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 `listFirebaseLinksAsync()` + * 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. + */ listFirebaseLinks( - request?: protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IFirebaseLink[], - protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest|null, - protos.google.analytics.admin.v1alpha.IListFirebaseLinksResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IFirebaseLink[], + protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest | null, + protos.google.analytics.admin.v1alpha.IListFirebaseLinksResponse, + ] + >; listFirebaseLinks( - request: protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest, - protos.google.analytics.admin.v1alpha.IListFirebaseLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IFirebaseLink>): void; + request: protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest, + | protos.google.analytics.admin.v1alpha.IListFirebaseLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IFirebaseLink + >, + ): void; listFirebaseLinks( - request: protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest, - protos.google.analytics.admin.v1alpha.IListFirebaseLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IFirebaseLink>): void; + request: protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest, + | protos.google.analytics.admin.v1alpha.IListFirebaseLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IFirebaseLink + >, + ): void; listFirebaseLinks( - request?: protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest, - protos.google.analytics.admin.v1alpha.IListFirebaseLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IFirebaseLink>, - callback?: PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest, - protos.google.analytics.admin.v1alpha.IListFirebaseLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IFirebaseLink>): - Promise<[ - protos.google.analytics.admin.v1alpha.IFirebaseLink[], - protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest|null, - protos.google.analytics.admin.v1alpha.IListFirebaseLinksResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListFirebaseLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IFirebaseLink + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest, + | protos.google.analytics.admin.v1alpha.IListFirebaseLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IFirebaseLink + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IFirebaseLink[], + protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest | null, + protos.google.analytics.admin.v1alpha.IListFirebaseLinksResponse, + ] + > | 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.analytics.admin.v1alpha.IListFirebaseLinksRequest, - protos.google.analytics.admin.v1alpha.IListFirebaseLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IFirebaseLink>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest, + | protos.google.analytics.admin.v1alpha.IListFirebaseLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IFirebaseLink + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listFirebaseLinks values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -13644,211 +20288,240 @@ export class AnalyticsAdminServiceClient { this._log.info('listFirebaseLinks request %j', request); return this.innerApiCalls .listFirebaseLinks(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.IFirebaseLink[], - protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest|null, - protos.google.analytics.admin.v1alpha.IListFirebaseLinksResponse - ]) => { - this._log.info('listFirebaseLinks values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.IFirebaseLink[], + protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest | null, + protos.google.analytics.admin.v1alpha.IListFirebaseLinksResponse, + ]) => { + this._log.info('listFirebaseLinks values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listFirebaseLinks`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Format: properties/{property_id} - * - * Example: `properties/1234` - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListFirebaseLinks` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListFirebaseLinks` must - * match the call that provided the page token. - * @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.analytics.admin.v1alpha.FirebaseLink|FirebaseLink} 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 `listFirebaseLinksAsync()` - * 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 `listFirebaseLinks`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Format: properties/{property_id} + * + * Example: `properties/1234` + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListFirebaseLinks` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListFirebaseLinks` must + * match the call that provided the page token. + * @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.analytics.admin.v1alpha.FirebaseLink|FirebaseLink} 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 `listFirebaseLinksAsync()` + * 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. + */ listFirebaseLinksStream( - request?: protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest, + 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['listFirebaseLinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listFirebaseLinks stream %j', request); return this.descriptors.page.listFirebaseLinks.createStream( this.innerApiCalls.listFirebaseLinks as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listFirebaseLinks`, 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. Format: properties/{property_id} - * - * Example: `properties/1234` - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListFirebaseLinks` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListFirebaseLinks` must - * match the call that provided the 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 protos.google.analytics.admin.v1alpha.FirebaseLink|FirebaseLink}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_firebase_links.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListFirebaseLinks_async - */ + /** + * Equivalent to `listFirebaseLinks`, 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. Format: properties/{property_id} + * + * Example: `properties/1234` + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListFirebaseLinks` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListFirebaseLinks` must + * match the call that provided the 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 protos.google.analytics.admin.v1alpha.FirebaseLink|FirebaseLink}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_firebase_links.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListFirebaseLinks_async + */ listFirebaseLinksAsync( - request?: protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListFirebaseLinksRequest, + 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['listFirebaseLinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listFirebaseLinks iterate %j', request); return this.descriptors.page.listFirebaseLinks.asyncIterate( this.innerApiCalls['listFirebaseLinks'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists GoogleAdsLinks on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListGoogleAdsLinks` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListGoogleAdsLinks` must - * match the call that provided the page token. - * @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.analytics.admin.v1alpha.GoogleAdsLink|GoogleAdsLink}. - * 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 `listGoogleAdsLinksAsync()` - * 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 GoogleAdsLinks on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListGoogleAdsLinks` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListGoogleAdsLinks` must + * match the call that provided the page token. + * @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.analytics.admin.v1alpha.GoogleAdsLink|GoogleAdsLink}. + * 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 `listGoogleAdsLinksAsync()` + * 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. + */ listGoogleAdsLinks( - request?: protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IGoogleAdsLink[], - protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest|null, - protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IGoogleAdsLink[], + protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest | null, + protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksResponse, + ] + >; listGoogleAdsLinks( - request: protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest, - protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IGoogleAdsLink>): void; + request: protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest, + | protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IGoogleAdsLink + >, + ): void; listGoogleAdsLinks( - request: protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest, - protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IGoogleAdsLink>): void; + request: protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest, + | protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IGoogleAdsLink + >, + ): void; listGoogleAdsLinks( - request?: protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest, - protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IGoogleAdsLink>, - callback?: PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest, - protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IGoogleAdsLink>): - Promise<[ - protos.google.analytics.admin.v1alpha.IGoogleAdsLink[], - protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest|null, - protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IGoogleAdsLink + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest, + | protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IGoogleAdsLink + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IGoogleAdsLink[], + protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest | null, + protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksResponse, + ] + > | 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.analytics.admin.v1alpha.IListGoogleAdsLinksRequest, - protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IGoogleAdsLink>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest, + | protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IGoogleAdsLink + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listGoogleAdsLinks values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -13857,210 +20530,239 @@ export class AnalyticsAdminServiceClient { this._log.info('listGoogleAdsLinks request %j', request); return this.innerApiCalls .listGoogleAdsLinks(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.IGoogleAdsLink[], - protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest|null, - protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksResponse - ]) => { - this._log.info('listGoogleAdsLinks values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.IGoogleAdsLink[], + protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest | null, + protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksResponse, + ]) => { + this._log.info('listGoogleAdsLinks values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listGoogleAdsLinks`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListGoogleAdsLinks` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListGoogleAdsLinks` must - * match the call that provided the page token. - * @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.analytics.admin.v1alpha.GoogleAdsLink|GoogleAdsLink} 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 `listGoogleAdsLinksAsync()` - * 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 `listGoogleAdsLinks`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListGoogleAdsLinks` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListGoogleAdsLinks` must + * match the call that provided the page token. + * @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.analytics.admin.v1alpha.GoogleAdsLink|GoogleAdsLink} 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 `listGoogleAdsLinksAsync()` + * 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. + */ listGoogleAdsLinksStream( - request?: protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest, + 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['listGoogleAdsLinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listGoogleAdsLinks stream %j', request); return this.descriptors.page.listGoogleAdsLinks.createStream( this.innerApiCalls.listGoogleAdsLinks as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listGoogleAdsLinks`, 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. Example format: properties/1234 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListGoogleAdsLinks` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListGoogleAdsLinks` must - * match the call that provided the 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 protos.google.analytics.admin.v1alpha.GoogleAdsLink|GoogleAdsLink}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_google_ads_links.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListGoogleAdsLinks_async - */ + /** + * Equivalent to `listGoogleAdsLinks`, 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. Example format: properties/1234 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListGoogleAdsLinks` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListGoogleAdsLinks` must + * match the call that provided the 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 protos.google.analytics.admin.v1alpha.GoogleAdsLink|GoogleAdsLink}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_google_ads_links.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListGoogleAdsLinks_async + */ listGoogleAdsLinksAsync( - request?: protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListGoogleAdsLinksRequest, + 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['listGoogleAdsLinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listGoogleAdsLinks iterate %j', request); return this.descriptors.page.listGoogleAdsLinks.asyncIterate( this.innerApiCalls['listGoogleAdsLinks'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Returns child MeasurementProtocolSecrets under the specified parent - * Property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the parent stream. - * Format: - * properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. - * If unspecified, at most 10 resources will be returned. - * The maximum value is 10. Higher values will be coerced to the maximum. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListMeasurementProtocolSecrets` call. Provide this to retrieve the - * subsequent page. When paginating, all other parameters provided to - * `ListMeasurementProtocolSecrets` must match the call that provided the page - * token. - * @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.analytics.admin.v1alpha.MeasurementProtocolSecret|MeasurementProtocolSecret}. - * 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 `listMeasurementProtocolSecretsAsync()` - * 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. - */ + /** + * Returns child MeasurementProtocolSecrets under the specified parent + * Property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the parent stream. + * Format: + * properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. + * If unspecified, at most 10 resources will be returned. + * The maximum value is 10. Higher values will be coerced to the maximum. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListMeasurementProtocolSecrets` call. Provide this to retrieve the + * subsequent page. When paginating, all other parameters provided to + * `ListMeasurementProtocolSecrets` must match the call that provided the page + * token. + * @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.analytics.admin.v1alpha.MeasurementProtocolSecret|MeasurementProtocolSecret}. + * 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 `listMeasurementProtocolSecretsAsync()` + * 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. + */ listMeasurementProtocolSecrets( - request?: protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret[], - protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest|null, - protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret[], + protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest | null, + protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsResponse, + ] + >; listMeasurementProtocolSecrets( - request: protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest, - protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret>): void; + request: protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest, + | protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret + >, + ): void; listMeasurementProtocolSecrets( - request: protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest, - protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret>): void; + request: protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest, + | protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret + >, + ): void; listMeasurementProtocolSecrets( - request?: protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest, - protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret>, - callback?: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest, - protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret>): - Promise<[ - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret[], - protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest|null, - protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest, + | protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret[], + protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest | null, + protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsResponse, + ] + > | 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.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest, - protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest, + | protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listMeasurementProtocolSecrets values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -14069,465 +20771,533 @@ export class AnalyticsAdminServiceClient { this._log.info('listMeasurementProtocolSecrets request %j', request); return this.innerApiCalls .listMeasurementProtocolSecrets(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret[], - protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest|null, - protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsResponse - ]) => { - this._log.info('listMeasurementProtocolSecrets values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret[], + protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest | null, + protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsResponse, + ]) => { + this._log.info('listMeasurementProtocolSecrets values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listMeasurementProtocolSecrets`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the parent stream. - * Format: - * properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. - * If unspecified, at most 10 resources will be returned. - * The maximum value is 10. Higher values will be coerced to the maximum. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListMeasurementProtocolSecrets` call. Provide this to retrieve the - * subsequent page. When paginating, all other parameters provided to - * `ListMeasurementProtocolSecrets` must match the call that provided the page - * token. - * @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.analytics.admin.v1alpha.MeasurementProtocolSecret|MeasurementProtocolSecret} 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 `listMeasurementProtocolSecretsAsync()` - * 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 `listMeasurementProtocolSecrets`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the parent stream. + * Format: + * properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. + * If unspecified, at most 10 resources will be returned. + * The maximum value is 10. Higher values will be coerced to the maximum. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListMeasurementProtocolSecrets` call. Provide this to retrieve the + * subsequent page. When paginating, all other parameters provided to + * `ListMeasurementProtocolSecrets` must match the call that provided the page + * token. + * @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.analytics.admin.v1alpha.MeasurementProtocolSecret|MeasurementProtocolSecret} 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 `listMeasurementProtocolSecretsAsync()` + * 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. + */ listMeasurementProtocolSecretsStream( - request?: protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest, + 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 ?? '', - }); - const defaultCallSettings = this._defaults['listMeasurementProtocolSecrets']; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = + this._defaults['listMeasurementProtocolSecrets']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listMeasurementProtocolSecrets stream %j', request); return this.descriptors.page.listMeasurementProtocolSecrets.createStream( this.innerApiCalls.listMeasurementProtocolSecrets as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listMeasurementProtocolSecrets`, 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 resource name of the parent stream. - * Format: - * properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. - * If unspecified, at most 10 resources will be returned. - * The maximum value is 10. Higher values will be coerced to the maximum. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListMeasurementProtocolSecrets` call. Provide this to retrieve the - * subsequent page. When paginating, all other parameters provided to - * `ListMeasurementProtocolSecrets` must match the call that provided the 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 protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret|MeasurementProtocolSecret}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_measurement_protocol_secrets.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListMeasurementProtocolSecrets_async - */ + /** + * Equivalent to `listMeasurementProtocolSecrets`, 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 resource name of the parent stream. + * Format: + * properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. + * If unspecified, at most 10 resources will be returned. + * The maximum value is 10. Higher values will be coerced to the maximum. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListMeasurementProtocolSecrets` call. Provide this to retrieve the + * subsequent page. When paginating, all other parameters provided to + * `ListMeasurementProtocolSecrets` must match the call that provided the 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 protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret|MeasurementProtocolSecret}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_measurement_protocol_secrets.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListMeasurementProtocolSecrets_async + */ listMeasurementProtocolSecretsAsync( - request?: protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListMeasurementProtocolSecretsRequest, + 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 ?? '', - }); - const defaultCallSettings = this._defaults['listMeasurementProtocolSecrets']; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = + this._defaults['listMeasurementProtocolSecrets']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listMeasurementProtocolSecrets iterate %j', request); return this.descriptors.page.listMeasurementProtocolSecrets.asyncIterate( this.innerApiCalls['listMeasurementProtocolSecrets'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists SKAdNetworkConversionValueSchema on a stream. - * Properties can have at most one SKAdNetworkConversionValueSchema. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The DataStream resource to list schemas for. - * Format: - * properties/{property_id}/dataStreams/{dataStream} - * Example: properties/1234/dataStreams/5678 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListSKAdNetworkConversionValueSchemas` call. Provide this to retrieve the - * subsequent page. When paginating, all other parameters provided to - * `ListSKAdNetworkConversionValueSchema` must match the call that provided - * the page token. - * @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.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema|SKAdNetworkConversionValueSchema}. - * 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 `listSKAdNetworkConversionValueSchemasAsync()` - * 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 SKAdNetworkConversionValueSchema on a stream. + * Properties can have at most one SKAdNetworkConversionValueSchema. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The DataStream resource to list schemas for. + * Format: + * properties/{property_id}/dataStreams/{dataStream} + * Example: properties/1234/dataStreams/5678 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListSKAdNetworkConversionValueSchemas` call. Provide this to retrieve the + * subsequent page. When paginating, all other parameters provided to + * `ListSKAdNetworkConversionValueSchema` must match the call that provided + * the page token. + * @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.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema|SKAdNetworkConversionValueSchema}. + * 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 `listSKAdNetworkConversionValueSchemasAsync()` + * 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. + */ listSKAdNetworkConversionValueSchemas( - request?: protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema[], - protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest|null, - protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema[], + protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest | null, + protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasResponse, + ] + >; listSKAdNetworkConversionValueSchemas( - request: protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest, - protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema>): void; + request: protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest, + | protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema + >, + ): void; listSKAdNetworkConversionValueSchemas( - request: protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest, - protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema>): void; + request: protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest, + | protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema + >, + ): void; listSKAdNetworkConversionValueSchemas( - request?: protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest, - protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema>, - callback?: PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest, - protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema>): - Promise<[ - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema[], - protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest|null, - protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest, + | protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema[], + protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest | null, + protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasResponse, + ] + > | 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.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest, - protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest, + | protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { - this._log.info('listSKAdNetworkConversionValueSchemas values %j', values); + this._log.info( + 'listSKAdNetworkConversionValueSchemas values %j', + values, + ); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. } : undefined; this._log.info('listSKAdNetworkConversionValueSchemas request %j', request); return this.innerApiCalls .listSkAdNetworkConversionValueSchemas(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema[], - protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest|null, - protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasResponse - ]) => { - this._log.info('listSKAdNetworkConversionValueSchemas values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema[], + protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest | null, + protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasResponse, + ]) => { + this._log.info( + 'listSKAdNetworkConversionValueSchemas values %j', + response, + ); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listSKAdNetworkConversionValueSchemas`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The DataStream resource to list schemas for. - * Format: - * properties/{property_id}/dataStreams/{dataStream} - * Example: properties/1234/dataStreams/5678 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListSKAdNetworkConversionValueSchemas` call. Provide this to retrieve the - * subsequent page. When paginating, all other parameters provided to - * `ListSKAdNetworkConversionValueSchema` must match the call that provided - * the page token. - * @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.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema|SKAdNetworkConversionValueSchema} 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 `listSKAdNetworkConversionValueSchemasAsync()` - * 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 `listSKAdNetworkConversionValueSchemas`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The DataStream resource to list schemas for. + * Format: + * properties/{property_id}/dataStreams/{dataStream} + * Example: properties/1234/dataStreams/5678 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListSKAdNetworkConversionValueSchemas` call. Provide this to retrieve the + * subsequent page. When paginating, all other parameters provided to + * `ListSKAdNetworkConversionValueSchema` must match the call that provided + * the page token. + * @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.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema|SKAdNetworkConversionValueSchema} 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 `listSKAdNetworkConversionValueSchemasAsync()` + * 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. + */ listSKAdNetworkConversionValueSchemasStream( - request?: protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest, + 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 ?? '', - }); - const defaultCallSettings = this._defaults['listSkAdNetworkConversionValueSchemas']; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = + this._defaults['listSkAdNetworkConversionValueSchemas']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listSKAdNetworkConversionValueSchemas stream %j', request); return this.descriptors.page.listSKAdNetworkConversionValueSchemas.createStream( this.innerApiCalls.listSkAdNetworkConversionValueSchemas as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listSKAdNetworkConversionValueSchemas`, 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 DataStream resource to list schemas for. - * Format: - * properties/{property_id}/dataStreams/{dataStream} - * Example: properties/1234/dataStreams/5678 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListSKAdNetworkConversionValueSchemas` call. Provide this to retrieve the - * subsequent page. When paginating, all other parameters provided to - * `ListSKAdNetworkConversionValueSchema` must match the call that provided - * the 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 protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema|SKAdNetworkConversionValueSchema}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_s_k_ad_network_conversion_value_schemas.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListSKAdNetworkConversionValueSchemas_async - */ + /** + * Equivalent to `listSKAdNetworkConversionValueSchemas`, 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 DataStream resource to list schemas for. + * Format: + * properties/{property_id}/dataStreams/{dataStream} + * Example: properties/1234/dataStreams/5678 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListSKAdNetworkConversionValueSchemas` call. Provide this to retrieve the + * subsequent page. When paginating, all other parameters provided to + * `ListSKAdNetworkConversionValueSchema` must match the call that provided + * the 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 protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema|SKAdNetworkConversionValueSchema}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_s_k_ad_network_conversion_value_schemas.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListSKAdNetworkConversionValueSchemas_async + */ listSKAdNetworkConversionValueSchemasAsync( - request?: protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListSKAdNetworkConversionValueSchemasRequest, + 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 ?? '', - }); - const defaultCallSettings = this._defaults['listSkAdNetworkConversionValueSchemas']; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = + this._defaults['listSkAdNetworkConversionValueSchemas']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listSKAdNetworkConversionValueSchemas iterate %j', request); return this.descriptors.page.listSKAdNetworkConversionValueSchemas.asyncIterate( this.innerApiCalls['listSkAdNetworkConversionValueSchemas'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Searches through all changes to an account or its children given the - * specified set of filters. - * - * Only returns the subset of changes supported by the API. The UI may return - * additional changes. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.account - * Required. The account resource for which to return change history - * resources. Format: accounts/{account} - * - * Example: `accounts/100` - * @param {string} [request.property] - * Optional. Resource name for a child property. If set, only return changes - * made to this property or its child resources. - * Format: properties/{propertyId} - * - * Example: `properties/100` - * @param {number[]} [request.resourceType] - * Optional. If set, only return changes if they are for a resource that - * matches at least one of these types. - * @param {number[]} [request.action] - * Optional. If set, only return changes that match one or more of these types - * of actions. - * @param {string[]} [request.actorEmail] - * Optional. If set, only return changes if they are made by a user in this - * list. - * @param {google.protobuf.Timestamp} [request.earliestChangeTime] - * Optional. If set, only return changes made after this time (inclusive). - * @param {google.protobuf.Timestamp} [request.latestChangeTime] - * Optional. If set, only return changes made before this time (inclusive). - * @param {number} [request.pageSize] - * Optional. The maximum number of ChangeHistoryEvent items to return. - * If unspecified, at most 50 items will be returned. The maximum value is 200 - * (higher values will be coerced to the maximum). - * - * Note that the service may return a page with fewer items than this value - * specifies (potentially even zero), and that there still may be additional - * pages. If you want a particular number of items, you'll need to continue - * requesting additional pages using `page_token` until you get the needed - * number. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `SearchChangeHistoryEvents` call. Provide this to retrieve the subsequent - * page. When paginating, all other parameters provided to - * `SearchChangeHistoryEvents` must match the call that provided the page - * token. - * @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.analytics.admin.v1alpha.ChangeHistoryEvent|ChangeHistoryEvent}. - * 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 `searchChangeHistoryEventsAsync()` - * 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. - */ + /** + * Searches through all changes to an account or its children given the + * specified set of filters. + * + * Only returns the subset of changes supported by the API. The UI may return + * additional changes. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.account + * Required. The account resource for which to return change history + * resources. Format: accounts/{account} + * + * Example: `accounts/100` + * @param {string} [request.property] + * Optional. Resource name for a child property. If set, only return changes + * made to this property or its child resources. + * Format: properties/{propertyId} + * + * Example: `properties/100` + * @param {number[]} [request.resourceType] + * Optional. If set, only return changes if they are for a resource that + * matches at least one of these types. + * @param {number[]} [request.action] + * Optional. If set, only return changes that match one or more of these types + * of actions. + * @param {string[]} [request.actorEmail] + * Optional. If set, only return changes if they are made by a user in this + * list. + * @param {google.protobuf.Timestamp} [request.earliestChangeTime] + * Optional. If set, only return changes made after this time (inclusive). + * @param {google.protobuf.Timestamp} [request.latestChangeTime] + * Optional. If set, only return changes made before this time (inclusive). + * @param {number} [request.pageSize] + * Optional. The maximum number of ChangeHistoryEvent items to return. + * If unspecified, at most 50 items will be returned. The maximum value is 200 + * (higher values will be coerced to the maximum). + * + * Note that the service may return a page with fewer items than this value + * specifies (potentially even zero), and that there still may be additional + * pages. If you want a particular number of items, you'll need to continue + * requesting additional pages using `page_token` until you get the needed + * number. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `SearchChangeHistoryEvents` call. Provide this to retrieve the subsequent + * page. When paginating, all other parameters provided to + * `SearchChangeHistoryEvents` must match the call that provided the page + * token. + * @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.analytics.admin.v1alpha.ChangeHistoryEvent|ChangeHistoryEvent}. + * 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 `searchChangeHistoryEventsAsync()` + * 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. + */ searchChangeHistoryEvents( - request?: protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IChangeHistoryEvent[], - protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest|null, - protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IChangeHistoryEvent[], + protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest | null, + protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsResponse, + ] + >; searchChangeHistoryEvents( - request: protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest, - protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IChangeHistoryEvent>): void; + request: protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest, + | protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IChangeHistoryEvent + >, + ): void; searchChangeHistoryEvents( - request: protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest, - protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IChangeHistoryEvent>): void; + request: protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest, + | protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IChangeHistoryEvent + >, + ): void; searchChangeHistoryEvents( - request?: protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest, - protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IChangeHistoryEvent>, - callback?: PaginationCallback< - protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest, - protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IChangeHistoryEvent>): - Promise<[ - protos.google.analytics.admin.v1alpha.IChangeHistoryEvent[], - protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest|null, - protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IChangeHistoryEvent + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest, + | protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IChangeHistoryEvent + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IChangeHistoryEvent[], + protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest | null, + protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsResponse, + ] + > | 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({ - 'account': request.account ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + account: request.account ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest, - protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IChangeHistoryEvent>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest, + | protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IChangeHistoryEvent + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('searchChangeHistoryEvents values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -14536,268 +21306,301 @@ export class AnalyticsAdminServiceClient { this._log.info('searchChangeHistoryEvents request %j', request); return this.innerApiCalls .searchChangeHistoryEvents(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.IChangeHistoryEvent[], - protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest|null, - protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsResponse - ]) => { - this._log.info('searchChangeHistoryEvents values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.IChangeHistoryEvent[], + protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest | null, + protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsResponse, + ]) => { + this._log.info('searchChangeHistoryEvents values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `searchChangeHistoryEvents`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.account - * Required. The account resource for which to return change history - * resources. Format: accounts/{account} - * - * Example: `accounts/100` - * @param {string} [request.property] - * Optional. Resource name for a child property. If set, only return changes - * made to this property or its child resources. - * Format: properties/{propertyId} - * - * Example: `properties/100` - * @param {number[]} [request.resourceType] - * Optional. If set, only return changes if they are for a resource that - * matches at least one of these types. - * @param {number[]} [request.action] - * Optional. If set, only return changes that match one or more of these types - * of actions. - * @param {string[]} [request.actorEmail] - * Optional. If set, only return changes if they are made by a user in this - * list. - * @param {google.protobuf.Timestamp} [request.earliestChangeTime] - * Optional. If set, only return changes made after this time (inclusive). - * @param {google.protobuf.Timestamp} [request.latestChangeTime] - * Optional. If set, only return changes made before this time (inclusive). - * @param {number} [request.pageSize] - * Optional. The maximum number of ChangeHistoryEvent items to return. - * If unspecified, at most 50 items will be returned. The maximum value is 200 - * (higher values will be coerced to the maximum). - * - * Note that the service may return a page with fewer items than this value - * specifies (potentially even zero), and that there still may be additional - * pages. If you want a particular number of items, you'll need to continue - * requesting additional pages using `page_token` until you get the needed - * number. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `SearchChangeHistoryEvents` call. Provide this to retrieve the subsequent - * page. When paginating, all other parameters provided to - * `SearchChangeHistoryEvents` must match the call that provided the page - * token. - * @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.analytics.admin.v1alpha.ChangeHistoryEvent|ChangeHistoryEvent} 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 `searchChangeHistoryEventsAsync()` - * 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 `searchChangeHistoryEvents`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.account + * Required. The account resource for which to return change history + * resources. Format: accounts/{account} + * + * Example: `accounts/100` + * @param {string} [request.property] + * Optional. Resource name for a child property. If set, only return changes + * made to this property or its child resources. + * Format: properties/{propertyId} + * + * Example: `properties/100` + * @param {number[]} [request.resourceType] + * Optional. If set, only return changes if they are for a resource that + * matches at least one of these types. + * @param {number[]} [request.action] + * Optional. If set, only return changes that match one or more of these types + * of actions. + * @param {string[]} [request.actorEmail] + * Optional. If set, only return changes if they are made by a user in this + * list. + * @param {google.protobuf.Timestamp} [request.earliestChangeTime] + * Optional. If set, only return changes made after this time (inclusive). + * @param {google.protobuf.Timestamp} [request.latestChangeTime] + * Optional. If set, only return changes made before this time (inclusive). + * @param {number} [request.pageSize] + * Optional. The maximum number of ChangeHistoryEvent items to return. + * If unspecified, at most 50 items will be returned. The maximum value is 200 + * (higher values will be coerced to the maximum). + * + * Note that the service may return a page with fewer items than this value + * specifies (potentially even zero), and that there still may be additional + * pages. If you want a particular number of items, you'll need to continue + * requesting additional pages using `page_token` until you get the needed + * number. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `SearchChangeHistoryEvents` call. Provide this to retrieve the subsequent + * page. When paginating, all other parameters provided to + * `SearchChangeHistoryEvents` must match the call that provided the page + * token. + * @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.analytics.admin.v1alpha.ChangeHistoryEvent|ChangeHistoryEvent} 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 `searchChangeHistoryEventsAsync()` + * 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. + */ searchChangeHistoryEventsStream( - request?: protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest, + 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({ - 'account': request.account ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + account: request.account ?? '', + }); const defaultCallSettings = this._defaults['searchChangeHistoryEvents']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('searchChangeHistoryEvents stream %j', request); return this.descriptors.page.searchChangeHistoryEvents.createStream( this.innerApiCalls.searchChangeHistoryEvents as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `searchChangeHistoryEvents`, 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.account - * Required. The account resource for which to return change history - * resources. Format: accounts/{account} - * - * Example: `accounts/100` - * @param {string} [request.property] - * Optional. Resource name for a child property. If set, only return changes - * made to this property or its child resources. - * Format: properties/{propertyId} - * - * Example: `properties/100` - * @param {number[]} [request.resourceType] - * Optional. If set, only return changes if they are for a resource that - * matches at least one of these types. - * @param {number[]} [request.action] - * Optional. If set, only return changes that match one or more of these types - * of actions. - * @param {string[]} [request.actorEmail] - * Optional. If set, only return changes if they are made by a user in this - * list. - * @param {google.protobuf.Timestamp} [request.earliestChangeTime] - * Optional. If set, only return changes made after this time (inclusive). - * @param {google.protobuf.Timestamp} [request.latestChangeTime] - * Optional. If set, only return changes made before this time (inclusive). - * @param {number} [request.pageSize] - * Optional. The maximum number of ChangeHistoryEvent items to return. - * If unspecified, at most 50 items will be returned. The maximum value is 200 - * (higher values will be coerced to the maximum). - * - * Note that the service may return a page with fewer items than this value - * specifies (potentially even zero), and that there still may be additional - * pages. If you want a particular number of items, you'll need to continue - * requesting additional pages using `page_token` until you get the needed - * number. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `SearchChangeHistoryEvents` call. Provide this to retrieve the subsequent - * page. When paginating, all other parameters provided to - * `SearchChangeHistoryEvents` must match the call that provided the 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 protos.google.analytics.admin.v1alpha.ChangeHistoryEvent|ChangeHistoryEvent}. 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 include:samples/generated/v1alpha/analytics_admin_service.search_change_history_events.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_SearchChangeHistoryEvents_async - */ + /** + * Equivalent to `searchChangeHistoryEvents`, 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.account + * Required. The account resource for which to return change history + * resources. Format: accounts/{account} + * + * Example: `accounts/100` + * @param {string} [request.property] + * Optional. Resource name for a child property. If set, only return changes + * made to this property or its child resources. + * Format: properties/{propertyId} + * + * Example: `properties/100` + * @param {number[]} [request.resourceType] + * Optional. If set, only return changes if they are for a resource that + * matches at least one of these types. + * @param {number[]} [request.action] + * Optional. If set, only return changes that match one or more of these types + * of actions. + * @param {string[]} [request.actorEmail] + * Optional. If set, only return changes if they are made by a user in this + * list. + * @param {google.protobuf.Timestamp} [request.earliestChangeTime] + * Optional. If set, only return changes made after this time (inclusive). + * @param {google.protobuf.Timestamp} [request.latestChangeTime] + * Optional. If set, only return changes made before this time (inclusive). + * @param {number} [request.pageSize] + * Optional. The maximum number of ChangeHistoryEvent items to return. + * If unspecified, at most 50 items will be returned. The maximum value is 200 + * (higher values will be coerced to the maximum). + * + * Note that the service may return a page with fewer items than this value + * specifies (potentially even zero), and that there still may be additional + * pages. If you want a particular number of items, you'll need to continue + * requesting additional pages using `page_token` until you get the needed + * number. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `SearchChangeHistoryEvents` call. Provide this to retrieve the subsequent + * page. When paginating, all other parameters provided to + * `SearchChangeHistoryEvents` must match the call that provided the 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 protos.google.analytics.admin.v1alpha.ChangeHistoryEvent|ChangeHistoryEvent}. 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 include:samples/generated/v1alpha/analytics_admin_service.search_change_history_events.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_SearchChangeHistoryEvents_async + */ searchChangeHistoryEventsAsync( - request?: protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.ISearchChangeHistoryEventsRequest, + 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({ - 'account': request.account ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + account: request.account ?? '', + }); const defaultCallSettings = this._defaults['searchChangeHistoryEvents']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('searchChangeHistoryEvents iterate %j', request); return this.descriptors.page.searchChangeHistoryEvents.asyncIterate( this.innerApiCalls['searchChangeHistoryEvents'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Deprecated: Use `ListKeyEvents` instead. - * Returns a list of conversion events in the specified parent property. - * - * Returns an empty list if no conversion events are found. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the parent property. - * Example: 'properties/123' - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListConversionEvents` - * call. Provide this to retrieve the subsequent page. When paginating, all - * other parameters provided to `ListConversionEvents` must match the call - * that provided the page token. - * @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.analytics.admin.v1alpha.ConversionEvent|ConversionEvent}. - * 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 `listConversionEventsAsync()` - * 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. - * @deprecated ListConversionEvents is deprecated and may be removed in a future version. - */ + /** + * Deprecated: Use `ListKeyEvents` instead. + * Returns a list of conversion events in the specified parent property. + * + * Returns an empty list if no conversion events are found. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the parent property. + * Example: 'properties/123' + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListConversionEvents` + * call. Provide this to retrieve the subsequent page. When paginating, all + * other parameters provided to `ListConversionEvents` must match the call + * that provided the page token. + * @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.analytics.admin.v1alpha.ConversionEvent|ConversionEvent}. + * 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 `listConversionEventsAsync()` + * 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. + * @deprecated ListConversionEvents is deprecated and may be removed in a future version. + */ listConversionEvents( - request?: protos.google.analytics.admin.v1alpha.IListConversionEventsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IConversionEvent[], - protos.google.analytics.admin.v1alpha.IListConversionEventsRequest|null, - protos.google.analytics.admin.v1alpha.IListConversionEventsResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListConversionEventsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IConversionEvent[], + protos.google.analytics.admin.v1alpha.IListConversionEventsRequest | null, + protos.google.analytics.admin.v1alpha.IListConversionEventsResponse, + ] + >; listConversionEvents( - request: protos.google.analytics.admin.v1alpha.IListConversionEventsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListConversionEventsRequest, - protos.google.analytics.admin.v1alpha.IListConversionEventsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IConversionEvent>): void; + request: protos.google.analytics.admin.v1alpha.IListConversionEventsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListConversionEventsRequest, + | protos.google.analytics.admin.v1alpha.IListConversionEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IConversionEvent + >, + ): void; listConversionEvents( - request: protos.google.analytics.admin.v1alpha.IListConversionEventsRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListConversionEventsRequest, - protos.google.analytics.admin.v1alpha.IListConversionEventsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IConversionEvent>): void; + request: protos.google.analytics.admin.v1alpha.IListConversionEventsRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListConversionEventsRequest, + | protos.google.analytics.admin.v1alpha.IListConversionEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IConversionEvent + >, + ): void; listConversionEvents( - request?: protos.google.analytics.admin.v1alpha.IListConversionEventsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListConversionEventsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListConversionEventsRequest, - protos.google.analytics.admin.v1alpha.IListConversionEventsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IConversionEvent>, - callback?: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListConversionEventsRequest, - protos.google.analytics.admin.v1alpha.IListConversionEventsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IConversionEvent>): - Promise<[ - protos.google.analytics.admin.v1alpha.IConversionEvent[], - protos.google.analytics.admin.v1alpha.IListConversionEventsRequest|null, - protos.google.analytics.admin.v1alpha.IListConversionEventsResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListConversionEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IConversionEvent + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListConversionEventsRequest, + | protos.google.analytics.admin.v1alpha.IListConversionEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IConversionEvent + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IConversionEvent[], + protos.google.analytics.admin.v1alpha.IListConversionEventsRequest | null, + protos.google.analytics.admin.v1alpha.IListConversionEventsResponse, + ] + > | 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.warn('DEP$AnalyticsAdminService-$ListConversionEvents','ListConversionEvents is deprecated and may be removed in a future version.', 'DeprecationWarning'); - const wrappedCallback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListConversionEventsRequest, - protos.google.analytics.admin.v1alpha.IListConversionEventsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IConversionEvent>|undefined = callback + this.warn( + 'DEP$AnalyticsAdminService-$ListConversionEvents', + 'ListConversionEvents is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListConversionEventsRequest, + | protos.google.analytics.admin.v1alpha.IListConversionEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IConversionEvent + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listConversionEvents values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -14806,212 +21609,249 @@ export class AnalyticsAdminServiceClient { this._log.info('listConversionEvents request %j', request); return this.innerApiCalls .listConversionEvents(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.IConversionEvent[], - protos.google.analytics.admin.v1alpha.IListConversionEventsRequest|null, - protos.google.analytics.admin.v1alpha.IListConversionEventsResponse - ]) => { - this._log.info('listConversionEvents values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.IConversionEvent[], + protos.google.analytics.admin.v1alpha.IListConversionEventsRequest | null, + protos.google.analytics.admin.v1alpha.IListConversionEventsResponse, + ]) => { + this._log.info('listConversionEvents values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listConversionEvents`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the parent property. - * Example: 'properties/123' - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListConversionEvents` - * call. Provide this to retrieve the subsequent page. When paginating, all - * other parameters provided to `ListConversionEvents` must match the call - * that provided the page token. - * @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.analytics.admin.v1alpha.ConversionEvent|ConversionEvent} 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 `listConversionEventsAsync()` - * 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. - * @deprecated ListConversionEvents is deprecated and may be removed in a future version. - */ + /** + * Equivalent to `listConversionEvents`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the parent property. + * Example: 'properties/123' + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListConversionEvents` + * call. Provide this to retrieve the subsequent page. When paginating, all + * other parameters provided to `ListConversionEvents` must match the call + * that provided the page token. + * @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.analytics.admin.v1alpha.ConversionEvent|ConversionEvent} 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 `listConversionEventsAsync()` + * 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. + * @deprecated ListConversionEvents is deprecated and may be removed in a future version. + */ listConversionEventsStream( - request?: protos.google.analytics.admin.v1alpha.IListConversionEventsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListConversionEventsRequest, + 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['listConversionEvents']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); - this.warn('DEP$AnalyticsAdminService-$ListConversionEvents','ListConversionEvents is deprecated and may be removed in a future version.', 'DeprecationWarning'); + this.initialize().catch((err) => { + throw err; + }); + this.warn( + 'DEP$AnalyticsAdminService-$ListConversionEvents', + 'ListConversionEvents is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); this._log.info('listConversionEvents stream %j', request); return this.descriptors.page.listConversionEvents.createStream( this.innerApiCalls.listConversionEvents as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listConversionEvents`, 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 resource name of the parent property. - * Example: 'properties/123' - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListConversionEvents` - * call. Provide this to retrieve the subsequent page. When paginating, all - * other parameters provided to `ListConversionEvents` must match the call - * that provided the 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 protos.google.analytics.admin.v1alpha.ConversionEvent|ConversionEvent}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_conversion_events.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListConversionEvents_async - * @deprecated ListConversionEvents is deprecated and may be removed in a future version. - */ + /** + * Equivalent to `listConversionEvents`, 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 resource name of the parent property. + * Example: 'properties/123' + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListConversionEvents` + * call. Provide this to retrieve the subsequent page. When paginating, all + * other parameters provided to `ListConversionEvents` must match the call + * that provided the 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 protos.google.analytics.admin.v1alpha.ConversionEvent|ConversionEvent}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_conversion_events.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListConversionEvents_async + * @deprecated ListConversionEvents is deprecated and may be removed in a future version. + */ listConversionEventsAsync( - request?: protos.google.analytics.admin.v1alpha.IListConversionEventsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListConversionEventsRequest, + 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['listConversionEvents']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); - this.warn('DEP$AnalyticsAdminService-$ListConversionEvents','ListConversionEvents is deprecated and may be removed in a future version.', 'DeprecationWarning'); + this.initialize().catch((err) => { + throw err; + }); + this.warn( + 'DEP$AnalyticsAdminService-$ListConversionEvents', + 'ListConversionEvents is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); this._log.info('listConversionEvents iterate %j', request); return this.descriptors.page.listConversionEvents.asyncIterate( this.innerApiCalls['listConversionEvents'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Returns a list of Key Events in the specified parent property. - * Returns an empty list if no Key Events are found. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the parent property. - * Example: 'properties/123' - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListKeyEvents` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListKeyEvents` - * must match the call that provided the page token. - * @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.analytics.admin.v1alpha.KeyEvent|KeyEvent}. - * 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 `listKeyEventsAsync()` - * 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. - */ + /** + * Returns a list of Key Events in the specified parent property. + * Returns an empty list if no Key Events are found. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the parent property. + * Example: 'properties/123' + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListKeyEvents` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListKeyEvents` + * must match the call that provided the page token. + * @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.analytics.admin.v1alpha.KeyEvent|KeyEvent}. + * 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 `listKeyEventsAsync()` + * 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. + */ listKeyEvents( - request?: protos.google.analytics.admin.v1alpha.IListKeyEventsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IKeyEvent[], - protos.google.analytics.admin.v1alpha.IListKeyEventsRequest|null, - protos.google.analytics.admin.v1alpha.IListKeyEventsResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListKeyEventsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IKeyEvent[], + protos.google.analytics.admin.v1alpha.IListKeyEventsRequest | null, + protos.google.analytics.admin.v1alpha.IListKeyEventsResponse, + ] + >; listKeyEvents( - request: protos.google.analytics.admin.v1alpha.IListKeyEventsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListKeyEventsRequest, - protos.google.analytics.admin.v1alpha.IListKeyEventsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IKeyEvent>): void; + request: protos.google.analytics.admin.v1alpha.IListKeyEventsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListKeyEventsRequest, + | protos.google.analytics.admin.v1alpha.IListKeyEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IKeyEvent + >, + ): void; listKeyEvents( - request: protos.google.analytics.admin.v1alpha.IListKeyEventsRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListKeyEventsRequest, - protos.google.analytics.admin.v1alpha.IListKeyEventsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IKeyEvent>): void; + request: protos.google.analytics.admin.v1alpha.IListKeyEventsRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListKeyEventsRequest, + | protos.google.analytics.admin.v1alpha.IListKeyEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IKeyEvent + >, + ): void; listKeyEvents( - request?: protos.google.analytics.admin.v1alpha.IListKeyEventsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListKeyEventsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListKeyEventsRequest, - protos.google.analytics.admin.v1alpha.IListKeyEventsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IKeyEvent>, - callback?: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListKeyEventsRequest, - protos.google.analytics.admin.v1alpha.IListKeyEventsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IKeyEvent>): - Promise<[ - protos.google.analytics.admin.v1alpha.IKeyEvent[], - protos.google.analytics.admin.v1alpha.IListKeyEventsRequest|null, - protos.google.analytics.admin.v1alpha.IListKeyEventsResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListKeyEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IKeyEvent + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListKeyEventsRequest, + | protos.google.analytics.admin.v1alpha.IListKeyEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IKeyEvent + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IKeyEvent[], + protos.google.analytics.admin.v1alpha.IListKeyEventsRequest | null, + protos.google.analytics.admin.v1alpha.IListKeyEventsResponse, + ] + > | 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.analytics.admin.v1alpha.IListKeyEventsRequest, - protos.google.analytics.admin.v1alpha.IListKeyEventsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IKeyEvent>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListKeyEventsRequest, + | protos.google.analytics.admin.v1alpha.IListKeyEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IKeyEvent + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listKeyEvents values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -15020,634 +21860,752 @@ export class AnalyticsAdminServiceClient { this._log.info('listKeyEvents request %j', request); return this.innerApiCalls .listKeyEvents(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.IKeyEvent[], - protos.google.analytics.admin.v1alpha.IListKeyEventsRequest|null, - protos.google.analytics.admin.v1alpha.IListKeyEventsResponse - ]) => { - this._log.info('listKeyEvents values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.IKeyEvent[], + protos.google.analytics.admin.v1alpha.IListKeyEventsRequest | null, + protos.google.analytics.admin.v1alpha.IListKeyEventsResponse, + ]) => { + this._log.info('listKeyEvents values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listKeyEvents`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the parent property. - * Example: 'properties/123' - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListKeyEvents` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListKeyEvents` - * must match the call that provided the page token. - * @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.analytics.admin.v1alpha.KeyEvent|KeyEvent} 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 `listKeyEventsAsync()` - * 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 `listKeyEvents`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the parent property. + * Example: 'properties/123' + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListKeyEvents` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListKeyEvents` + * must match the call that provided the page token. + * @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.analytics.admin.v1alpha.KeyEvent|KeyEvent} 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 `listKeyEventsAsync()` + * 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. + */ listKeyEventsStream( - request?: protos.google.analytics.admin.v1alpha.IListKeyEventsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListKeyEventsRequest, + 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['listKeyEvents']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listKeyEvents stream %j', request); return this.descriptors.page.listKeyEvents.createStream( this.innerApiCalls.listKeyEvents as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listKeyEvents`, 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 resource name of the parent property. - * Example: 'properties/123' - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListKeyEvents` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListKeyEvents` - * must match the call that provided the 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 protos.google.analytics.admin.v1alpha.KeyEvent|KeyEvent}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_key_events.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListKeyEvents_async - */ + /** + * Equivalent to `listKeyEvents`, 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 resource name of the parent property. + * Example: 'properties/123' + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListKeyEvents` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListKeyEvents` + * must match the call that provided the 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 protos.google.analytics.admin.v1alpha.KeyEvent|KeyEvent}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_key_events.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListKeyEvents_async + */ listKeyEventsAsync( - request?: protos.google.analytics.admin.v1alpha.IListKeyEventsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListKeyEventsRequest, + 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['listKeyEvents']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listKeyEvents iterate %j', request); return this.descriptors.page.listKeyEvents.asyncIterate( this.innerApiCalls['listKeyEvents'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists all DisplayVideo360AdvertiserLinks on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListDisplayVideo360AdvertiserLinks` - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * `ListDisplayVideo360AdvertiserLinks` must match the call that provided the - * page token. - * @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.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink|DisplayVideo360AdvertiserLink}. - * 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 `listDisplayVideo360AdvertiserLinksAsync()` - * 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 DisplayVideo360AdvertiserLinks on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListDisplayVideo360AdvertiserLinks` + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * `ListDisplayVideo360AdvertiserLinks` must match the call that provided the + * page token. + * @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.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink|DisplayVideo360AdvertiserLink}. + * 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 `listDisplayVideo360AdvertiserLinksAsync()` + * 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. + */ listDisplayVideo360AdvertiserLinks( - request?: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink[], - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest|null, - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink[], + protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest | null, + protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksResponse, + ] + >; listDisplayVideo360AdvertiserLinks( - request: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest, - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink>): void; + request: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest, + | protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink + >, + ): void; listDisplayVideo360AdvertiserLinks( - request: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest, - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink>): void; + request: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest, + | protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink + >, + ): void; listDisplayVideo360AdvertiserLinks( - request?: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest, - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink>, - callback?: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest, - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink>): - Promise<[ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink[], - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest|null, - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest, + | protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink[], + protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest | null, + protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksResponse, + ] + > | 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.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest, - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest, + | protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { - this._log.info('listDisplayVideo360AdvertiserLinks values %j', values); + this._log.info( + 'listDisplayVideo360AdvertiserLinks values %j', + values, + ); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. } : undefined; this._log.info('listDisplayVideo360AdvertiserLinks request %j', request); return this.innerApiCalls .listDisplayVideo360AdvertiserLinks(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink[], - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest|null, - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksResponse - ]) => { - this._log.info('listDisplayVideo360AdvertiserLinks values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink[], + protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest | null, + protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksResponse, + ]) => { + this._log.info( + 'listDisplayVideo360AdvertiserLinks values %j', + response, + ); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listDisplayVideo360AdvertiserLinks`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListDisplayVideo360AdvertiserLinks` - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * `ListDisplayVideo360AdvertiserLinks` must match the call that provided the - * page token. - * @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.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink|DisplayVideo360AdvertiserLink} 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 `listDisplayVideo360AdvertiserLinksAsync()` - * 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 `listDisplayVideo360AdvertiserLinks`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListDisplayVideo360AdvertiserLinks` + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * `ListDisplayVideo360AdvertiserLinks` must match the call that provided the + * page token. + * @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.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink|DisplayVideo360AdvertiserLink} 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 `listDisplayVideo360AdvertiserLinksAsync()` + * 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. + */ listDisplayVideo360AdvertiserLinksStream( - request?: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest, + 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 ?? '', - }); - const defaultCallSettings = this._defaults['listDisplayVideo360AdvertiserLinks']; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = + this._defaults['listDisplayVideo360AdvertiserLinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listDisplayVideo360AdvertiserLinks stream %j', request); return this.descriptors.page.listDisplayVideo360AdvertiserLinks.createStream( this.innerApiCalls.listDisplayVideo360AdvertiserLinks as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listDisplayVideo360AdvertiserLinks`, 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. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListDisplayVideo360AdvertiserLinks` - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * `ListDisplayVideo360AdvertiserLinks` must match the call that provided the - * 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 protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink|DisplayVideo360AdvertiserLink}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_display_video360_advertiser_links.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListDisplayVideo360AdvertiserLinks_async - */ + /** + * Equivalent to `listDisplayVideo360AdvertiserLinks`, 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. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListDisplayVideo360AdvertiserLinks` + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * `ListDisplayVideo360AdvertiserLinks` must match the call that provided the + * 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 protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink|DisplayVideo360AdvertiserLink}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_display_video360_advertiser_links.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListDisplayVideo360AdvertiserLinks_async + */ listDisplayVideo360AdvertiserLinksAsync( - request?: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinksRequest, + 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 ?? '', - }); - const defaultCallSettings = this._defaults['listDisplayVideo360AdvertiserLinks']; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = + this._defaults['listDisplayVideo360AdvertiserLinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listDisplayVideo360AdvertiserLinks iterate %j', request); return this.descriptors.page.listDisplayVideo360AdvertiserLinks.asyncIterate( this.innerApiCalls['listDisplayVideo360AdvertiserLinks'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists DisplayVideo360AdvertiserLinkProposals on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous - * `ListDisplayVideo360AdvertiserLinkProposals` call. Provide this to retrieve - * the subsequent page. - * - * When paginating, all other parameters provided to - * `ListDisplayVideo360AdvertiserLinkProposals` must match the call that - * provided the page token. - * @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.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal|DisplayVideo360AdvertiserLinkProposal}. - * 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 `listDisplayVideo360AdvertiserLinkProposalsAsync()` - * 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 DisplayVideo360AdvertiserLinkProposals on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous + * `ListDisplayVideo360AdvertiserLinkProposals` call. Provide this to retrieve + * the subsequent page. + * + * When paginating, all other parameters provided to + * `ListDisplayVideo360AdvertiserLinkProposals` must match the call that + * provided the page token. + * @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.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal|DisplayVideo360AdvertiserLinkProposal}. + * 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 `listDisplayVideo360AdvertiserLinkProposalsAsync()` + * 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. + */ listDisplayVideo360AdvertiserLinkProposals( - request?: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal[], - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest|null, - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal[], + protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest | null, + protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsResponse, + ] + >; listDisplayVideo360AdvertiserLinkProposals( - request: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest, - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal>): void; + request: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest, + | protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal + >, + ): void; listDisplayVideo360AdvertiserLinkProposals( - request: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest, - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal>): void; + request: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest, + | protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal + >, + ): void; listDisplayVideo360AdvertiserLinkProposals( - request?: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest, - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal>, - callback?: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest, - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal>): - Promise<[ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal[], - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest|null, - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest, + | protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal[], + protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest | null, + protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsResponse, + ] + > | 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.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest, - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest, + | protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { - this._log.info('listDisplayVideo360AdvertiserLinkProposals values %j', values); + this._log.info( + 'listDisplayVideo360AdvertiserLinkProposals values %j', + values, + ); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. } : undefined; - this._log.info('listDisplayVideo360AdvertiserLinkProposals request %j', request); + this._log.info( + 'listDisplayVideo360AdvertiserLinkProposals request %j', + request, + ); return this.innerApiCalls - .listDisplayVideo360AdvertiserLinkProposals(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal[], - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest|null, - protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsResponse - ]) => { - this._log.info('listDisplayVideo360AdvertiserLinkProposals values %j', response); - return [response, input, output]; - }); + .listDisplayVideo360AdvertiserLinkProposals( + request, + options, + wrappedCallback, + ) + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal[], + protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest | null, + protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsResponse, + ]) => { + this._log.info( + 'listDisplayVideo360AdvertiserLinkProposals values %j', + response, + ); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listDisplayVideo360AdvertiserLinkProposals`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous - * `ListDisplayVideo360AdvertiserLinkProposals` call. Provide this to retrieve - * the subsequent page. - * - * When paginating, all other parameters provided to - * `ListDisplayVideo360AdvertiserLinkProposals` must match the call that - * provided the page token. - * @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.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal|DisplayVideo360AdvertiserLinkProposal} 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 `listDisplayVideo360AdvertiserLinkProposalsAsync()` - * 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 `listDisplayVideo360AdvertiserLinkProposals`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous + * `ListDisplayVideo360AdvertiserLinkProposals` call. Provide this to retrieve + * the subsequent page. + * + * When paginating, all other parameters provided to + * `ListDisplayVideo360AdvertiserLinkProposals` must match the call that + * provided the page token. + * @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.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal|DisplayVideo360AdvertiserLinkProposal} 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 `listDisplayVideo360AdvertiserLinkProposalsAsync()` + * 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. + */ listDisplayVideo360AdvertiserLinkProposalsStream( - request?: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest, + 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 ?? '', - }); - const defaultCallSettings = this._defaults['listDisplayVideo360AdvertiserLinkProposals']; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = + this._defaults['listDisplayVideo360AdvertiserLinkProposals']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); - this._log.info('listDisplayVideo360AdvertiserLinkProposals stream %j', request); + this.initialize().catch((err) => { + throw err; + }); + this._log.info( + 'listDisplayVideo360AdvertiserLinkProposals stream %j', + request, + ); return this.descriptors.page.listDisplayVideo360AdvertiserLinkProposals.createStream( this.innerApiCalls.listDisplayVideo360AdvertiserLinkProposals as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listDisplayVideo360AdvertiserLinkProposals`, 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. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous - * `ListDisplayVideo360AdvertiserLinkProposals` call. Provide this to retrieve - * the subsequent page. - * - * When paginating, all other parameters provided to - * `ListDisplayVideo360AdvertiserLinkProposals` must match the call that - * provided the 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 protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal|DisplayVideo360AdvertiserLinkProposal}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_display_video360_advertiser_link_proposals.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListDisplayVideo360AdvertiserLinkProposals_async - */ + /** + * Equivalent to `listDisplayVideo360AdvertiserLinkProposals`, 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. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous + * `ListDisplayVideo360AdvertiserLinkProposals` call. Provide this to retrieve + * the subsequent page. + * + * When paginating, all other parameters provided to + * `ListDisplayVideo360AdvertiserLinkProposals` must match the call that + * provided the 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 protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal|DisplayVideo360AdvertiserLinkProposal}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_display_video360_advertiser_link_proposals.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListDisplayVideo360AdvertiserLinkProposals_async + */ listDisplayVideo360AdvertiserLinkProposalsAsync( - request?: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListDisplayVideo360AdvertiserLinkProposalsRequest, + 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 ?? '', - }); - const defaultCallSettings = this._defaults['listDisplayVideo360AdvertiserLinkProposals']; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = + this._defaults['listDisplayVideo360AdvertiserLinkProposals']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); - this._log.info('listDisplayVideo360AdvertiserLinkProposals iterate %j', request); + this.initialize().catch((err) => { + throw err; + }); + this._log.info( + 'listDisplayVideo360AdvertiserLinkProposals iterate %j', + request, + ); return this.descriptors.page.listDisplayVideo360AdvertiserLinkProposals.asyncIterate( - this.innerApiCalls['listDisplayVideo360AdvertiserLinkProposals'] as GaxCall, + this.innerApiCalls[ + 'listDisplayVideo360AdvertiserLinkProposals' + ] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists CustomDimensions on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListCustomDimensions` - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListCustomDimensions` - * must match the call that provided the page token. - * @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.analytics.admin.v1alpha.CustomDimension|CustomDimension}. - * 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 `listCustomDimensionsAsync()` - * 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 CustomDimensions on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListCustomDimensions` + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListCustomDimensions` + * must match the call that provided the page token. + * @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.analytics.admin.v1alpha.CustomDimension|CustomDimension}. + * 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 `listCustomDimensionsAsync()` + * 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. + */ listCustomDimensions( - request?: protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ICustomDimension[], - protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest|null, - protos.google.analytics.admin.v1alpha.IListCustomDimensionsResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICustomDimension[], + protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest | null, + protos.google.analytics.admin.v1alpha.IListCustomDimensionsResponse, + ] + >; listCustomDimensions( - request: protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest, - protos.google.analytics.admin.v1alpha.IListCustomDimensionsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ICustomDimension>): void; + request: protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest, + | protos.google.analytics.admin.v1alpha.IListCustomDimensionsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ICustomDimension + >, + ): void; listCustomDimensions( - request: protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest, - protos.google.analytics.admin.v1alpha.IListCustomDimensionsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ICustomDimension>): void; + request: protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest, + | protos.google.analytics.admin.v1alpha.IListCustomDimensionsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ICustomDimension + >, + ): void; listCustomDimensions( - request?: protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest, - protos.google.analytics.admin.v1alpha.IListCustomDimensionsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ICustomDimension>, - callback?: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest, - protos.google.analytics.admin.v1alpha.IListCustomDimensionsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ICustomDimension>): - Promise<[ - protos.google.analytics.admin.v1alpha.ICustomDimension[], - protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest|null, - protos.google.analytics.admin.v1alpha.IListCustomDimensionsResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListCustomDimensionsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ICustomDimension + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest, + | protos.google.analytics.admin.v1alpha.IListCustomDimensionsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ICustomDimension + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICustomDimension[], + protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest | null, + protos.google.analytics.admin.v1alpha.IListCustomDimensionsResponse, + ] + > | 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.analytics.admin.v1alpha.IListCustomDimensionsRequest, - protos.google.analytics.admin.v1alpha.IListCustomDimensionsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ICustomDimension>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest, + | protos.google.analytics.admin.v1alpha.IListCustomDimensionsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ICustomDimension + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listCustomDimensions values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -15656,207 +22614,236 @@ export class AnalyticsAdminServiceClient { this._log.info('listCustomDimensions request %j', request); return this.innerApiCalls .listCustomDimensions(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.ICustomDimension[], - protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest|null, - protos.google.analytics.admin.v1alpha.IListCustomDimensionsResponse - ]) => { - this._log.info('listCustomDimensions values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.ICustomDimension[], + protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest | null, + protos.google.analytics.admin.v1alpha.IListCustomDimensionsResponse, + ]) => { + this._log.info('listCustomDimensions values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listCustomDimensions`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListCustomDimensions` - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListCustomDimensions` - * must match the call that provided the page token. - * @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.analytics.admin.v1alpha.CustomDimension|CustomDimension} 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 `listCustomDimensionsAsync()` - * 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 `listCustomDimensions`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListCustomDimensions` + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListCustomDimensions` + * must match the call that provided the page token. + * @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.analytics.admin.v1alpha.CustomDimension|CustomDimension} 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 `listCustomDimensionsAsync()` + * 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. + */ listCustomDimensionsStream( - request?: protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest, + 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['listCustomDimensions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCustomDimensions stream %j', request); return this.descriptors.page.listCustomDimensions.createStream( this.innerApiCalls.listCustomDimensions as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listCustomDimensions`, 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. Example format: properties/1234 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListCustomDimensions` - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListCustomDimensions` - * must match the call that provided the 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 protos.google.analytics.admin.v1alpha.CustomDimension|CustomDimension}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_custom_dimensions.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListCustomDimensions_async - */ + /** + * Equivalent to `listCustomDimensions`, 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. Example format: properties/1234 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListCustomDimensions` + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListCustomDimensions` + * must match the call that provided the 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 protos.google.analytics.admin.v1alpha.CustomDimension|CustomDimension}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_custom_dimensions.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListCustomDimensions_async + */ listCustomDimensionsAsync( - request?: protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListCustomDimensionsRequest, + 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['listCustomDimensions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCustomDimensions iterate %j', request); return this.descriptors.page.listCustomDimensions.asyncIterate( this.innerApiCalls['listCustomDimensions'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists CustomMetrics on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListCustomMetrics` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListCustomMetrics` must - * match the call that provided the page token. - * @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.analytics.admin.v1alpha.CustomMetric|CustomMetric}. - * 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 `listCustomMetricsAsync()` - * 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 CustomMetrics on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListCustomMetrics` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListCustomMetrics` must + * match the call that provided the page token. + * @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.analytics.admin.v1alpha.CustomMetric|CustomMetric}. + * 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 `listCustomMetricsAsync()` + * 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. + */ listCustomMetrics( - request?: protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ICustomMetric[], - protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest|null, - protos.google.analytics.admin.v1alpha.IListCustomMetricsResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICustomMetric[], + protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest | null, + protos.google.analytics.admin.v1alpha.IListCustomMetricsResponse, + ] + >; listCustomMetrics( - request: protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest, - protos.google.analytics.admin.v1alpha.IListCustomMetricsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ICustomMetric>): void; + request: protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest, + | protos.google.analytics.admin.v1alpha.IListCustomMetricsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ICustomMetric + >, + ): void; listCustomMetrics( - request: protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest, - protos.google.analytics.admin.v1alpha.IListCustomMetricsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ICustomMetric>): void; + request: protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest, + | protos.google.analytics.admin.v1alpha.IListCustomMetricsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ICustomMetric + >, + ): void; listCustomMetrics( - request?: protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest, - protos.google.analytics.admin.v1alpha.IListCustomMetricsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ICustomMetric>, - callback?: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest, - protos.google.analytics.admin.v1alpha.IListCustomMetricsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ICustomMetric>): - Promise<[ - protos.google.analytics.admin.v1alpha.ICustomMetric[], - protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest|null, - protos.google.analytics.admin.v1alpha.IListCustomMetricsResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListCustomMetricsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ICustomMetric + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest, + | protos.google.analytics.admin.v1alpha.IListCustomMetricsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ICustomMetric + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICustomMetric[], + protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest | null, + protos.google.analytics.admin.v1alpha.IListCustomMetricsResponse, + ] + > | 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.analytics.admin.v1alpha.IListCustomMetricsRequest, - protos.google.analytics.admin.v1alpha.IListCustomMetricsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ICustomMetric>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest, + | protos.google.analytics.admin.v1alpha.IListCustomMetricsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ICustomMetric + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listCustomMetrics values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -15865,207 +22852,236 @@ export class AnalyticsAdminServiceClient { this._log.info('listCustomMetrics request %j', request); return this.innerApiCalls .listCustomMetrics(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.ICustomMetric[], - protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest|null, - protos.google.analytics.admin.v1alpha.IListCustomMetricsResponse - ]) => { - this._log.info('listCustomMetrics values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.ICustomMetric[], + protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest | null, + protos.google.analytics.admin.v1alpha.IListCustomMetricsResponse, + ]) => { + this._log.info('listCustomMetrics values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listCustomMetrics`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListCustomMetrics` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListCustomMetrics` must - * match the call that provided the page token. - * @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.analytics.admin.v1alpha.CustomMetric|CustomMetric} 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 `listCustomMetricsAsync()` - * 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 `listCustomMetrics`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListCustomMetrics` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListCustomMetrics` must + * match the call that provided the page token. + * @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.analytics.admin.v1alpha.CustomMetric|CustomMetric} 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 `listCustomMetricsAsync()` + * 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. + */ listCustomMetricsStream( - request?: protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest, + 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['listCustomMetrics']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCustomMetrics stream %j', request); return this.descriptors.page.listCustomMetrics.createStream( this.innerApiCalls.listCustomMetrics as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listCustomMetrics`, 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. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListCustomMetrics` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListCustomMetrics` must - * match the call that provided the 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 protos.google.analytics.admin.v1alpha.CustomMetric|CustomMetric}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_custom_metrics.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListCustomMetrics_async - */ + /** + * Equivalent to `listCustomMetrics`, 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. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListCustomMetrics` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListCustomMetrics` must + * match the call that provided the 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 protos.google.analytics.admin.v1alpha.CustomMetric|CustomMetric}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_custom_metrics.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListCustomMetrics_async + */ listCustomMetricsAsync( - request?: protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListCustomMetricsRequest, + 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['listCustomMetrics']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCustomMetrics iterate %j', request); return this.descriptors.page.listCustomMetrics.asyncIterate( this.innerApiCalls['listCustomMetrics'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists DataStreams on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListDataStreams` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListDataStreams` must - * match the call that provided the page token. - * @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.analytics.admin.v1alpha.DataStream|DataStream}. - * 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 `listDataStreamsAsync()` - * 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 DataStreams on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListDataStreams` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListDataStreams` must + * match the call that provided the page token. + * @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.analytics.admin.v1alpha.DataStream|DataStream}. + * 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 `listDataStreamsAsync()` + * 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. + */ listDataStreams( - request?: protos.google.analytics.admin.v1alpha.IListDataStreamsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IDataStream[], - protos.google.analytics.admin.v1alpha.IListDataStreamsRequest|null, - protos.google.analytics.admin.v1alpha.IListDataStreamsResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListDataStreamsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDataStream[], + protos.google.analytics.admin.v1alpha.IListDataStreamsRequest | null, + protos.google.analytics.admin.v1alpha.IListDataStreamsResponse, + ] + >; listDataStreams( - request: protos.google.analytics.admin.v1alpha.IListDataStreamsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListDataStreamsRequest, - protos.google.analytics.admin.v1alpha.IListDataStreamsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IDataStream>): void; + request: protos.google.analytics.admin.v1alpha.IListDataStreamsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListDataStreamsRequest, + | protos.google.analytics.admin.v1alpha.IListDataStreamsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IDataStream + >, + ): void; listDataStreams( - request: protos.google.analytics.admin.v1alpha.IListDataStreamsRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListDataStreamsRequest, - protos.google.analytics.admin.v1alpha.IListDataStreamsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IDataStream>): void; + request: protos.google.analytics.admin.v1alpha.IListDataStreamsRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListDataStreamsRequest, + | protos.google.analytics.admin.v1alpha.IListDataStreamsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IDataStream + >, + ): void; listDataStreams( - request?: protos.google.analytics.admin.v1alpha.IListDataStreamsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListDataStreamsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListDataStreamsRequest, - protos.google.analytics.admin.v1alpha.IListDataStreamsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IDataStream>, - callback?: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListDataStreamsRequest, - protos.google.analytics.admin.v1alpha.IListDataStreamsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IDataStream>): - Promise<[ - protos.google.analytics.admin.v1alpha.IDataStream[], - protos.google.analytics.admin.v1alpha.IListDataStreamsRequest|null, - protos.google.analytics.admin.v1alpha.IListDataStreamsResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListDataStreamsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IDataStream + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListDataStreamsRequest, + | protos.google.analytics.admin.v1alpha.IListDataStreamsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IDataStream + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IDataStream[], + protos.google.analytics.admin.v1alpha.IListDataStreamsRequest | null, + protos.google.analytics.admin.v1alpha.IListDataStreamsResponse, + ] + > | 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.analytics.admin.v1alpha.IListDataStreamsRequest, - protos.google.analytics.admin.v1alpha.IListDataStreamsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IDataStream>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListDataStreamsRequest, + | protos.google.analytics.admin.v1alpha.IListDataStreamsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IDataStream + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listDataStreams values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -16074,209 +23090,238 @@ export class AnalyticsAdminServiceClient { this._log.info('listDataStreams request %j', request); return this.innerApiCalls .listDataStreams(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.IDataStream[], - protos.google.analytics.admin.v1alpha.IListDataStreamsRequest|null, - protos.google.analytics.admin.v1alpha.IListDataStreamsResponse - ]) => { - this._log.info('listDataStreams values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.IDataStream[], + protos.google.analytics.admin.v1alpha.IListDataStreamsRequest | null, + protos.google.analytics.admin.v1alpha.IListDataStreamsResponse, + ]) => { + this._log.info('listDataStreams values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listDataStreams`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListDataStreams` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListDataStreams` must - * match the call that provided the page token. - * @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.analytics.admin.v1alpha.DataStream|DataStream} 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 `listDataStreamsAsync()` - * 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 `listDataStreams`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListDataStreams` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListDataStreams` must + * match the call that provided the page token. + * @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.analytics.admin.v1alpha.DataStream|DataStream} 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 `listDataStreamsAsync()` + * 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. + */ listDataStreamsStream( - request?: protos.google.analytics.admin.v1alpha.IListDataStreamsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListDataStreamsRequest, + 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['listDataStreams']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listDataStreams stream %j', request); return this.descriptors.page.listDataStreams.createStream( this.innerApiCalls.listDataStreams as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listDataStreams`, 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. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListDataStreams` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListDataStreams` must - * match the call that provided the 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 protos.google.analytics.admin.v1alpha.DataStream|DataStream}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_data_streams.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListDataStreams_async - */ + /** + * Equivalent to `listDataStreams`, 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. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListDataStreams` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListDataStreams` must + * match the call that provided the 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 protos.google.analytics.admin.v1alpha.DataStream|DataStream}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_data_streams.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListDataStreams_async + */ listDataStreamsAsync( - request?: protos.google.analytics.admin.v1alpha.IListDataStreamsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListDataStreamsRequest, + 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['listDataStreams']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listDataStreams iterate %j', request); return this.descriptors.page.listDataStreams.asyncIterate( this.innerApiCalls['listDataStreams'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists Audiences on a property. - * Audiences created before 2020 may not be supported. - * Default audiences will not show filter definitions. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListAudiences` call. Provide this - * to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListAudiences` must - * match the call that provided the page token. - * @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.analytics.admin.v1alpha.Audience|Audience}. - * 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 `listAudiencesAsync()` - * 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 Audiences on a property. + * Audiences created before 2020 may not be supported. + * Default audiences will not show filter definitions. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListAudiences` call. Provide this + * to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListAudiences` must + * match the call that provided the page token. + * @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.analytics.admin.v1alpha.Audience|Audience}. + * 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 `listAudiencesAsync()` + * 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. + */ listAudiences( - request?: protos.google.analytics.admin.v1alpha.IListAudiencesRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IAudience[], - protos.google.analytics.admin.v1alpha.IListAudiencesRequest|null, - protos.google.analytics.admin.v1alpha.IListAudiencesResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListAudiencesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAudience[], + protos.google.analytics.admin.v1alpha.IListAudiencesRequest | null, + protos.google.analytics.admin.v1alpha.IListAudiencesResponse, + ] + >; listAudiences( - request: protos.google.analytics.admin.v1alpha.IListAudiencesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListAudiencesRequest, - protos.google.analytics.admin.v1alpha.IListAudiencesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAudience>): void; + request: protos.google.analytics.admin.v1alpha.IListAudiencesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListAudiencesRequest, + | protos.google.analytics.admin.v1alpha.IListAudiencesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAudience + >, + ): void; listAudiences( - request: protos.google.analytics.admin.v1alpha.IListAudiencesRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListAudiencesRequest, - protos.google.analytics.admin.v1alpha.IListAudiencesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAudience>): void; + request: protos.google.analytics.admin.v1alpha.IListAudiencesRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListAudiencesRequest, + | protos.google.analytics.admin.v1alpha.IListAudiencesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAudience + >, + ): void; listAudiences( - request?: protos.google.analytics.admin.v1alpha.IListAudiencesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListAudiencesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListAudiencesRequest, - protos.google.analytics.admin.v1alpha.IListAudiencesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAudience>, - callback?: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListAudiencesRequest, - protos.google.analytics.admin.v1alpha.IListAudiencesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAudience>): - Promise<[ - protos.google.analytics.admin.v1alpha.IAudience[], - protos.google.analytics.admin.v1alpha.IListAudiencesRequest|null, - protos.google.analytics.admin.v1alpha.IListAudiencesResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListAudiencesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAudience + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListAudiencesRequest, + | protos.google.analytics.admin.v1alpha.IListAudiencesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAudience + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAudience[], + protos.google.analytics.admin.v1alpha.IListAudiencesRequest | null, + protos.google.analytics.admin.v1alpha.IListAudiencesResponse, + ] + > | 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.analytics.admin.v1alpha.IListAudiencesRequest, - protos.google.analytics.admin.v1alpha.IListAudiencesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAudience>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListAudiencesRequest, + | protos.google.analytics.admin.v1alpha.IListAudiencesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAudience + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listAudiences values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -16285,208 +23330,237 @@ export class AnalyticsAdminServiceClient { this._log.info('listAudiences request %j', request); return this.innerApiCalls .listAudiences(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.IAudience[], - protos.google.analytics.admin.v1alpha.IListAudiencesRequest|null, - protos.google.analytics.admin.v1alpha.IListAudiencesResponse - ]) => { - this._log.info('listAudiences values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.IAudience[], + protos.google.analytics.admin.v1alpha.IListAudiencesRequest | null, + protos.google.analytics.admin.v1alpha.IListAudiencesResponse, + ]) => { + this._log.info('listAudiences values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listAudiences`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListAudiences` call. Provide this - * to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListAudiences` must - * match the call that provided the page token. - * @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.analytics.admin.v1alpha.Audience|Audience} 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 `listAudiencesAsync()` - * 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 `listAudiences`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListAudiences` call. Provide this + * to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListAudiences` must + * match the call that provided the page token. + * @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.analytics.admin.v1alpha.Audience|Audience} 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 `listAudiencesAsync()` + * 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. + */ listAudiencesStream( - request?: protos.google.analytics.admin.v1alpha.IListAudiencesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListAudiencesRequest, + 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['listAudiences']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listAudiences stream %j', request); return this.descriptors.page.listAudiences.createStream( this.innerApiCalls.listAudiences as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listAudiences`, 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. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListAudiences` call. Provide this - * to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListAudiences` must - * match the call that provided the 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 protos.google.analytics.admin.v1alpha.Audience|Audience}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_audiences.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListAudiences_async - */ + /** + * Equivalent to `listAudiences`, 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. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListAudiences` call. Provide this + * to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListAudiences` must + * match the call that provided the 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 protos.google.analytics.admin.v1alpha.Audience|Audience}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_audiences.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListAudiences_async + */ listAudiencesAsync( - request?: protos.google.analytics.admin.v1alpha.IListAudiencesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListAudiencesRequest, + 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['listAudiences']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listAudiences iterate %j', request); return this.descriptors.page.listAudiences.asyncIterate( this.innerApiCalls['listAudiences'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists all SearchAds360Links on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListSearchAds360Links` - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * `ListSearchAds360Links` must match the call that provided the - * page token. - * @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.analytics.admin.v1alpha.SearchAds360Link|SearchAds360Link}. - * 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 `listSearchAds360LinksAsync()` - * 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 SearchAds360Links on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListSearchAds360Links` + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * `ListSearchAds360Links` must match the call that provided the + * page token. + * @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.analytics.admin.v1alpha.SearchAds360Link|SearchAds360Link}. + * 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 `listSearchAds360LinksAsync()` + * 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. + */ listSearchAds360Links( - request?: protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ISearchAds360Link[], - protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest|null, - protos.google.analytics.admin.v1alpha.IListSearchAds360LinksResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISearchAds360Link[], + protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest | null, + protos.google.analytics.admin.v1alpha.IListSearchAds360LinksResponse, + ] + >; listSearchAds360Links( - request: protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest, - protos.google.analytics.admin.v1alpha.IListSearchAds360LinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ISearchAds360Link>): void; + request: protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest, + | protos.google.analytics.admin.v1alpha.IListSearchAds360LinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ISearchAds360Link + >, + ): void; listSearchAds360Links( - request: protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest, - protos.google.analytics.admin.v1alpha.IListSearchAds360LinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ISearchAds360Link>): void; + request: protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest, + | protos.google.analytics.admin.v1alpha.IListSearchAds360LinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ISearchAds360Link + >, + ): void; listSearchAds360Links( - request?: protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest, - protos.google.analytics.admin.v1alpha.IListSearchAds360LinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ISearchAds360Link>, - callback?: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest, - protos.google.analytics.admin.v1alpha.IListSearchAds360LinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ISearchAds360Link>): - Promise<[ - protos.google.analytics.admin.v1alpha.ISearchAds360Link[], - protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest|null, - protos.google.analytics.admin.v1alpha.IListSearchAds360LinksResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListSearchAds360LinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ISearchAds360Link + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest, + | protos.google.analytics.admin.v1alpha.IListSearchAds360LinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ISearchAds360Link + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISearchAds360Link[], + protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest | null, + protos.google.analytics.admin.v1alpha.IListSearchAds360LinksResponse, + ] + > | 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.analytics.admin.v1alpha.IListSearchAds360LinksRequest, - protos.google.analytics.admin.v1alpha.IListSearchAds360LinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ISearchAds360Link>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest, + | protos.google.analytics.admin.v1alpha.IListSearchAds360LinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ISearchAds360Link + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listSearchAds360Links values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -16495,211 +23569,240 @@ export class AnalyticsAdminServiceClient { this._log.info('listSearchAds360Links request %j', request); return this.innerApiCalls .listSearchAds360Links(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.ISearchAds360Link[], - protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest|null, - protos.google.analytics.admin.v1alpha.IListSearchAds360LinksResponse - ]) => { - this._log.info('listSearchAds360Links values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.ISearchAds360Link[], + protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest | null, + protos.google.analytics.admin.v1alpha.IListSearchAds360LinksResponse, + ]) => { + this._log.info('listSearchAds360Links values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listSearchAds360Links`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListSearchAds360Links` - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * `ListSearchAds360Links` must match the call that provided the - * page token. - * @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.analytics.admin.v1alpha.SearchAds360Link|SearchAds360Link} 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 `listSearchAds360LinksAsync()` - * 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 `listSearchAds360Links`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListSearchAds360Links` + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * `ListSearchAds360Links` must match the call that provided the + * page token. + * @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.analytics.admin.v1alpha.SearchAds360Link|SearchAds360Link} 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 `listSearchAds360LinksAsync()` + * 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. + */ listSearchAds360LinksStream( - request?: protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest, + 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['listSearchAds360Links']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listSearchAds360Links stream %j', request); return this.descriptors.page.listSearchAds360Links.createStream( this.innerApiCalls.listSearchAds360Links as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listSearchAds360Links`, 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. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListSearchAds360Links` - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to - * `ListSearchAds360Links` must match the call that provided the - * 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 protos.google.analytics.admin.v1alpha.SearchAds360Link|SearchAds360Link}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_search_ads360_links.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListSearchAds360Links_async - */ + /** + * Equivalent to `listSearchAds360Links`, 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. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListSearchAds360Links` + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to + * `ListSearchAds360Links` must match the call that provided the + * 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 protos.google.analytics.admin.v1alpha.SearchAds360Link|SearchAds360Link}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_search_ads360_links.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListSearchAds360Links_async + */ listSearchAds360LinksAsync( - request?: protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListSearchAds360LinksRequest, + 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['listSearchAds360Links']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listSearchAds360Links iterate %j', request); return this.descriptors.page.listSearchAds360Links.asyncIterate( this.innerApiCalls['listSearchAds360Links'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists all access bindings on an account or property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Formats: - * - accounts/{account} - * - properties/{property} - * @param {number} request.pageSize - * The maximum number of access bindings to return. - * The service may return fewer than this value. - * If unspecified, at most 200 access bindings will be returned. - * The maximum value is 500; values above 500 will be coerced to 500. - * @param {string} request.pageToken - * A page token, received from a previous `ListAccessBindings` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListAccessBindings` must - * match the call that provided the page token. - * @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.analytics.admin.v1alpha.AccessBinding|AccessBinding}. - * 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 `listAccessBindingsAsync()` - * 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 access bindings on an account or property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Formats: + * - accounts/{account} + * - properties/{property} + * @param {number} request.pageSize + * The maximum number of access bindings to return. + * The service may return fewer than this value. + * If unspecified, at most 200 access bindings will be returned. + * The maximum value is 500; values above 500 will be coerced to 500. + * @param {string} request.pageToken + * A page token, received from a previous `ListAccessBindings` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListAccessBindings` must + * match the call that provided the page token. + * @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.analytics.admin.v1alpha.AccessBinding|AccessBinding}. + * 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 `listAccessBindingsAsync()` + * 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. + */ listAccessBindings( - request?: protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IAccessBinding[], - protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest|null, - protos.google.analytics.admin.v1alpha.IListAccessBindingsResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAccessBinding[], + protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest | null, + protos.google.analytics.admin.v1alpha.IListAccessBindingsResponse, + ] + >; listAccessBindings( - request: protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest, - protos.google.analytics.admin.v1alpha.IListAccessBindingsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAccessBinding>): void; + request: protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest, + | protos.google.analytics.admin.v1alpha.IListAccessBindingsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAccessBinding + >, + ): void; listAccessBindings( - request: protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest, - protos.google.analytics.admin.v1alpha.IListAccessBindingsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAccessBinding>): void; + request: protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest, + | protos.google.analytics.admin.v1alpha.IListAccessBindingsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAccessBinding + >, + ): void; listAccessBindings( - request?: protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest, - protos.google.analytics.admin.v1alpha.IListAccessBindingsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAccessBinding>, - callback?: PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest, - protos.google.analytics.admin.v1alpha.IListAccessBindingsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAccessBinding>): - Promise<[ - protos.google.analytics.admin.v1alpha.IAccessBinding[], - protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest|null, - protos.google.analytics.admin.v1alpha.IListAccessBindingsResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListAccessBindingsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAccessBinding + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest, + | protos.google.analytics.admin.v1alpha.IListAccessBindingsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAccessBinding + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAccessBinding[], + protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest | null, + protos.google.analytics.admin.v1alpha.IListAccessBindingsResponse, + ] + > | 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.analytics.admin.v1alpha.IListAccessBindingsRequest, - protos.google.analytics.admin.v1alpha.IListAccessBindingsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAccessBinding>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest, + | protos.google.analytics.admin.v1alpha.IListAccessBindingsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAccessBinding + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listAccessBindings values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -16708,211 +23811,240 @@ export class AnalyticsAdminServiceClient { this._log.info('listAccessBindings request %j', request); return this.innerApiCalls .listAccessBindings(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.IAccessBinding[], - protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest|null, - protos.google.analytics.admin.v1alpha.IListAccessBindingsResponse - ]) => { - this._log.info('listAccessBindings values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.IAccessBinding[], + protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest | null, + protos.google.analytics.admin.v1alpha.IListAccessBindingsResponse, + ]) => { + this._log.info('listAccessBindings values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listAccessBindings`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Formats: - * - accounts/{account} - * - properties/{property} - * @param {number} request.pageSize - * The maximum number of access bindings to return. - * The service may return fewer than this value. - * If unspecified, at most 200 access bindings will be returned. - * The maximum value is 500; values above 500 will be coerced to 500. - * @param {string} request.pageToken - * A page token, received from a previous `ListAccessBindings` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListAccessBindings` must - * match the call that provided the page token. - * @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.analytics.admin.v1alpha.AccessBinding|AccessBinding} 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 `listAccessBindingsAsync()` - * 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 `listAccessBindings`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Formats: + * - accounts/{account} + * - properties/{property} + * @param {number} request.pageSize + * The maximum number of access bindings to return. + * The service may return fewer than this value. + * If unspecified, at most 200 access bindings will be returned. + * The maximum value is 500; values above 500 will be coerced to 500. + * @param {string} request.pageToken + * A page token, received from a previous `ListAccessBindings` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListAccessBindings` must + * match the call that provided the page token. + * @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.analytics.admin.v1alpha.AccessBinding|AccessBinding} 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 `listAccessBindingsAsync()` + * 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. + */ listAccessBindingsStream( - request?: protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest, + 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['listAccessBindings']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listAccessBindings stream %j', request); return this.descriptors.page.listAccessBindings.createStream( this.innerApiCalls.listAccessBindings as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listAccessBindings`, 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. Formats: - * - accounts/{account} - * - properties/{property} - * @param {number} request.pageSize - * The maximum number of access bindings to return. - * The service may return fewer than this value. - * If unspecified, at most 200 access bindings will be returned. - * The maximum value is 500; values above 500 will be coerced to 500. - * @param {string} request.pageToken - * A page token, received from a previous `ListAccessBindings` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListAccessBindings` must - * match the call that provided the 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 protos.google.analytics.admin.v1alpha.AccessBinding|AccessBinding}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_access_bindings.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListAccessBindings_async - */ + /** + * Equivalent to `listAccessBindings`, 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. Formats: + * - accounts/{account} + * - properties/{property} + * @param {number} request.pageSize + * The maximum number of access bindings to return. + * The service may return fewer than this value. + * If unspecified, at most 200 access bindings will be returned. + * The maximum value is 500; values above 500 will be coerced to 500. + * @param {string} request.pageToken + * A page token, received from a previous `ListAccessBindings` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListAccessBindings` must + * match the call that provided the 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 protos.google.analytics.admin.v1alpha.AccessBinding|AccessBinding}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_access_bindings.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListAccessBindings_async + */ listAccessBindingsAsync( - request?: protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListAccessBindingsRequest, + 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['listAccessBindings']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listAccessBindings iterate %j', request); return this.descriptors.page.listAccessBindings.asyncIterate( this.innerApiCalls['listAccessBindings'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists ExpandedDataSets on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListExpandedDataSets` call. Provide - * this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListExpandedDataSet` - * must match the call that provided the page token. - * @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.analytics.admin.v1alpha.ExpandedDataSet|ExpandedDataSet}. - * 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 `listExpandedDataSetsAsync()` - * 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 ExpandedDataSets on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListExpandedDataSets` call. Provide + * this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListExpandedDataSet` + * must match the call that provided the page token. + * @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.analytics.admin.v1alpha.ExpandedDataSet|ExpandedDataSet}. + * 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 `listExpandedDataSetsAsync()` + * 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. + */ listExpandedDataSets( - request?: protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IExpandedDataSet[], - protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest|null, - protos.google.analytics.admin.v1alpha.IListExpandedDataSetsResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IExpandedDataSet[], + protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest | null, + protos.google.analytics.admin.v1alpha.IListExpandedDataSetsResponse, + ] + >; listExpandedDataSets( - request: protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest, - protos.google.analytics.admin.v1alpha.IListExpandedDataSetsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IExpandedDataSet>): void; + request: protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest, + | protos.google.analytics.admin.v1alpha.IListExpandedDataSetsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IExpandedDataSet + >, + ): void; listExpandedDataSets( - request: protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest, - protos.google.analytics.admin.v1alpha.IListExpandedDataSetsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IExpandedDataSet>): void; + request: protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest, + | protos.google.analytics.admin.v1alpha.IListExpandedDataSetsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IExpandedDataSet + >, + ): void; listExpandedDataSets( - request?: protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest, - protos.google.analytics.admin.v1alpha.IListExpandedDataSetsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IExpandedDataSet>, - callback?: PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest, - protos.google.analytics.admin.v1alpha.IListExpandedDataSetsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IExpandedDataSet>): - Promise<[ - protos.google.analytics.admin.v1alpha.IExpandedDataSet[], - protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest|null, - protos.google.analytics.admin.v1alpha.IListExpandedDataSetsResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListExpandedDataSetsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IExpandedDataSet + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest, + | protos.google.analytics.admin.v1alpha.IListExpandedDataSetsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IExpandedDataSet + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IExpandedDataSet[], + protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest | null, + protos.google.analytics.admin.v1alpha.IListExpandedDataSetsResponse, + ] + > | 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.analytics.admin.v1alpha.IListExpandedDataSetsRequest, - protos.google.analytics.admin.v1alpha.IListExpandedDataSetsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IExpandedDataSet>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest, + | protos.google.analytics.admin.v1alpha.IListExpandedDataSetsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IExpandedDataSet + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listExpandedDataSets values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -16921,208 +24053,237 @@ export class AnalyticsAdminServiceClient { this._log.info('listExpandedDataSets request %j', request); return this.innerApiCalls .listExpandedDataSets(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.IExpandedDataSet[], - protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest|null, - protos.google.analytics.admin.v1alpha.IListExpandedDataSetsResponse - ]) => { - this._log.info('listExpandedDataSets values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.IExpandedDataSet[], + protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest | null, + protos.google.analytics.admin.v1alpha.IListExpandedDataSetsResponse, + ]) => { + this._log.info('listExpandedDataSets values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listExpandedDataSets`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListExpandedDataSets` call. Provide - * this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListExpandedDataSet` - * must match the call that provided the page token. - * @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.analytics.admin.v1alpha.ExpandedDataSet|ExpandedDataSet} 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 `listExpandedDataSetsAsync()` - * 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 `listExpandedDataSets`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListExpandedDataSets` call. Provide + * this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListExpandedDataSet` + * must match the call that provided the page token. + * @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.analytics.admin.v1alpha.ExpandedDataSet|ExpandedDataSet} 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 `listExpandedDataSetsAsync()` + * 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. + */ listExpandedDataSetsStream( - request?: protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest, + 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['listExpandedDataSets']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listExpandedDataSets stream %j', request); return this.descriptors.page.listExpandedDataSets.createStream( this.innerApiCalls.listExpandedDataSets as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listExpandedDataSets`, 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. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListExpandedDataSets` call. Provide - * this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListExpandedDataSet` - * must match the call that provided the 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 protos.google.analytics.admin.v1alpha.ExpandedDataSet|ExpandedDataSet}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_expanded_data_sets.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListExpandedDataSets_async - */ + /** + * Equivalent to `listExpandedDataSets`, 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. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListExpandedDataSets` call. Provide + * this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListExpandedDataSet` + * must match the call that provided the 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 protos.google.analytics.admin.v1alpha.ExpandedDataSet|ExpandedDataSet}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_expanded_data_sets.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListExpandedDataSets_async + */ listExpandedDataSetsAsync( - request?: protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListExpandedDataSetsRequest, + 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['listExpandedDataSets']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listExpandedDataSets iterate %j', request); return this.descriptors.page.listExpandedDataSets.asyncIterate( this.innerApiCalls['listExpandedDataSets'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists ChannelGroups on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The property for which to list ChannelGroups. - * Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListChannelGroups` call. Provide - * this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListChannelGroups` - * must match the call that provided the page token. - * @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.analytics.admin.v1alpha.ChannelGroup|ChannelGroup}. - * 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 `listChannelGroupsAsync()` - * 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 ChannelGroups on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The property for which to list ChannelGroups. + * Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListChannelGroups` call. Provide + * this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListChannelGroups` + * must match the call that provided the page token. + * @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.analytics.admin.v1alpha.ChannelGroup|ChannelGroup}. + * 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 `listChannelGroupsAsync()` + * 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. + */ listChannelGroups( - request?: protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IChannelGroup[], - protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest|null, - protos.google.analytics.admin.v1alpha.IListChannelGroupsResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IChannelGroup[], + protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest | null, + protos.google.analytics.admin.v1alpha.IListChannelGroupsResponse, + ] + >; listChannelGroups( - request: protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest, - protos.google.analytics.admin.v1alpha.IListChannelGroupsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IChannelGroup>): void; + request: protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest, + | protos.google.analytics.admin.v1alpha.IListChannelGroupsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IChannelGroup + >, + ): void; listChannelGroups( - request: protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest, - protos.google.analytics.admin.v1alpha.IListChannelGroupsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IChannelGroup>): void; + request: protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest, + | protos.google.analytics.admin.v1alpha.IListChannelGroupsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IChannelGroup + >, + ): void; listChannelGroups( - request?: protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest, - protos.google.analytics.admin.v1alpha.IListChannelGroupsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IChannelGroup>, - callback?: PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest, - protos.google.analytics.admin.v1alpha.IListChannelGroupsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IChannelGroup>): - Promise<[ - protos.google.analytics.admin.v1alpha.IChannelGroup[], - protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest|null, - protos.google.analytics.admin.v1alpha.IListChannelGroupsResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListChannelGroupsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IChannelGroup + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest, + | protos.google.analytics.admin.v1alpha.IListChannelGroupsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IChannelGroup + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IChannelGroup[], + protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest | null, + protos.google.analytics.admin.v1alpha.IListChannelGroupsResponse, + ] + > | 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.analytics.admin.v1alpha.IListChannelGroupsRequest, - protos.google.analytics.admin.v1alpha.IListChannelGroupsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IChannelGroup>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest, + | protos.google.analytics.admin.v1alpha.IListChannelGroupsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IChannelGroup + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listChannelGroups values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -17131,211 +24292,240 @@ export class AnalyticsAdminServiceClient { this._log.info('listChannelGroups request %j', request); return this.innerApiCalls .listChannelGroups(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.IChannelGroup[], - protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest|null, - protos.google.analytics.admin.v1alpha.IListChannelGroupsResponse - ]) => { - this._log.info('listChannelGroups values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.IChannelGroup[], + protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest | null, + protos.google.analytics.admin.v1alpha.IListChannelGroupsResponse, + ]) => { + this._log.info('listChannelGroups values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listChannelGroups`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The property for which to list ChannelGroups. - * Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListChannelGroups` call. Provide - * this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListChannelGroups` - * must match the call that provided the page token. - * @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.analytics.admin.v1alpha.ChannelGroup|ChannelGroup} 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 `listChannelGroupsAsync()` - * 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 `listChannelGroups`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The property for which to list ChannelGroups. + * Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListChannelGroups` call. Provide + * this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListChannelGroups` + * must match the call that provided the page token. + * @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.analytics.admin.v1alpha.ChannelGroup|ChannelGroup} 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 `listChannelGroupsAsync()` + * 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. + */ listChannelGroupsStream( - request?: protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest, + 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['listChannelGroups']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listChannelGroups stream %j', request); return this.descriptors.page.listChannelGroups.createStream( this.innerApiCalls.listChannelGroups as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listChannelGroups`, 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 property for which to list ChannelGroups. - * Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListChannelGroups` call. Provide - * this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListChannelGroups` - * must match the call that provided the 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 protos.google.analytics.admin.v1alpha.ChannelGroup|ChannelGroup}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_channel_groups.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListChannelGroups_async - */ + /** + * Equivalent to `listChannelGroups`, 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 property for which to list ChannelGroups. + * Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListChannelGroups` call. Provide + * this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListChannelGroups` + * must match the call that provided the 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 protos.google.analytics.admin.v1alpha.ChannelGroup|ChannelGroup}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_channel_groups.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListChannelGroups_async + */ listChannelGroupsAsync( - request?: protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListChannelGroupsRequest, + 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['listChannelGroups']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listChannelGroups iterate %j', request); return this.descriptors.page.listChannelGroups.asyncIterate( this.innerApiCalls['listChannelGroups'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists BigQuery Links on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the property to list BigQuery links under. - * Format: properties/{property_id} - * Example: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} request.pageToken - * A page token, received from a previous `ListBigQueryLinks` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListBigQueryLinks` must - * match the call that provided the page token. - * @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.analytics.admin.v1alpha.BigQueryLink|BigQueryLink}. - * 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 `listBigQueryLinksAsync()` - * 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 BigQuery Links on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the property to list BigQuery links under. + * Format: properties/{property_id} + * Example: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} request.pageToken + * A page token, received from a previous `ListBigQueryLinks` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListBigQueryLinks` must + * match the call that provided the page token. + * @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.analytics.admin.v1alpha.BigQueryLink|BigQueryLink}. + * 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 `listBigQueryLinksAsync()` + * 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. + */ listBigQueryLinks( - request?: protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IBigQueryLink[], - protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest|null, - protos.google.analytics.admin.v1alpha.IListBigQueryLinksResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IBigQueryLink[], + protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest | null, + protos.google.analytics.admin.v1alpha.IListBigQueryLinksResponse, + ] + >; listBigQueryLinks( - request: protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest, - protos.google.analytics.admin.v1alpha.IListBigQueryLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IBigQueryLink>): void; + request: protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest, + | protos.google.analytics.admin.v1alpha.IListBigQueryLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IBigQueryLink + >, + ): void; listBigQueryLinks( - request: protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest, - protos.google.analytics.admin.v1alpha.IListBigQueryLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IBigQueryLink>): void; + request: protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest, + | protos.google.analytics.admin.v1alpha.IListBigQueryLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IBigQueryLink + >, + ): void; listBigQueryLinks( - request?: protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest, - protos.google.analytics.admin.v1alpha.IListBigQueryLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IBigQueryLink>, - callback?: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest, - protos.google.analytics.admin.v1alpha.IListBigQueryLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IBigQueryLink>): - Promise<[ - protos.google.analytics.admin.v1alpha.IBigQueryLink[], - protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest|null, - protos.google.analytics.admin.v1alpha.IListBigQueryLinksResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListBigQueryLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IBigQueryLink + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest, + | protos.google.analytics.admin.v1alpha.IListBigQueryLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IBigQueryLink + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IBigQueryLink[], + protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest | null, + protos.google.analytics.admin.v1alpha.IListBigQueryLinksResponse, + ] + > | 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.analytics.admin.v1alpha.IListBigQueryLinksRequest, - protos.google.analytics.admin.v1alpha.IListBigQueryLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IBigQueryLink>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest, + | protos.google.analytics.admin.v1alpha.IListBigQueryLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IBigQueryLink + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listBigQueryLinks values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -17344,213 +24534,242 @@ export class AnalyticsAdminServiceClient { this._log.info('listBigQueryLinks request %j', request); return this.innerApiCalls .listBigQueryLinks(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.IBigQueryLink[], - protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest|null, - protos.google.analytics.admin.v1alpha.IListBigQueryLinksResponse - ]) => { - this._log.info('listBigQueryLinks values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.IBigQueryLink[], + protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest | null, + protos.google.analytics.admin.v1alpha.IListBigQueryLinksResponse, + ]) => { + this._log.info('listBigQueryLinks values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listBigQueryLinks`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the property to list BigQuery links under. - * Format: properties/{property_id} - * Example: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} request.pageToken - * A page token, received from a previous `ListBigQueryLinks` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListBigQueryLinks` must - * match the call that provided the page token. - * @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.analytics.admin.v1alpha.BigQueryLink|BigQueryLink} 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 `listBigQueryLinksAsync()` - * 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 `listBigQueryLinks`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the property to list BigQuery links under. + * Format: properties/{property_id} + * Example: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} request.pageToken + * A page token, received from a previous `ListBigQueryLinks` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListBigQueryLinks` must + * match the call that provided the page token. + * @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.analytics.admin.v1alpha.BigQueryLink|BigQueryLink} 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 `listBigQueryLinksAsync()` + * 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. + */ listBigQueryLinksStream( - request?: protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest, + 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['listBigQueryLinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listBigQueryLinks stream %j', request); return this.descriptors.page.listBigQueryLinks.createStream( this.innerApiCalls.listBigQueryLinks as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listBigQueryLinks`, 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 name of the property to list BigQuery links under. - * Format: properties/{property_id} - * Example: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} request.pageToken - * A page token, received from a previous `ListBigQueryLinks` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListBigQueryLinks` must - * match the call that provided the 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 protos.google.analytics.admin.v1alpha.BigQueryLink|BigQueryLink}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_big_query_links.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListBigQueryLinks_async - */ + /** + * Equivalent to `listBigQueryLinks`, 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 name of the property to list BigQuery links under. + * Format: properties/{property_id} + * Example: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} request.pageToken + * A page token, received from a previous `ListBigQueryLinks` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListBigQueryLinks` must + * match the call that provided the 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 protos.google.analytics.admin.v1alpha.BigQueryLink|BigQueryLink}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_big_query_links.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListBigQueryLinks_async + */ listBigQueryLinksAsync( - request?: protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListBigQueryLinksRequest, + 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['listBigQueryLinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listBigQueryLinks iterate %j', request); return this.descriptors.page.listBigQueryLinks.asyncIterate( this.innerApiCalls['listBigQueryLinks'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists AdSenseLinks on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the parent property. - * Format: properties/{propertyId} - * Example: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token received from a previous `ListAdSenseLinks` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListAdSenseLinks` must - * match the call that provided the page token. - * @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.analytics.admin.v1alpha.AdSenseLink|AdSenseLink}. - * 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 `listAdSenseLinksAsync()` - * 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 AdSenseLinks on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the parent property. + * Format: properties/{propertyId} + * Example: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token received from a previous `ListAdSenseLinks` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListAdSenseLinks` must + * match the call that provided the page token. + * @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.analytics.admin.v1alpha.AdSenseLink|AdSenseLink}. + * 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 `listAdSenseLinksAsync()` + * 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. + */ listAdSenseLinks( - request?: protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IAdSenseLink[], - protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest|null, - protos.google.analytics.admin.v1alpha.IListAdSenseLinksResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAdSenseLink[], + protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest | null, + protos.google.analytics.admin.v1alpha.IListAdSenseLinksResponse, + ] + >; listAdSenseLinks( - request: protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest, - protos.google.analytics.admin.v1alpha.IListAdSenseLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAdSenseLink>): void; + request: protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest, + | protos.google.analytics.admin.v1alpha.IListAdSenseLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAdSenseLink + >, + ): void; listAdSenseLinks( - request: protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest, - protos.google.analytics.admin.v1alpha.IListAdSenseLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAdSenseLink>): void; + request: protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest, + | protos.google.analytics.admin.v1alpha.IListAdSenseLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAdSenseLink + >, + ): void; listAdSenseLinks( - request?: protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest, - protos.google.analytics.admin.v1alpha.IListAdSenseLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAdSenseLink>, - callback?: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest, - protos.google.analytics.admin.v1alpha.IListAdSenseLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAdSenseLink>): - Promise<[ - protos.google.analytics.admin.v1alpha.IAdSenseLink[], - protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest|null, - protos.google.analytics.admin.v1alpha.IListAdSenseLinksResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListAdSenseLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAdSenseLink + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest, + | protos.google.analytics.admin.v1alpha.IListAdSenseLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAdSenseLink + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IAdSenseLink[], + protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest | null, + protos.google.analytics.admin.v1alpha.IListAdSenseLinksResponse, + ] + > | 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.analytics.admin.v1alpha.IListAdSenseLinksRequest, - protos.google.analytics.admin.v1alpha.IListAdSenseLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IAdSenseLink>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest, + | protos.google.analytics.admin.v1alpha.IListAdSenseLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IAdSenseLink + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listAdSenseLinks values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -17559,211 +24778,240 @@ export class AnalyticsAdminServiceClient { this._log.info('listAdSenseLinks request %j', request); return this.innerApiCalls .listAdSenseLinks(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.IAdSenseLink[], - protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest|null, - protos.google.analytics.admin.v1alpha.IListAdSenseLinksResponse - ]) => { - this._log.info('listAdSenseLinks values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.IAdSenseLink[], + protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest | null, + protos.google.analytics.admin.v1alpha.IListAdSenseLinksResponse, + ]) => { + this._log.info('listAdSenseLinks values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listAdSenseLinks`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the parent property. - * Format: properties/{propertyId} - * Example: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token received from a previous `ListAdSenseLinks` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListAdSenseLinks` must - * match the call that provided the page token. - * @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.analytics.admin.v1alpha.AdSenseLink|AdSenseLink} 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 `listAdSenseLinksAsync()` - * 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 `listAdSenseLinks`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the parent property. + * Format: properties/{propertyId} + * Example: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token received from a previous `ListAdSenseLinks` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListAdSenseLinks` must + * match the call that provided the page token. + * @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.analytics.admin.v1alpha.AdSenseLink|AdSenseLink} 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 `listAdSenseLinksAsync()` + * 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. + */ listAdSenseLinksStream( - request?: protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest, + 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['listAdSenseLinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listAdSenseLinks stream %j', request); return this.descriptors.page.listAdSenseLinks.createStream( this.innerApiCalls.listAdSenseLinks as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listAdSenseLinks`, 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. Resource name of the parent property. - * Format: properties/{propertyId} - * Example: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token received from a previous `ListAdSenseLinks` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListAdSenseLinks` must - * match the call that provided the 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 protos.google.analytics.admin.v1alpha.AdSenseLink|AdSenseLink}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_ad_sense_links.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListAdSenseLinks_async - */ + /** + * Equivalent to `listAdSenseLinks`, 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. Resource name of the parent property. + * Format: properties/{propertyId} + * Example: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token received from a previous `ListAdSenseLinks` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListAdSenseLinks` must + * match the call that provided the 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 protos.google.analytics.admin.v1alpha.AdSenseLink|AdSenseLink}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_ad_sense_links.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListAdSenseLinks_async + */ listAdSenseLinksAsync( - request?: protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListAdSenseLinksRequest, + 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['listAdSenseLinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listAdSenseLinks iterate %j', request); return this.descriptors.page.listAdSenseLinks.asyncIterate( this.innerApiCalls['listAdSenseLinks'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists EventCreateRules on a web data stream. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/123/dataStreams/456 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListEventCreateRules` call. Provide - * this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListEventCreateRules` - * must match the call that provided the page token. - * @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.analytics.admin.v1alpha.EventCreateRule|EventCreateRule}. - * 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 `listEventCreateRulesAsync()` - * 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 EventCreateRules on a web data stream. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/123/dataStreams/456 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListEventCreateRules` call. Provide + * this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListEventCreateRules` + * must match the call that provided the page token. + * @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.analytics.admin.v1alpha.EventCreateRule|EventCreateRule}. + * 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 `listEventCreateRulesAsync()` + * 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. + */ listEventCreateRules( - request?: protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IEventCreateRule[], - protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest|null, - protos.google.analytics.admin.v1alpha.IListEventCreateRulesResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IEventCreateRule[], + protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest | null, + protos.google.analytics.admin.v1alpha.IListEventCreateRulesResponse, + ] + >; listEventCreateRules( - request: protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest, - protos.google.analytics.admin.v1alpha.IListEventCreateRulesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IEventCreateRule>): void; + request: protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest, + | protos.google.analytics.admin.v1alpha.IListEventCreateRulesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IEventCreateRule + >, + ): void; listEventCreateRules( - request: protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest, - protos.google.analytics.admin.v1alpha.IListEventCreateRulesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IEventCreateRule>): void; + request: protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest, + | protos.google.analytics.admin.v1alpha.IListEventCreateRulesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IEventCreateRule + >, + ): void; listEventCreateRules( - request?: protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest, - protos.google.analytics.admin.v1alpha.IListEventCreateRulesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IEventCreateRule>, - callback?: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest, - protos.google.analytics.admin.v1alpha.IListEventCreateRulesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IEventCreateRule>): - Promise<[ - protos.google.analytics.admin.v1alpha.IEventCreateRule[], - protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest|null, - protos.google.analytics.admin.v1alpha.IListEventCreateRulesResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListEventCreateRulesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IEventCreateRule + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest, + | protos.google.analytics.admin.v1alpha.IListEventCreateRulesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IEventCreateRule + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IEventCreateRule[], + protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest | null, + protos.google.analytics.admin.v1alpha.IListEventCreateRulesResponse, + ] + > | 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.analytics.admin.v1alpha.IListEventCreateRulesRequest, - protos.google.analytics.admin.v1alpha.IListEventCreateRulesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IEventCreateRule>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest, + | protos.google.analytics.admin.v1alpha.IListEventCreateRulesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IEventCreateRule + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listEventCreateRules values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -17772,207 +25020,236 @@ export class AnalyticsAdminServiceClient { this._log.info('listEventCreateRules request %j', request); return this.innerApiCalls .listEventCreateRules(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.IEventCreateRule[], - protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest|null, - protos.google.analytics.admin.v1alpha.IListEventCreateRulesResponse - ]) => { - this._log.info('listEventCreateRules values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.IEventCreateRule[], + protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest | null, + protos.google.analytics.admin.v1alpha.IListEventCreateRulesResponse, + ]) => { + this._log.info('listEventCreateRules values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listEventCreateRules`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/123/dataStreams/456 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListEventCreateRules` call. Provide - * this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListEventCreateRules` - * must match the call that provided the page token. - * @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.analytics.admin.v1alpha.EventCreateRule|EventCreateRule} 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 `listEventCreateRulesAsync()` - * 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 `listEventCreateRules`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/123/dataStreams/456 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListEventCreateRules` call. Provide + * this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListEventCreateRules` + * must match the call that provided the page token. + * @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.analytics.admin.v1alpha.EventCreateRule|EventCreateRule} 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 `listEventCreateRulesAsync()` + * 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. + */ listEventCreateRulesStream( - request?: protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest, + 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['listEventCreateRules']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listEventCreateRules stream %j', request); return this.descriptors.page.listEventCreateRules.createStream( this.innerApiCalls.listEventCreateRules as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listEventCreateRules`, 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. Example format: properties/123/dataStreams/456 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListEventCreateRules` call. Provide - * this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListEventCreateRules` - * must match the call that provided the 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 protos.google.analytics.admin.v1alpha.EventCreateRule|EventCreateRule}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_event_create_rules.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListEventCreateRules_async - */ + /** + * Equivalent to `listEventCreateRules`, 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. Example format: properties/123/dataStreams/456 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListEventCreateRules` call. Provide + * this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListEventCreateRules` + * must match the call that provided the 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 protos.google.analytics.admin.v1alpha.EventCreateRule|EventCreateRule}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_event_create_rules.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListEventCreateRules_async + */ listEventCreateRulesAsync( - request?: protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListEventCreateRulesRequest, + 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['listEventCreateRules']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listEventCreateRules iterate %j', request); return this.descriptors.page.listEventCreateRules.asyncIterate( this.innerApiCalls['listEventCreateRules'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists EventEditRules on a web data stream. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/123/dataStreams/456 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListEventEditRules` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListEventEditRules` - * must match the call that provided the page token. - * @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.analytics.admin.v1alpha.EventEditRule|EventEditRule}. - * 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 `listEventEditRulesAsync()` - * 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 EventEditRules on a web data stream. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/123/dataStreams/456 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListEventEditRules` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListEventEditRules` + * must match the call that provided the page token. + * @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.analytics.admin.v1alpha.EventEditRule|EventEditRule}. + * 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 `listEventEditRulesAsync()` + * 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. + */ listEventEditRules( - request?: protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IEventEditRule[], - protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest|null, - protos.google.analytics.admin.v1alpha.IListEventEditRulesResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IEventEditRule[], + protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest | null, + protos.google.analytics.admin.v1alpha.IListEventEditRulesResponse, + ] + >; listEventEditRules( - request: protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest, - protos.google.analytics.admin.v1alpha.IListEventEditRulesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IEventEditRule>): void; + request: protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest, + | protos.google.analytics.admin.v1alpha.IListEventEditRulesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IEventEditRule + >, + ): void; listEventEditRules( - request: protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest, - protos.google.analytics.admin.v1alpha.IListEventEditRulesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IEventEditRule>): void; + request: protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest, + | protos.google.analytics.admin.v1alpha.IListEventEditRulesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IEventEditRule + >, + ): void; listEventEditRules( - request?: protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest, - protos.google.analytics.admin.v1alpha.IListEventEditRulesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IEventEditRule>, - callback?: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest, - protos.google.analytics.admin.v1alpha.IListEventEditRulesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IEventEditRule>): - Promise<[ - protos.google.analytics.admin.v1alpha.IEventEditRule[], - protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest|null, - protos.google.analytics.admin.v1alpha.IListEventEditRulesResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListEventEditRulesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IEventEditRule + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest, + | protos.google.analytics.admin.v1alpha.IListEventEditRulesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IEventEditRule + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IEventEditRule[], + protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest | null, + protos.google.analytics.admin.v1alpha.IListEventEditRulesResponse, + ] + > | 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.analytics.admin.v1alpha.IListEventEditRulesRequest, - protos.google.analytics.admin.v1alpha.IListEventEditRulesResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IEventEditRule>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest, + | protos.google.analytics.admin.v1alpha.IListEventEditRulesResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IEventEditRule + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listEventEditRules values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -17981,207 +25258,236 @@ export class AnalyticsAdminServiceClient { this._log.info('listEventEditRules request %j', request); return this.innerApiCalls .listEventEditRules(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.IEventEditRule[], - protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest|null, - protos.google.analytics.admin.v1alpha.IListEventEditRulesResponse - ]) => { - this._log.info('listEventEditRules values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.IEventEditRule[], + protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest | null, + protos.google.analytics.admin.v1alpha.IListEventEditRulesResponse, + ]) => { + this._log.info('listEventEditRules values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listEventEditRules`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/123/dataStreams/456 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListEventEditRules` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListEventEditRules` - * must match the call that provided the page token. - * @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.analytics.admin.v1alpha.EventEditRule|EventEditRule} 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 `listEventEditRulesAsync()` - * 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 `listEventEditRules`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/123/dataStreams/456 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListEventEditRules` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListEventEditRules` + * must match the call that provided the page token. + * @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.analytics.admin.v1alpha.EventEditRule|EventEditRule} 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 `listEventEditRulesAsync()` + * 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. + */ listEventEditRulesStream( - request?: protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest, + 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['listEventEditRules']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listEventEditRules stream %j', request); return this.descriptors.page.listEventEditRules.createStream( this.innerApiCalls.listEventEditRules as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listEventEditRules`, 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. Example format: properties/123/dataStreams/456 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListEventEditRules` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListEventEditRules` - * must match the call that provided the 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 protos.google.analytics.admin.v1alpha.EventEditRule|EventEditRule}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_event_edit_rules.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListEventEditRules_async - */ + /** + * Equivalent to `listEventEditRules`, 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. Example format: properties/123/dataStreams/456 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListEventEditRules` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListEventEditRules` + * must match the call that provided the 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 protos.google.analytics.admin.v1alpha.EventEditRule|EventEditRule}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_event_edit_rules.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListEventEditRules_async + */ listEventEditRulesAsync( - request?: protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListEventEditRulesRequest, + 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['listEventEditRules']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listEventEditRules iterate %j', request); return this.descriptors.page.listEventEditRules.asyncIterate( this.innerApiCalls['listEventEditRules'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists CalculatedMetrics on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListCalculatedMetrics` - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListCalculatedMetrics` - * must match the call that provided the page token. - * @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.analytics.admin.v1alpha.CalculatedMetric|CalculatedMetric}. - * 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 `listCalculatedMetricsAsync()` - * 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 CalculatedMetrics on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListCalculatedMetrics` + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListCalculatedMetrics` + * must match the call that provided the page token. + * @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.analytics.admin.v1alpha.CalculatedMetric|CalculatedMetric}. + * 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 `listCalculatedMetricsAsync()` + * 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. + */ listCalculatedMetrics( - request?: protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ICalculatedMetric[], - protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest|null, - protos.google.analytics.admin.v1alpha.IListCalculatedMetricsResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICalculatedMetric[], + protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest | null, + protos.google.analytics.admin.v1alpha.IListCalculatedMetricsResponse, + ] + >; listCalculatedMetrics( - request: protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest, - protos.google.analytics.admin.v1alpha.IListCalculatedMetricsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ICalculatedMetric>): void; + request: protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest, + | protos.google.analytics.admin.v1alpha.IListCalculatedMetricsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ICalculatedMetric + >, + ): void; listCalculatedMetrics( - request: protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest, - protos.google.analytics.admin.v1alpha.IListCalculatedMetricsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ICalculatedMetric>): void; + request: protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest, + | protos.google.analytics.admin.v1alpha.IListCalculatedMetricsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ICalculatedMetric + >, + ): void; listCalculatedMetrics( - request?: protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest, - protos.google.analytics.admin.v1alpha.IListCalculatedMetricsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ICalculatedMetric>, - callback?: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest, - protos.google.analytics.admin.v1alpha.IListCalculatedMetricsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ICalculatedMetric>): - Promise<[ - protos.google.analytics.admin.v1alpha.ICalculatedMetric[], - protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest|null, - protos.google.analytics.admin.v1alpha.IListCalculatedMetricsResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListCalculatedMetricsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ICalculatedMetric + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest, + | protos.google.analytics.admin.v1alpha.IListCalculatedMetricsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ICalculatedMetric + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ICalculatedMetric[], + protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest | null, + protos.google.analytics.admin.v1alpha.IListCalculatedMetricsResponse, + ] + > | 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.analytics.admin.v1alpha.IListCalculatedMetricsRequest, - protos.google.analytics.admin.v1alpha.IListCalculatedMetricsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ICalculatedMetric>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest, + | protos.google.analytics.admin.v1alpha.IListCalculatedMetricsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ICalculatedMetric + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listCalculatedMetrics values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -18190,211 +25496,240 @@ export class AnalyticsAdminServiceClient { this._log.info('listCalculatedMetrics request %j', request); return this.innerApiCalls .listCalculatedMetrics(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.ICalculatedMetric[], - protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest|null, - protos.google.analytics.admin.v1alpha.IListCalculatedMetricsResponse - ]) => { - this._log.info('listCalculatedMetrics values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.ICalculatedMetric[], + protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest | null, + protos.google.analytics.admin.v1alpha.IListCalculatedMetricsResponse, + ]) => { + this._log.info('listCalculatedMetrics values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listCalculatedMetrics`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListCalculatedMetrics` - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListCalculatedMetrics` - * must match the call that provided the page token. - * @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.analytics.admin.v1alpha.CalculatedMetric|CalculatedMetric} 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 `listCalculatedMetricsAsync()` - * 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 `listCalculatedMetrics`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListCalculatedMetrics` + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListCalculatedMetrics` + * must match the call that provided the page token. + * @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.analytics.admin.v1alpha.CalculatedMetric|CalculatedMetric} 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 `listCalculatedMetricsAsync()` + * 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. + */ listCalculatedMetricsStream( - request?: protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest, + 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['listCalculatedMetrics']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCalculatedMetrics stream %j', request); return this.descriptors.page.listCalculatedMetrics.createStream( this.innerApiCalls.listCalculatedMetrics as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listCalculatedMetrics`, 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. Example format: properties/1234 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListCalculatedMetrics` - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListCalculatedMetrics` - * must match the call that provided the 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 protos.google.analytics.admin.v1alpha.CalculatedMetric|CalculatedMetric}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_calculated_metrics.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListCalculatedMetrics_async - */ + /** + * Equivalent to `listCalculatedMetrics`, 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. Example format: properties/1234 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListCalculatedMetrics` + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListCalculatedMetrics` + * must match the call that provided the 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 protos.google.analytics.admin.v1alpha.CalculatedMetric|CalculatedMetric}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_calculated_metrics.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListCalculatedMetrics_async + */ listCalculatedMetricsAsync( - request?: protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListCalculatedMetricsRequest, + 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['listCalculatedMetrics']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCalculatedMetrics iterate %j', request); return this.descriptors.page.listCalculatedMetrics.asyncIterate( this.innerApiCalls['listCalculatedMetrics'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists roll-up property source Links on a property. - * Only roll-up properties can have source links, so this method will throw an - * error if used on other types of properties. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the roll-up property to list roll-up property source - * links under. Format: properties/{property_id} Example: properties/1234 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListRollupPropertySourceLinks` call. Provide this to retrieve the - * subsequent page. When paginating, all other parameters provided to - * `ListRollupPropertySourceLinks` must match the call that provided the page - * token. - * @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.analytics.admin.v1alpha.RollupPropertySourceLink|RollupPropertySourceLink}. - * 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 `listRollupPropertySourceLinksAsync()` - * 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 roll-up property source Links on a property. + * Only roll-up properties can have source links, so this method will throw an + * error if used on other types of properties. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the roll-up property to list roll-up property source + * links under. Format: properties/{property_id} Example: properties/1234 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListRollupPropertySourceLinks` call. Provide this to retrieve the + * subsequent page. When paginating, all other parameters provided to + * `ListRollupPropertySourceLinks` must match the call that provided the page + * token. + * @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.analytics.admin.v1alpha.RollupPropertySourceLink|RollupPropertySourceLink}. + * 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 `listRollupPropertySourceLinksAsync()` + * 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. + */ listRollupPropertySourceLinks( - request?: protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink[], - protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest|null, - protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink[], + protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest | null, + protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksResponse, + ] + >; listRollupPropertySourceLinks( - request: protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest, - protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink>): void; + request: protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest, + | protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink + >, + ): void; listRollupPropertySourceLinks( - request: protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest, - protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink>): void; + request: protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest, + | protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink + >, + ): void; listRollupPropertySourceLinks( - request?: protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest, - protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink>, - callback?: PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest, - protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink>): - Promise<[ - protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink[], - protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest|null, - protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest, + | protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink[], + protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest | null, + protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksResponse, + ] + > | 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.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest, - protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest, + | protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listRollupPropertySourceLinks values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -18403,214 +25738,243 @@ export class AnalyticsAdminServiceClient { this._log.info('listRollupPropertySourceLinks request %j', request); return this.innerApiCalls .listRollupPropertySourceLinks(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink[], - protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest|null, - protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksResponse - ]) => { - this._log.info('listRollupPropertySourceLinks values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink[], + protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest | null, + protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksResponse, + ]) => { + this._log.info('listRollupPropertySourceLinks values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listRollupPropertySourceLinks`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the roll-up property to list roll-up property source - * links under. Format: properties/{property_id} Example: properties/1234 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListRollupPropertySourceLinks` call. Provide this to retrieve the - * subsequent page. When paginating, all other parameters provided to - * `ListRollupPropertySourceLinks` must match the call that provided the page - * token. - * @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.analytics.admin.v1alpha.RollupPropertySourceLink|RollupPropertySourceLink} 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 `listRollupPropertySourceLinksAsync()` - * 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 `listRollupPropertySourceLinks`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the roll-up property to list roll-up property source + * links under. Format: properties/{property_id} Example: properties/1234 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListRollupPropertySourceLinks` call. Provide this to retrieve the + * subsequent page. When paginating, all other parameters provided to + * `ListRollupPropertySourceLinks` must match the call that provided the page + * token. + * @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.analytics.admin.v1alpha.RollupPropertySourceLink|RollupPropertySourceLink} 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 `listRollupPropertySourceLinksAsync()` + * 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. + */ listRollupPropertySourceLinksStream( - request?: protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest, + 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['listRollupPropertySourceLinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listRollupPropertySourceLinks stream %j', request); return this.descriptors.page.listRollupPropertySourceLinks.createStream( this.innerApiCalls.listRollupPropertySourceLinks as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listRollupPropertySourceLinks`, 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 name of the roll-up property to list roll-up property source - * links under. Format: properties/{property_id} Example: properties/1234 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListRollupPropertySourceLinks` call. Provide this to retrieve the - * subsequent page. When paginating, all other parameters provided to - * `ListRollupPropertySourceLinks` must match the call that provided the 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 protos.google.analytics.admin.v1alpha.RollupPropertySourceLink|RollupPropertySourceLink}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_rollup_property_source_links.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListRollupPropertySourceLinks_async - */ + /** + * Equivalent to `listRollupPropertySourceLinks`, 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 name of the roll-up property to list roll-up property source + * links under. Format: properties/{property_id} Example: properties/1234 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListRollupPropertySourceLinks` call. Provide this to retrieve the + * subsequent page. When paginating, all other parameters provided to + * `ListRollupPropertySourceLinks` must match the call that provided the 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 protos.google.analytics.admin.v1alpha.RollupPropertySourceLink|RollupPropertySourceLink}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_rollup_property_source_links.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListRollupPropertySourceLinks_async + */ listRollupPropertySourceLinksAsync( - request?: protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListRollupPropertySourceLinksRequest, + 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['listRollupPropertySourceLinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listRollupPropertySourceLinks iterate %j', request); return this.descriptors.page.listRollupPropertySourceLinks.asyncIterate( this.innerApiCalls['listRollupPropertySourceLinks'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * List all subproperty Event Filters on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the ordinary property. - * Format: properties/property_id - * Example: properties/123 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. If unspecified, - * at most 50 resources will be returned. The maximum value is 200; (higher - * values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListSubpropertyEventFilters` call. Provide this to retrieve the subsequent - * page. When paginating, all other parameters provided to - * `ListSubpropertyEventFilters` must match the call that provided the page - * token. - * @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.analytics.admin.v1alpha.SubpropertyEventFilter|SubpropertyEventFilter}. - * 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 `listSubpropertyEventFiltersAsync()` - * 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. - */ + /** + * List all subproperty Event Filters on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the ordinary property. + * Format: properties/property_id + * Example: properties/123 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. If unspecified, + * at most 50 resources will be returned. The maximum value is 200; (higher + * values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListSubpropertyEventFilters` call. Provide this to retrieve the subsequent + * page. When paginating, all other parameters provided to + * `ListSubpropertyEventFilters` must match the call that provided the page + * token. + * @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.analytics.admin.v1alpha.SubpropertyEventFilter|SubpropertyEventFilter}. + * 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 `listSubpropertyEventFiltersAsync()` + * 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. + */ listSubpropertyEventFilters( - request?: protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter[], - protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest|null, - protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter[], + protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest | null, + protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersResponse, + ] + >; listSubpropertyEventFilters( - request: protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest, - protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter>): void; + request: protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest, + | protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter + >, + ): void; listSubpropertyEventFilters( - request: protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest, - protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter>): void; + request: protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest, + | protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter + >, + ): void; listSubpropertyEventFilters( - request?: protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest, - protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter>, - callback?: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest, - protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter>): - Promise<[ - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter[], - protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest|null, - protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest, + | protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter[], + protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest | null, + protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersResponse, + ] + > | 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.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest, - protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest, + | protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listSubpropertyEventFilters values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -18619,261 +25983,290 @@ export class AnalyticsAdminServiceClient { this._log.info('listSubpropertyEventFilters request %j', request); return this.innerApiCalls .listSubpropertyEventFilters(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter[], - protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest|null, - protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersResponse - ]) => { - this._log.info('listSubpropertyEventFilters values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter[], + protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest | null, + protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersResponse, + ]) => { + this._log.info('listSubpropertyEventFilters values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listSubpropertyEventFilters`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the ordinary property. - * Format: properties/property_id - * Example: properties/123 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. If unspecified, - * at most 50 resources will be returned. The maximum value is 200; (higher - * values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListSubpropertyEventFilters` call. Provide this to retrieve the subsequent - * page. When paginating, all other parameters provided to - * `ListSubpropertyEventFilters` must match the call that provided the page - * token. - * @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.analytics.admin.v1alpha.SubpropertyEventFilter|SubpropertyEventFilter} 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 `listSubpropertyEventFiltersAsync()` - * 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 `listSubpropertyEventFilters`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the ordinary property. + * Format: properties/property_id + * Example: properties/123 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. If unspecified, + * at most 50 resources will be returned. The maximum value is 200; (higher + * values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListSubpropertyEventFilters` call. Provide this to retrieve the subsequent + * page. When paginating, all other parameters provided to + * `ListSubpropertyEventFilters` must match the call that provided the page + * token. + * @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.analytics.admin.v1alpha.SubpropertyEventFilter|SubpropertyEventFilter} 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 `listSubpropertyEventFiltersAsync()` + * 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. + */ listSubpropertyEventFiltersStream( - request?: protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest, + 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['listSubpropertyEventFilters']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listSubpropertyEventFilters stream %j', request); return this.descriptors.page.listSubpropertyEventFilters.createStream( this.innerApiCalls.listSubpropertyEventFilters as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listSubpropertyEventFilters`, 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. Resource name of the ordinary property. - * Format: properties/property_id - * Example: properties/123 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. If unspecified, - * at most 50 resources will be returned. The maximum value is 200; (higher - * values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListSubpropertyEventFilters` call. Provide this to retrieve the subsequent - * page. When paginating, all other parameters provided to - * `ListSubpropertyEventFilters` must match the call that provided the 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 protos.google.analytics.admin.v1alpha.SubpropertyEventFilter|SubpropertyEventFilter}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_subproperty_event_filters.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListSubpropertyEventFilters_async - */ + /** + * Equivalent to `listSubpropertyEventFilters`, 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. Resource name of the ordinary property. + * Format: properties/property_id + * Example: properties/123 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. If unspecified, + * at most 50 resources will be returned. The maximum value is 200; (higher + * values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListSubpropertyEventFilters` call. Provide this to retrieve the subsequent + * page. When paginating, all other parameters provided to + * `ListSubpropertyEventFilters` must match the call that provided the 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 protos.google.analytics.admin.v1alpha.SubpropertyEventFilter|SubpropertyEventFilter}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_subproperty_event_filters.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListSubpropertyEventFilters_async + */ listSubpropertyEventFiltersAsync( - request?: protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListSubpropertyEventFiltersRequest, + 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['listSubpropertyEventFilters']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listSubpropertyEventFilters iterate %j', request); return this.descriptors.page.listSubpropertyEventFilters.asyncIterate( this.innerApiCalls['listSubpropertyEventFilters'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * List all Reporting Data Annotations on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the property. - * Format: properties/property_id - * Example: properties/123 - * @param {string} [request.filter] - * Optional. Filter that restricts which reporting data annotations under the - * parent property are listed. - * - * Supported fields are: - * - * * 'name' - * * `title` - * * `description` - * * `annotation_date` - * * `annotation_date_range` - * * `color` - * - * Additionally, this API provides the following helper functions: - * - * * annotation_duration() : the duration that this annotation marks, - * [durations](https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/duration.proto). - * expect a numeric representation of seconds followed by an `s` suffix. - * * is_annotation_in_range(start_date, end_date) : if the annotation is in - * the range specified by the `start_date` and `end_date`. The dates are in - * ISO-8601 format, for example `2031-06-28`. - * - * Supported operations: - * - * * `=` : equals - * * `!=` : not equals - * * `<` : less than - * * `>` : greater than - * * `<=` : less than or equals - * * `>=` : greater than or equals - * * `:` : has operator - * * `=~` : [regular expression](https://github.com/google/re2/wiki/Syntax) - * match - * * `!~` : [regular expression](https://github.com/google/re2/wiki/Syntax) - * does not match - * * `NOT` : Logical not - * * `AND` : Logical and - * * `OR` : Logical or - * - * Examples: - * - * 1. `title="Holiday Sale"` - * 2. `description=~"[Bb]ig [Gg]ame.*[Ss]ale"` - * 3. `is_annotation_in_range("2025-12-25", "2026-01-16") = true` - * 4. `annotation_duration() >= 172800s AND title:BOGO` - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. If unspecified, - * at most 50 resources will be returned. The maximum value is 200; (higher - * values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListReportingDataAnnotations` call. Provide this to retrieve the - * subsequent page. When paginating, all other parameters provided to - * `ListReportingDataAnnotations` must match the call that provided the page - * token. - * @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.analytics.admin.v1alpha.ReportingDataAnnotation|ReportingDataAnnotation}. - * 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 `listReportingDataAnnotationsAsync()` - * 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. - */ + /** + * List all Reporting Data Annotations on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the property. + * Format: properties/property_id + * Example: properties/123 + * @param {string} [request.filter] + * Optional. Filter that restricts which reporting data annotations under the + * parent property are listed. + * + * Supported fields are: + * + * * 'name' + * * `title` + * * `description` + * * `annotation_date` + * * `annotation_date_range` + * * `color` + * + * Additionally, this API provides the following helper functions: + * + * * annotation_duration() : the duration that this annotation marks, + * [durations](https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/duration.proto). + * expect a numeric representation of seconds followed by an `s` suffix. + * * is_annotation_in_range(start_date, end_date) : if the annotation is in + * the range specified by the `start_date` and `end_date`. The dates are in + * ISO-8601 format, for example `2031-06-28`. + * + * Supported operations: + * + * * `=` : equals + * * `!=` : not equals + * * `<` : less than + * * `>` : greater than + * * `<=` : less than or equals + * * `>=` : greater than or equals + * * `:` : has operator + * * `=~` : [regular expression](https://github.com/google/re2/wiki/Syntax) + * match + * * `!~` : [regular expression](https://github.com/google/re2/wiki/Syntax) + * does not match + * * `NOT` : Logical not + * * `AND` : Logical and + * * `OR` : Logical or + * + * Examples: + * + * 1. `title="Holiday Sale"` + * 2. `description=~"[Bb]ig [Gg]ame.*[Ss]ale"` + * 3. `is_annotation_in_range("2025-12-25", "2026-01-16") = true` + * 4. `annotation_duration() >= 172800s AND title:BOGO` + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. If unspecified, + * at most 50 resources will be returned. The maximum value is 200; (higher + * values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListReportingDataAnnotations` call. Provide this to retrieve the + * subsequent page. When paginating, all other parameters provided to + * `ListReportingDataAnnotations` must match the call that provided the page + * token. + * @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.analytics.admin.v1alpha.ReportingDataAnnotation|ReportingDataAnnotation}. + * 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 `listReportingDataAnnotationsAsync()` + * 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. + */ listReportingDataAnnotations( - request?: protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation[], - protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest|null, - protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation[], + protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest | null, + protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsResponse, + ] + >; listReportingDataAnnotations( - request: protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest, - protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation>): void; + request: protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest, + | protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation + >, + ): void; listReportingDataAnnotations( - request: protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest, - protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation>): void; + request: protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest, + | protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation + >, + ): void; listReportingDataAnnotations( - request?: protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest, - protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation>, - callback?: PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest, - protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation>): - Promise<[ - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation[], - protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest|null, - protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest, + | protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation[], + protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest | null, + protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsResponse, + ] + > | 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.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest, - protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest, + | protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listReportingDataAnnotations values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -18882,306 +26275,335 @@ export class AnalyticsAdminServiceClient { this._log.info('listReportingDataAnnotations request %j', request); return this.innerApiCalls .listReportingDataAnnotations(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.IReportingDataAnnotation[], - protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest|null, - protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsResponse - ]) => { - this._log.info('listReportingDataAnnotations values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.IReportingDataAnnotation[], + protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest | null, + protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsResponse, + ]) => { + this._log.info('listReportingDataAnnotations values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listReportingDataAnnotations`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the property. - * Format: properties/property_id - * Example: properties/123 - * @param {string} [request.filter] - * Optional. Filter that restricts which reporting data annotations under the - * parent property are listed. - * - * Supported fields are: - * - * * 'name' - * * `title` - * * `description` - * * `annotation_date` - * * `annotation_date_range` - * * `color` - * - * Additionally, this API provides the following helper functions: - * - * * annotation_duration() : the duration that this annotation marks, - * [durations](https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/duration.proto). - * expect a numeric representation of seconds followed by an `s` suffix. - * * is_annotation_in_range(start_date, end_date) : if the annotation is in - * the range specified by the `start_date` and `end_date`. The dates are in - * ISO-8601 format, for example `2031-06-28`. - * - * Supported operations: - * - * * `=` : equals - * * `!=` : not equals - * * `<` : less than - * * `>` : greater than - * * `<=` : less than or equals - * * `>=` : greater than or equals - * * `:` : has operator - * * `=~` : [regular expression](https://github.com/google/re2/wiki/Syntax) - * match - * * `!~` : [regular expression](https://github.com/google/re2/wiki/Syntax) - * does not match - * * `NOT` : Logical not - * * `AND` : Logical and - * * `OR` : Logical or - * - * Examples: - * - * 1. `title="Holiday Sale"` - * 2. `description=~"[Bb]ig [Gg]ame.*[Ss]ale"` - * 3. `is_annotation_in_range("2025-12-25", "2026-01-16") = true` - * 4. `annotation_duration() >= 172800s AND title:BOGO` - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. If unspecified, - * at most 50 resources will be returned. The maximum value is 200; (higher - * values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListReportingDataAnnotations` call. Provide this to retrieve the - * subsequent page. When paginating, all other parameters provided to - * `ListReportingDataAnnotations` must match the call that provided the page - * token. - * @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.analytics.admin.v1alpha.ReportingDataAnnotation|ReportingDataAnnotation} 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 `listReportingDataAnnotationsAsync()` - * 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 `listReportingDataAnnotations`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the property. + * Format: properties/property_id + * Example: properties/123 + * @param {string} [request.filter] + * Optional. Filter that restricts which reporting data annotations under the + * parent property are listed. + * + * Supported fields are: + * + * * 'name' + * * `title` + * * `description` + * * `annotation_date` + * * `annotation_date_range` + * * `color` + * + * Additionally, this API provides the following helper functions: + * + * * annotation_duration() : the duration that this annotation marks, + * [durations](https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/duration.proto). + * expect a numeric representation of seconds followed by an `s` suffix. + * * is_annotation_in_range(start_date, end_date) : if the annotation is in + * the range specified by the `start_date` and `end_date`. The dates are in + * ISO-8601 format, for example `2031-06-28`. + * + * Supported operations: + * + * * `=` : equals + * * `!=` : not equals + * * `<` : less than + * * `>` : greater than + * * `<=` : less than or equals + * * `>=` : greater than or equals + * * `:` : has operator + * * `=~` : [regular expression](https://github.com/google/re2/wiki/Syntax) + * match + * * `!~` : [regular expression](https://github.com/google/re2/wiki/Syntax) + * does not match + * * `NOT` : Logical not + * * `AND` : Logical and + * * `OR` : Logical or + * + * Examples: + * + * 1. `title="Holiday Sale"` + * 2. `description=~"[Bb]ig [Gg]ame.*[Ss]ale"` + * 3. `is_annotation_in_range("2025-12-25", "2026-01-16") = true` + * 4. `annotation_duration() >= 172800s AND title:BOGO` + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. If unspecified, + * at most 50 resources will be returned. The maximum value is 200; (higher + * values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListReportingDataAnnotations` call. Provide this to retrieve the + * subsequent page. When paginating, all other parameters provided to + * `ListReportingDataAnnotations` must match the call that provided the page + * token. + * @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.analytics.admin.v1alpha.ReportingDataAnnotation|ReportingDataAnnotation} 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 `listReportingDataAnnotationsAsync()` + * 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. + */ listReportingDataAnnotationsStream( - request?: protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest, + 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['listReportingDataAnnotations']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listReportingDataAnnotations stream %j', request); return this.descriptors.page.listReportingDataAnnotations.createStream( this.innerApiCalls.listReportingDataAnnotations as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listReportingDataAnnotations`, 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. Resource name of the property. - * Format: properties/property_id - * Example: properties/123 - * @param {string} [request.filter] - * Optional. Filter that restricts which reporting data annotations under the - * parent property are listed. - * - * Supported fields are: - * - * * 'name' - * * `title` - * * `description` - * * `annotation_date` - * * `annotation_date_range` - * * `color` - * - * Additionally, this API provides the following helper functions: - * - * * annotation_duration() : the duration that this annotation marks, - * [durations](https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/duration.proto). - * expect a numeric representation of seconds followed by an `s` suffix. - * * is_annotation_in_range(start_date, end_date) : if the annotation is in - * the range specified by the `start_date` and `end_date`. The dates are in - * ISO-8601 format, for example `2031-06-28`. - * - * Supported operations: - * - * * `=` : equals - * * `!=` : not equals - * * `<` : less than - * * `>` : greater than - * * `<=` : less than or equals - * * `>=` : greater than or equals - * * `:` : has operator - * * `=~` : [regular expression](https://github.com/google/re2/wiki/Syntax) - * match - * * `!~` : [regular expression](https://github.com/google/re2/wiki/Syntax) - * does not match - * * `NOT` : Logical not - * * `AND` : Logical and - * * `OR` : Logical or - * - * Examples: - * - * 1. `title="Holiday Sale"` - * 2. `description=~"[Bb]ig [Gg]ame.*[Ss]ale"` - * 3. `is_annotation_in_range("2025-12-25", "2026-01-16") = true` - * 4. `annotation_duration() >= 172800s AND title:BOGO` - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. If unspecified, - * at most 50 resources will be returned. The maximum value is 200; (higher - * values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListReportingDataAnnotations` call. Provide this to retrieve the - * subsequent page. When paginating, all other parameters provided to - * `ListReportingDataAnnotations` must match the call that provided the 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 protos.google.analytics.admin.v1alpha.ReportingDataAnnotation|ReportingDataAnnotation}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_reporting_data_annotations.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListReportingDataAnnotations_async - */ + /** + * Equivalent to `listReportingDataAnnotations`, 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. Resource name of the property. + * Format: properties/property_id + * Example: properties/123 + * @param {string} [request.filter] + * Optional. Filter that restricts which reporting data annotations under the + * parent property are listed. + * + * Supported fields are: + * + * * 'name' + * * `title` + * * `description` + * * `annotation_date` + * * `annotation_date_range` + * * `color` + * + * Additionally, this API provides the following helper functions: + * + * * annotation_duration() : the duration that this annotation marks, + * [durations](https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/duration.proto). + * expect a numeric representation of seconds followed by an `s` suffix. + * * is_annotation_in_range(start_date, end_date) : if the annotation is in + * the range specified by the `start_date` and `end_date`. The dates are in + * ISO-8601 format, for example `2031-06-28`. + * + * Supported operations: + * + * * `=` : equals + * * `!=` : not equals + * * `<` : less than + * * `>` : greater than + * * `<=` : less than or equals + * * `>=` : greater than or equals + * * `:` : has operator + * * `=~` : [regular expression](https://github.com/google/re2/wiki/Syntax) + * match + * * `!~` : [regular expression](https://github.com/google/re2/wiki/Syntax) + * does not match + * * `NOT` : Logical not + * * `AND` : Logical and + * * `OR` : Logical or + * + * Examples: + * + * 1. `title="Holiday Sale"` + * 2. `description=~"[Bb]ig [Gg]ame.*[Ss]ale"` + * 3. `is_annotation_in_range("2025-12-25", "2026-01-16") = true` + * 4. `annotation_duration() >= 172800s AND title:BOGO` + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. If unspecified, + * at most 50 resources will be returned. The maximum value is 200; (higher + * values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListReportingDataAnnotations` call. Provide this to retrieve the + * subsequent page. When paginating, all other parameters provided to + * `ListReportingDataAnnotations` must match the call that provided the 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 protos.google.analytics.admin.v1alpha.ReportingDataAnnotation|ReportingDataAnnotation}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_reporting_data_annotations.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListReportingDataAnnotations_async + */ listReportingDataAnnotationsAsync( - request?: protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListReportingDataAnnotationsRequest, + 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['listReportingDataAnnotations']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listReportingDataAnnotations iterate %j', request); return this.descriptors.page.listReportingDataAnnotations.asyncIterate( this.innerApiCalls['listReportingDataAnnotations'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * List all `SubpropertySyncConfig` resources for a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the property. - * Format: properties/property_id - * Example: properties/123 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. If unspecified, - * at most 50 resources will be returned. The maximum value is 200; (higher - * values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListSubpropertySyncConfig` call. Provide this to retrieve the subsequent - * page. When paginating, all other parameters provided to - * `ListSubpropertySyncConfig` must match the call that provided the page - * token. - * @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.analytics.admin.v1alpha.SubpropertySyncConfig|SubpropertySyncConfig}. - * 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 `listSubpropertySyncConfigsAsync()` - * 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. - */ + /** + * List all `SubpropertySyncConfig` resources for a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the property. + * Format: properties/property_id + * Example: properties/123 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. If unspecified, + * at most 50 resources will be returned. The maximum value is 200; (higher + * values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListSubpropertySyncConfig` call. Provide this to retrieve the subsequent + * page. When paginating, all other parameters provided to + * `ListSubpropertySyncConfig` must match the call that provided the page + * token. + * @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.analytics.admin.v1alpha.SubpropertySyncConfig|SubpropertySyncConfig}. + * 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 `listSubpropertySyncConfigsAsync()` + * 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. + */ listSubpropertySyncConfigs( - request?: protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig[], - protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest|null, - protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsResponse - ]>; + request?: protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig[], + protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest | null, + protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsResponse, + ] + >; listSubpropertySyncConfigs( - request: protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest, - protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig>): void; + request: protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest, + | protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig + >, + ): void; listSubpropertySyncConfigs( - request: protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest, - protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig>): void; + request: protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest, + | protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig + >, + ): void; listSubpropertySyncConfigs( - request?: protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest, - protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig>, - callback?: PaginationCallback< - protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest, - protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig>): - Promise<[ - protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig[], - protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest|null, - protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsResponse - ]>|void { + | protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest, + | protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig + >, + ): Promise< + [ + protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig[], + protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest | null, + protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsResponse, + ] + > | 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.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest, - protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsResponse|null|undefined, - protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest, + | protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsResponse + | null + | undefined, + protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listSubpropertySyncConfigs values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -19190,124 +26612,128 @@ export class AnalyticsAdminServiceClient { this._log.info('listSubpropertySyncConfigs request %j', request); return this.innerApiCalls .listSubpropertySyncConfigs(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig[], - protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest|null, - protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsResponse - ]) => { - this._log.info('listSubpropertySyncConfigs values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig[], + protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest | null, + protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsResponse, + ]) => { + this._log.info('listSubpropertySyncConfigs values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listSubpropertySyncConfigs`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Resource name of the property. - * Format: properties/property_id - * Example: properties/123 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. If unspecified, - * at most 50 resources will be returned. The maximum value is 200; (higher - * values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListSubpropertySyncConfig` call. Provide this to retrieve the subsequent - * page. When paginating, all other parameters provided to - * `ListSubpropertySyncConfig` must match the call that provided the page - * token. - * @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.analytics.admin.v1alpha.SubpropertySyncConfig|SubpropertySyncConfig} 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 `listSubpropertySyncConfigsAsync()` - * 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 `listSubpropertySyncConfigs`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Resource name of the property. + * Format: properties/property_id + * Example: properties/123 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. If unspecified, + * at most 50 resources will be returned. The maximum value is 200; (higher + * values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListSubpropertySyncConfig` call. Provide this to retrieve the subsequent + * page. When paginating, all other parameters provided to + * `ListSubpropertySyncConfig` must match the call that provided the page + * token. + * @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.analytics.admin.v1alpha.SubpropertySyncConfig|SubpropertySyncConfig} 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 `listSubpropertySyncConfigsAsync()` + * 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. + */ listSubpropertySyncConfigsStream( - request?: protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest, + 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['listSubpropertySyncConfigs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listSubpropertySyncConfigs stream %j', request); return this.descriptors.page.listSubpropertySyncConfigs.createStream( this.innerApiCalls.listSubpropertySyncConfigs as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listSubpropertySyncConfigs`, 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. Resource name of the property. - * Format: properties/property_id - * Example: properties/123 - * @param {number} [request.pageSize] - * Optional. The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. If unspecified, - * at most 50 resources will be returned. The maximum value is 200; (higher - * values will be coerced to the maximum) - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListSubpropertySyncConfig` call. Provide this to retrieve the subsequent - * page. When paginating, all other parameters provided to - * `ListSubpropertySyncConfig` must match the call that provided the 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 protos.google.analytics.admin.v1alpha.SubpropertySyncConfig|SubpropertySyncConfig}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_subproperty_sync_configs.js - * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListSubpropertySyncConfigs_async - */ + /** + * Equivalent to `listSubpropertySyncConfigs`, 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. Resource name of the property. + * Format: properties/property_id + * Example: properties/123 + * @param {number} [request.pageSize] + * Optional. The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. If unspecified, + * at most 50 resources will be returned. The maximum value is 200; (higher + * values will be coerced to the maximum) + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListSubpropertySyncConfig` call. Provide this to retrieve the subsequent + * page. When paginating, all other parameters provided to + * `ListSubpropertySyncConfig` must match the call that provided the 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 protos.google.analytics.admin.v1alpha.SubpropertySyncConfig|SubpropertySyncConfig}. 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 include:samples/generated/v1alpha/analytics_admin_service.list_subproperty_sync_configs.js + * region_tag:analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListSubpropertySyncConfigs_async + */ listSubpropertySyncConfigsAsync( - request?: protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1alpha.IListSubpropertySyncConfigsRequest, + 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['listSubpropertySyncConfigs']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listSubpropertySyncConfigs iterate %j', request); return this.descriptors.page.listSubpropertySyncConfigs.asyncIterate( this.innerApiCalls['listSubpropertySyncConfigs'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -19320,7 +26746,7 @@ export class AnalyticsAdminServiceClient { * @param {string} account * @returns {string} Resource name string. */ - accountPath(account:string) { + accountPath(account: string) { return this.pathTemplates.accountPathTemplate.render({ account: account, }); @@ -19344,7 +26770,7 @@ export class AnalyticsAdminServiceClient { * @param {string} access_binding * @returns {string} Resource name string. */ - accountAccessBindingPath(account:string,accessBinding:string) { + accountAccessBindingPath(account: string, accessBinding: string) { return this.pathTemplates.accountAccessBindingPathTemplate.render({ account: account, access_binding: accessBinding, @@ -19359,7 +26785,9 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the account. */ matchAccountFromAccountAccessBindingName(accountAccessBindingName: string) { - return this.pathTemplates.accountAccessBindingPathTemplate.match(accountAccessBindingName).account; + return this.pathTemplates.accountAccessBindingPathTemplate.match( + accountAccessBindingName, + ).account; } /** @@ -19369,8 +26797,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing account_access_binding resource. * @returns {string} A string representing the access_binding. */ - matchAccessBindingFromAccountAccessBindingName(accountAccessBindingName: string) { - return this.pathTemplates.accountAccessBindingPathTemplate.match(accountAccessBindingName).access_binding; + matchAccessBindingFromAccountAccessBindingName( + accountAccessBindingName: string, + ) { + return this.pathTemplates.accountAccessBindingPathTemplate.match( + accountAccessBindingName, + ).access_binding; } /** @@ -19379,7 +26811,7 @@ export class AnalyticsAdminServiceClient { * @param {string} account_summary * @returns {string} Resource name string. */ - accountSummaryPath(accountSummary:string) { + accountSummaryPath(accountSummary: string) { return this.pathTemplates.accountSummaryPathTemplate.render({ account_summary: accountSummary, }); @@ -19393,7 +26825,9 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the account_summary. */ matchAccountSummaryFromAccountSummaryName(accountSummaryName: string) { - return this.pathTemplates.accountSummaryPathTemplate.match(accountSummaryName).account_summary; + return this.pathTemplates.accountSummaryPathTemplate.match( + accountSummaryName, + ).account_summary; } /** @@ -19403,7 +26837,7 @@ export class AnalyticsAdminServiceClient { * @param {string} adsense_link * @returns {string} Resource name string. */ - adSenseLinkPath(property:string,adsenseLink:string) { + adSenseLinkPath(property: string, adsenseLink: string) { return this.pathTemplates.adSenseLinkPathTemplate.render({ property: property, adsense_link: adsenseLink, @@ -19418,7 +26852,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the property. */ matchPropertyFromAdSenseLinkName(adSenseLinkName: string) { - return this.pathTemplates.adSenseLinkPathTemplate.match(adSenseLinkName).property; + return this.pathTemplates.adSenseLinkPathTemplate.match(adSenseLinkName) + .property; } /** @@ -19429,7 +26864,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the adsense_link. */ matchAdsenseLinkFromAdSenseLinkName(adSenseLinkName: string) { - return this.pathTemplates.adSenseLinkPathTemplate.match(adSenseLinkName).adsense_link; + return this.pathTemplates.adSenseLinkPathTemplate.match(adSenseLinkName) + .adsense_link; } /** @@ -19438,7 +26874,7 @@ export class AnalyticsAdminServiceClient { * @param {string} property * @returns {string} Resource name string. */ - attributionSettingsPath(property:string) { + attributionSettingsPath(property: string) { return this.pathTemplates.attributionSettingsPathTemplate.render({ property: property, }); @@ -19452,7 +26888,9 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the property. */ matchPropertyFromAttributionSettingsName(attributionSettingsName: string) { - return this.pathTemplates.attributionSettingsPathTemplate.match(attributionSettingsName).property; + return this.pathTemplates.attributionSettingsPathTemplate.match( + attributionSettingsName, + ).property; } /** @@ -19462,7 +26900,7 @@ export class AnalyticsAdminServiceClient { * @param {string} audience * @returns {string} Resource name string. */ - audiencePath(property:string,audience:string) { + audiencePath(property: string, audience: string) { return this.pathTemplates.audiencePathTemplate.render({ property: property, audience: audience, @@ -19498,7 +26936,7 @@ export class AnalyticsAdminServiceClient { * @param {string} bigquery_link * @returns {string} Resource name string. */ - bigQueryLinkPath(property:string,bigqueryLink:string) { + bigQueryLinkPath(property: string, bigqueryLink: string) { return this.pathTemplates.bigQueryLinkPathTemplate.render({ property: property, bigquery_link: bigqueryLink, @@ -19513,7 +26951,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the property. */ matchPropertyFromBigQueryLinkName(bigQueryLinkName: string) { - return this.pathTemplates.bigQueryLinkPathTemplate.match(bigQueryLinkName).property; + return this.pathTemplates.bigQueryLinkPathTemplate.match(bigQueryLinkName) + .property; } /** @@ -19524,7 +26963,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the bigquery_link. */ matchBigqueryLinkFromBigQueryLinkName(bigQueryLinkName: string) { - return this.pathTemplates.bigQueryLinkPathTemplate.match(bigQueryLinkName).bigquery_link; + return this.pathTemplates.bigQueryLinkPathTemplate.match(bigQueryLinkName) + .bigquery_link; } /** @@ -19534,7 +26974,7 @@ export class AnalyticsAdminServiceClient { * @param {string} calculated_metric * @returns {string} Resource name string. */ - calculatedMetricPath(property:string,calculatedMetric:string) { + calculatedMetricPath(property: string, calculatedMetric: string) { return this.pathTemplates.calculatedMetricPathTemplate.render({ property: property, calculated_metric: calculatedMetric, @@ -19549,7 +26989,9 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the property. */ matchPropertyFromCalculatedMetricName(calculatedMetricName: string) { - return this.pathTemplates.calculatedMetricPathTemplate.match(calculatedMetricName).property; + return this.pathTemplates.calculatedMetricPathTemplate.match( + calculatedMetricName, + ).property; } /** @@ -19560,7 +27002,9 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the calculated_metric. */ matchCalculatedMetricFromCalculatedMetricName(calculatedMetricName: string) { - return this.pathTemplates.calculatedMetricPathTemplate.match(calculatedMetricName).calculated_metric; + return this.pathTemplates.calculatedMetricPathTemplate.match( + calculatedMetricName, + ).calculated_metric; } /** @@ -19570,7 +27014,7 @@ export class AnalyticsAdminServiceClient { * @param {string} channel_group * @returns {string} Resource name string. */ - channelGroupPath(property:string,channelGroup:string) { + channelGroupPath(property: string, channelGroup: string) { return this.pathTemplates.channelGroupPathTemplate.render({ property: property, channel_group: channelGroup, @@ -19585,7 +27029,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the property. */ matchPropertyFromChannelGroupName(channelGroupName: string) { - return this.pathTemplates.channelGroupPathTemplate.match(channelGroupName).property; + return this.pathTemplates.channelGroupPathTemplate.match(channelGroupName) + .property; } /** @@ -19596,7 +27041,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the channel_group. */ matchChannelGroupFromChannelGroupName(channelGroupName: string) { - return this.pathTemplates.channelGroupPathTemplate.match(channelGroupName).channel_group; + return this.pathTemplates.channelGroupPathTemplate.match(channelGroupName) + .channel_group; } /** @@ -19606,7 +27052,7 @@ export class AnalyticsAdminServiceClient { * @param {string} conversion_event * @returns {string} Resource name string. */ - conversionEventPath(property:string,conversionEvent:string) { + conversionEventPath(property: string, conversionEvent: string) { return this.pathTemplates.conversionEventPathTemplate.render({ property: property, conversion_event: conversionEvent, @@ -19621,7 +27067,9 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the property. */ matchPropertyFromConversionEventName(conversionEventName: string) { - return this.pathTemplates.conversionEventPathTemplate.match(conversionEventName).property; + return this.pathTemplates.conversionEventPathTemplate.match( + conversionEventName, + ).property; } /** @@ -19632,7 +27080,9 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the conversion_event. */ matchConversionEventFromConversionEventName(conversionEventName: string) { - return this.pathTemplates.conversionEventPathTemplate.match(conversionEventName).conversion_event; + return this.pathTemplates.conversionEventPathTemplate.match( + conversionEventName, + ).conversion_event; } /** @@ -19642,7 +27092,7 @@ export class AnalyticsAdminServiceClient { * @param {string} custom_dimension * @returns {string} Resource name string. */ - customDimensionPath(property:string,customDimension:string) { + customDimensionPath(property: string, customDimension: string) { return this.pathTemplates.customDimensionPathTemplate.render({ property: property, custom_dimension: customDimension, @@ -19657,7 +27107,9 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the property. */ matchPropertyFromCustomDimensionName(customDimensionName: string) { - return this.pathTemplates.customDimensionPathTemplate.match(customDimensionName).property; + return this.pathTemplates.customDimensionPathTemplate.match( + customDimensionName, + ).property; } /** @@ -19668,7 +27120,9 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the custom_dimension. */ matchCustomDimensionFromCustomDimensionName(customDimensionName: string) { - return this.pathTemplates.customDimensionPathTemplate.match(customDimensionName).custom_dimension; + return this.pathTemplates.customDimensionPathTemplate.match( + customDimensionName, + ).custom_dimension; } /** @@ -19678,7 +27132,7 @@ export class AnalyticsAdminServiceClient { * @param {string} custom_metric * @returns {string} Resource name string. */ - customMetricPath(property:string,customMetric:string) { + customMetricPath(property: string, customMetric: string) { return this.pathTemplates.customMetricPathTemplate.render({ property: property, custom_metric: customMetric, @@ -19693,7 +27147,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the property. */ matchPropertyFromCustomMetricName(customMetricName: string) { - return this.pathTemplates.customMetricPathTemplate.match(customMetricName).property; + return this.pathTemplates.customMetricPathTemplate.match(customMetricName) + .property; } /** @@ -19704,7 +27159,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the custom_metric. */ matchCustomMetricFromCustomMetricName(customMetricName: string) { - return this.pathTemplates.customMetricPathTemplate.match(customMetricName).custom_metric; + return this.pathTemplates.customMetricPathTemplate.match(customMetricName) + .custom_metric; } /** @@ -19714,7 +27170,7 @@ export class AnalyticsAdminServiceClient { * @param {string} data_stream * @returns {string} Resource name string. */ - dataRedactionSettingsPath(property:string,dataStream:string) { + dataRedactionSettingsPath(property: string, dataStream: string) { return this.pathTemplates.dataRedactionSettingsPathTemplate.render({ property: property, data_stream: dataStream, @@ -19728,8 +27184,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing DataRedactionSettings resource. * @returns {string} A string representing the property. */ - matchPropertyFromDataRedactionSettingsName(dataRedactionSettingsName: string) { - return this.pathTemplates.dataRedactionSettingsPathTemplate.match(dataRedactionSettingsName).property; + matchPropertyFromDataRedactionSettingsName( + dataRedactionSettingsName: string, + ) { + return this.pathTemplates.dataRedactionSettingsPathTemplate.match( + dataRedactionSettingsName, + ).property; } /** @@ -19739,8 +27199,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing DataRedactionSettings resource. * @returns {string} A string representing the data_stream. */ - matchDataStreamFromDataRedactionSettingsName(dataRedactionSettingsName: string) { - return this.pathTemplates.dataRedactionSettingsPathTemplate.match(dataRedactionSettingsName).data_stream; + matchDataStreamFromDataRedactionSettingsName( + dataRedactionSettingsName: string, + ) { + return this.pathTemplates.dataRedactionSettingsPathTemplate.match( + dataRedactionSettingsName, + ).data_stream; } /** @@ -19749,7 +27213,7 @@ export class AnalyticsAdminServiceClient { * @param {string} property * @returns {string} Resource name string. */ - dataRetentionSettingsPath(property:string) { + dataRetentionSettingsPath(property: string) { return this.pathTemplates.dataRetentionSettingsPathTemplate.render({ property: property, }); @@ -19762,8 +27226,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing DataRetentionSettings resource. * @returns {string} A string representing the property. */ - matchPropertyFromDataRetentionSettingsName(dataRetentionSettingsName: string) { - return this.pathTemplates.dataRetentionSettingsPathTemplate.match(dataRetentionSettingsName).property; + matchPropertyFromDataRetentionSettingsName( + dataRetentionSettingsName: string, + ) { + return this.pathTemplates.dataRetentionSettingsPathTemplate.match( + dataRetentionSettingsName, + ).property; } /** @@ -19772,7 +27240,7 @@ export class AnalyticsAdminServiceClient { * @param {string} account * @returns {string} Resource name string. */ - dataSharingSettingsPath(account:string) { + dataSharingSettingsPath(account: string) { return this.pathTemplates.dataSharingSettingsPathTemplate.render({ account: account, }); @@ -19786,7 +27254,9 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the account. */ matchAccountFromDataSharingSettingsName(dataSharingSettingsName: string) { - return this.pathTemplates.dataSharingSettingsPathTemplate.match(dataSharingSettingsName).account; + return this.pathTemplates.dataSharingSettingsPathTemplate.match( + dataSharingSettingsName, + ).account; } /** @@ -19796,7 +27266,7 @@ export class AnalyticsAdminServiceClient { * @param {string} data_stream * @returns {string} Resource name string. */ - dataStreamPath(property:string,dataStream:string) { + dataStreamPath(property: string, dataStream: string) { return this.pathTemplates.dataStreamPathTemplate.render({ property: property, data_stream: dataStream, @@ -19811,7 +27281,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the property. */ matchPropertyFromDataStreamName(dataStreamName: string) { - return this.pathTemplates.dataStreamPathTemplate.match(dataStreamName).property; + return this.pathTemplates.dataStreamPathTemplate.match(dataStreamName) + .property; } /** @@ -19822,7 +27293,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the data_stream. */ matchDataStreamFromDataStreamName(dataStreamName: string) { - return this.pathTemplates.dataStreamPathTemplate.match(dataStreamName).data_stream; + return this.pathTemplates.dataStreamPathTemplate.match(dataStreamName) + .data_stream; } /** @@ -19831,7 +27303,7 @@ export class AnalyticsAdminServiceClient { * @param {string} property * @returns {string} Resource name string. */ - displayVideo360AdvertiserLinkPath(property:string) { + displayVideo360AdvertiserLinkPath(property: string) { return this.pathTemplates.displayVideo360AdvertiserLinkPathTemplate.render({ property: property, }); @@ -19844,8 +27316,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing DisplayVideo360AdvertiserLink resource. * @returns {string} A string representing the property. */ - matchPropertyFromDisplayVideo360AdvertiserLinkName(displayVideo360AdvertiserLinkName: string) { - return this.pathTemplates.displayVideo360AdvertiserLinkPathTemplate.match(displayVideo360AdvertiserLinkName).property; + matchPropertyFromDisplayVideo360AdvertiserLinkName( + displayVideo360AdvertiserLinkName: string, + ) { + return this.pathTemplates.displayVideo360AdvertiserLinkPathTemplate.match( + displayVideo360AdvertiserLinkName, + ).property; } /** @@ -19854,10 +27330,12 @@ export class AnalyticsAdminServiceClient { * @param {string} property * @returns {string} Resource name string. */ - displayVideo360AdvertiserLinkProposalPath(property:string) { - return this.pathTemplates.displayVideo360AdvertiserLinkProposalPathTemplate.render({ - property: property, - }); + displayVideo360AdvertiserLinkProposalPath(property: string) { + return this.pathTemplates.displayVideo360AdvertiserLinkProposalPathTemplate.render( + { + property: property, + }, + ); } /** @@ -19867,8 +27345,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing DisplayVideo360AdvertiserLinkProposal resource. * @returns {string} A string representing the property. */ - matchPropertyFromDisplayVideo360AdvertiserLinkProposalName(displayVideo360AdvertiserLinkProposalName: string) { - return this.pathTemplates.displayVideo360AdvertiserLinkProposalPathTemplate.match(displayVideo360AdvertiserLinkProposalName).property; + matchPropertyFromDisplayVideo360AdvertiserLinkProposalName( + displayVideo360AdvertiserLinkProposalName: string, + ) { + return this.pathTemplates.displayVideo360AdvertiserLinkProposalPathTemplate.match( + displayVideo360AdvertiserLinkProposalName, + ).property; } /** @@ -19878,7 +27360,7 @@ export class AnalyticsAdminServiceClient { * @param {string} data_stream * @returns {string} Resource name string. */ - enhancedMeasurementSettingsPath(property:string,dataStream:string) { + enhancedMeasurementSettingsPath(property: string, dataStream: string) { return this.pathTemplates.enhancedMeasurementSettingsPathTemplate.render({ property: property, data_stream: dataStream, @@ -19892,8 +27374,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing EnhancedMeasurementSettings resource. * @returns {string} A string representing the property. */ - matchPropertyFromEnhancedMeasurementSettingsName(enhancedMeasurementSettingsName: string) { - return this.pathTemplates.enhancedMeasurementSettingsPathTemplate.match(enhancedMeasurementSettingsName).property; + matchPropertyFromEnhancedMeasurementSettingsName( + enhancedMeasurementSettingsName: string, + ) { + return this.pathTemplates.enhancedMeasurementSettingsPathTemplate.match( + enhancedMeasurementSettingsName, + ).property; } /** @@ -19903,8 +27389,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing EnhancedMeasurementSettings resource. * @returns {string} A string representing the data_stream. */ - matchDataStreamFromEnhancedMeasurementSettingsName(enhancedMeasurementSettingsName: string) { - return this.pathTemplates.enhancedMeasurementSettingsPathTemplate.match(enhancedMeasurementSettingsName).data_stream; + matchDataStreamFromEnhancedMeasurementSettingsName( + enhancedMeasurementSettingsName: string, + ) { + return this.pathTemplates.enhancedMeasurementSettingsPathTemplate.match( + enhancedMeasurementSettingsName, + ).data_stream; } /** @@ -19915,7 +27405,11 @@ export class AnalyticsAdminServiceClient { * @param {string} event_create_rule * @returns {string} Resource name string. */ - eventCreateRulePath(property:string,dataStream:string,eventCreateRule:string) { + eventCreateRulePath( + property: string, + dataStream: string, + eventCreateRule: string, + ) { return this.pathTemplates.eventCreateRulePathTemplate.render({ property: property, data_stream: dataStream, @@ -19931,7 +27425,9 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the property. */ matchPropertyFromEventCreateRuleName(eventCreateRuleName: string) { - return this.pathTemplates.eventCreateRulePathTemplate.match(eventCreateRuleName).property; + return this.pathTemplates.eventCreateRulePathTemplate.match( + eventCreateRuleName, + ).property; } /** @@ -19942,7 +27438,9 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the data_stream. */ matchDataStreamFromEventCreateRuleName(eventCreateRuleName: string) { - return this.pathTemplates.eventCreateRulePathTemplate.match(eventCreateRuleName).data_stream; + return this.pathTemplates.eventCreateRulePathTemplate.match( + eventCreateRuleName, + ).data_stream; } /** @@ -19953,7 +27451,9 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the event_create_rule. */ matchEventCreateRuleFromEventCreateRuleName(eventCreateRuleName: string) { - return this.pathTemplates.eventCreateRulePathTemplate.match(eventCreateRuleName).event_create_rule; + return this.pathTemplates.eventCreateRulePathTemplate.match( + eventCreateRuleName, + ).event_create_rule; } /** @@ -19964,7 +27464,11 @@ export class AnalyticsAdminServiceClient { * @param {string} event_edit_rule * @returns {string} Resource name string. */ - eventEditRulePath(property:string,dataStream:string,eventEditRule:string) { + eventEditRulePath( + property: string, + dataStream: string, + eventEditRule: string, + ) { return this.pathTemplates.eventEditRulePathTemplate.render({ property: property, data_stream: dataStream, @@ -19980,7 +27484,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the property. */ matchPropertyFromEventEditRuleName(eventEditRuleName: string) { - return this.pathTemplates.eventEditRulePathTemplate.match(eventEditRuleName).property; + return this.pathTemplates.eventEditRulePathTemplate.match(eventEditRuleName) + .property; } /** @@ -19991,7 +27496,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the data_stream. */ matchDataStreamFromEventEditRuleName(eventEditRuleName: string) { - return this.pathTemplates.eventEditRulePathTemplate.match(eventEditRuleName).data_stream; + return this.pathTemplates.eventEditRulePathTemplate.match(eventEditRuleName) + .data_stream; } /** @@ -20002,7 +27508,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the event_edit_rule. */ matchEventEditRuleFromEventEditRuleName(eventEditRuleName: string) { - return this.pathTemplates.eventEditRulePathTemplate.match(eventEditRuleName).event_edit_rule; + return this.pathTemplates.eventEditRulePathTemplate.match(eventEditRuleName) + .event_edit_rule; } /** @@ -20012,7 +27519,7 @@ export class AnalyticsAdminServiceClient { * @param {string} expanded_data_set * @returns {string} Resource name string. */ - expandedDataSetPath(property:string,expandedDataSet:string) { + expandedDataSetPath(property: string, expandedDataSet: string) { return this.pathTemplates.expandedDataSetPathTemplate.render({ property: property, expanded_data_set: expandedDataSet, @@ -20027,7 +27534,9 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the property. */ matchPropertyFromExpandedDataSetName(expandedDataSetName: string) { - return this.pathTemplates.expandedDataSetPathTemplate.match(expandedDataSetName).property; + return this.pathTemplates.expandedDataSetPathTemplate.match( + expandedDataSetName, + ).property; } /** @@ -20038,7 +27547,9 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the expanded_data_set. */ matchExpandedDataSetFromExpandedDataSetName(expandedDataSetName: string) { - return this.pathTemplates.expandedDataSetPathTemplate.match(expandedDataSetName).expanded_data_set; + return this.pathTemplates.expandedDataSetPathTemplate.match( + expandedDataSetName, + ).expanded_data_set; } /** @@ -20048,7 +27559,7 @@ export class AnalyticsAdminServiceClient { * @param {string} firebase_link * @returns {string} Resource name string. */ - firebaseLinkPath(property:string,firebaseLink:string) { + firebaseLinkPath(property: string, firebaseLink: string) { return this.pathTemplates.firebaseLinkPathTemplate.render({ property: property, firebase_link: firebaseLink, @@ -20063,7 +27574,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the property. */ matchPropertyFromFirebaseLinkName(firebaseLinkName: string) { - return this.pathTemplates.firebaseLinkPathTemplate.match(firebaseLinkName).property; + return this.pathTemplates.firebaseLinkPathTemplate.match(firebaseLinkName) + .property; } /** @@ -20074,7 +27586,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the firebase_link. */ matchFirebaseLinkFromFirebaseLinkName(firebaseLinkName: string) { - return this.pathTemplates.firebaseLinkPathTemplate.match(firebaseLinkName).firebase_link; + return this.pathTemplates.firebaseLinkPathTemplate.match(firebaseLinkName) + .firebase_link; } /** @@ -20084,7 +27597,7 @@ export class AnalyticsAdminServiceClient { * @param {string} data_stream * @returns {string} Resource name string. */ - globalSiteTagPath(property:string,dataStream:string) { + globalSiteTagPath(property: string, dataStream: string) { return this.pathTemplates.globalSiteTagPathTemplate.render({ property: property, data_stream: dataStream, @@ -20099,7 +27612,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the property. */ matchPropertyFromGlobalSiteTagName(globalSiteTagName: string) { - return this.pathTemplates.globalSiteTagPathTemplate.match(globalSiteTagName).property; + return this.pathTemplates.globalSiteTagPathTemplate.match(globalSiteTagName) + .property; } /** @@ -20110,7 +27624,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the data_stream. */ matchDataStreamFromGlobalSiteTagName(globalSiteTagName: string) { - return this.pathTemplates.globalSiteTagPathTemplate.match(globalSiteTagName).data_stream; + return this.pathTemplates.globalSiteTagPathTemplate.match(globalSiteTagName) + .data_stream; } /** @@ -20120,7 +27635,7 @@ export class AnalyticsAdminServiceClient { * @param {string} google_ads_link * @returns {string} Resource name string. */ - googleAdsLinkPath(property:string,googleAdsLink:string) { + googleAdsLinkPath(property: string, googleAdsLink: string) { return this.pathTemplates.googleAdsLinkPathTemplate.render({ property: property, google_ads_link: googleAdsLink, @@ -20135,7 +27650,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the property. */ matchPropertyFromGoogleAdsLinkName(googleAdsLinkName: string) { - return this.pathTemplates.googleAdsLinkPathTemplate.match(googleAdsLinkName).property; + return this.pathTemplates.googleAdsLinkPathTemplate.match(googleAdsLinkName) + .property; } /** @@ -20146,7 +27662,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the google_ads_link. */ matchGoogleAdsLinkFromGoogleAdsLinkName(googleAdsLinkName: string) { - return this.pathTemplates.googleAdsLinkPathTemplate.match(googleAdsLinkName).google_ads_link; + return this.pathTemplates.googleAdsLinkPathTemplate.match(googleAdsLinkName) + .google_ads_link; } /** @@ -20155,7 +27672,7 @@ export class AnalyticsAdminServiceClient { * @param {string} property * @returns {string} Resource name string. */ - googleSignalsSettingsPath(property:string) { + googleSignalsSettingsPath(property: string) { return this.pathTemplates.googleSignalsSettingsPathTemplate.render({ property: property, }); @@ -20168,8 +27685,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing GoogleSignalsSettings resource. * @returns {string} A string representing the property. */ - matchPropertyFromGoogleSignalsSettingsName(googleSignalsSettingsName: string) { - return this.pathTemplates.googleSignalsSettingsPathTemplate.match(googleSignalsSettingsName).property; + matchPropertyFromGoogleSignalsSettingsName( + googleSignalsSettingsName: string, + ) { + return this.pathTemplates.googleSignalsSettingsPathTemplate.match( + googleSignalsSettingsName, + ).property; } /** @@ -20179,7 +27700,7 @@ export class AnalyticsAdminServiceClient { * @param {string} key_event * @returns {string} Resource name string. */ - keyEventPath(property:string,keyEvent:string) { + keyEventPath(property: string, keyEvent: string) { return this.pathTemplates.keyEventPathTemplate.render({ property: property, key_event: keyEvent, @@ -20205,7 +27726,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the key_event. */ matchKeyEventFromKeyEventName(keyEventName: string) { - return this.pathTemplates.keyEventPathTemplate.match(keyEventName).key_event; + return this.pathTemplates.keyEventPathTemplate.match(keyEventName) + .key_event; } /** @@ -20216,7 +27738,11 @@ export class AnalyticsAdminServiceClient { * @param {string} measurement_protocol_secret * @returns {string} Resource name string. */ - measurementProtocolSecretPath(property:string,dataStream:string,measurementProtocolSecret:string) { + measurementProtocolSecretPath( + property: string, + dataStream: string, + measurementProtocolSecret: string, + ) { return this.pathTemplates.measurementProtocolSecretPathTemplate.render({ property: property, data_stream: dataStream, @@ -20231,8 +27757,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing MeasurementProtocolSecret resource. * @returns {string} A string representing the property. */ - matchPropertyFromMeasurementProtocolSecretName(measurementProtocolSecretName: string) { - return this.pathTemplates.measurementProtocolSecretPathTemplate.match(measurementProtocolSecretName).property; + matchPropertyFromMeasurementProtocolSecretName( + measurementProtocolSecretName: string, + ) { + return this.pathTemplates.measurementProtocolSecretPathTemplate.match( + measurementProtocolSecretName, + ).property; } /** @@ -20242,8 +27772,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing MeasurementProtocolSecret resource. * @returns {string} A string representing the data_stream. */ - matchDataStreamFromMeasurementProtocolSecretName(measurementProtocolSecretName: string) { - return this.pathTemplates.measurementProtocolSecretPathTemplate.match(measurementProtocolSecretName).data_stream; + matchDataStreamFromMeasurementProtocolSecretName( + measurementProtocolSecretName: string, + ) { + return this.pathTemplates.measurementProtocolSecretPathTemplate.match( + measurementProtocolSecretName, + ).data_stream; } /** @@ -20253,8 +27787,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing MeasurementProtocolSecret resource. * @returns {string} A string representing the measurement_protocol_secret. */ - matchMeasurementProtocolSecretFromMeasurementProtocolSecretName(measurementProtocolSecretName: string) { - return this.pathTemplates.measurementProtocolSecretPathTemplate.match(measurementProtocolSecretName).measurement_protocol_secret; + matchMeasurementProtocolSecretFromMeasurementProtocolSecretName( + measurementProtocolSecretName: string, + ) { + return this.pathTemplates.measurementProtocolSecretPathTemplate.match( + measurementProtocolSecretName, + ).measurement_protocol_secret; } /** @@ -20263,7 +27801,7 @@ export class AnalyticsAdminServiceClient { * @param {string} property * @returns {string} Resource name string. */ - propertyPath(property:string) { + propertyPath(property: string) { return this.pathTemplates.propertyPathTemplate.render({ property: property, }); @@ -20287,7 +27825,7 @@ export class AnalyticsAdminServiceClient { * @param {string} access_binding * @returns {string} Resource name string. */ - propertyAccessBindingPath(property:string,accessBinding:string) { + propertyAccessBindingPath(property: string, accessBinding: string) { return this.pathTemplates.propertyAccessBindingPathTemplate.render({ property: property, access_binding: accessBinding, @@ -20301,8 +27839,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing property_access_binding resource. * @returns {string} A string representing the property. */ - matchPropertyFromPropertyAccessBindingName(propertyAccessBindingName: string) { - return this.pathTemplates.propertyAccessBindingPathTemplate.match(propertyAccessBindingName).property; + matchPropertyFromPropertyAccessBindingName( + propertyAccessBindingName: string, + ) { + return this.pathTemplates.propertyAccessBindingPathTemplate.match( + propertyAccessBindingName, + ).property; } /** @@ -20312,8 +27854,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing property_access_binding resource. * @returns {string} A string representing the access_binding. */ - matchAccessBindingFromPropertyAccessBindingName(propertyAccessBindingName: string) { - return this.pathTemplates.propertyAccessBindingPathTemplate.match(propertyAccessBindingName).access_binding; + matchAccessBindingFromPropertyAccessBindingName( + propertyAccessBindingName: string, + ) { + return this.pathTemplates.propertyAccessBindingPathTemplate.match( + propertyAccessBindingName, + ).access_binding; } /** @@ -20323,7 +27869,10 @@ export class AnalyticsAdminServiceClient { * @param {string} reporting_data_annotation * @returns {string} Resource name string. */ - reportingDataAnnotationPath(property:string,reportingDataAnnotation:string) { + reportingDataAnnotationPath( + property: string, + reportingDataAnnotation: string, + ) { return this.pathTemplates.reportingDataAnnotationPathTemplate.render({ property: property, reporting_data_annotation: reportingDataAnnotation, @@ -20337,8 +27886,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing ReportingDataAnnotation resource. * @returns {string} A string representing the property. */ - matchPropertyFromReportingDataAnnotationName(reportingDataAnnotationName: string) { - return this.pathTemplates.reportingDataAnnotationPathTemplate.match(reportingDataAnnotationName).property; + matchPropertyFromReportingDataAnnotationName( + reportingDataAnnotationName: string, + ) { + return this.pathTemplates.reportingDataAnnotationPathTemplate.match( + reportingDataAnnotationName, + ).property; } /** @@ -20348,8 +27901,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing ReportingDataAnnotation resource. * @returns {string} A string representing the reporting_data_annotation. */ - matchReportingDataAnnotationFromReportingDataAnnotationName(reportingDataAnnotationName: string) { - return this.pathTemplates.reportingDataAnnotationPathTemplate.match(reportingDataAnnotationName).reporting_data_annotation; + matchReportingDataAnnotationFromReportingDataAnnotationName( + reportingDataAnnotationName: string, + ) { + return this.pathTemplates.reportingDataAnnotationPathTemplate.match( + reportingDataAnnotationName, + ).reporting_data_annotation; } /** @@ -20358,7 +27915,7 @@ export class AnalyticsAdminServiceClient { * @param {string} property * @returns {string} Resource name string. */ - reportingIdentitySettingsPath(property:string) { + reportingIdentitySettingsPath(property: string) { return this.pathTemplates.reportingIdentitySettingsPathTemplate.render({ property: property, }); @@ -20371,8 +27928,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing ReportingIdentitySettings resource. * @returns {string} A string representing the property. */ - matchPropertyFromReportingIdentitySettingsName(reportingIdentitySettingsName: string) { - return this.pathTemplates.reportingIdentitySettingsPathTemplate.match(reportingIdentitySettingsName).property; + matchPropertyFromReportingIdentitySettingsName( + reportingIdentitySettingsName: string, + ) { + return this.pathTemplates.reportingIdentitySettingsPathTemplate.match( + reportingIdentitySettingsName, + ).property; } /** @@ -20382,7 +27943,10 @@ export class AnalyticsAdminServiceClient { * @param {string} rollup_property_source_link * @returns {string} Resource name string. */ - rollupPropertySourceLinkPath(property:string,rollupPropertySourceLink:string) { + rollupPropertySourceLinkPath( + property: string, + rollupPropertySourceLink: string, + ) { return this.pathTemplates.rollupPropertySourceLinkPathTemplate.render({ property: property, rollup_property_source_link: rollupPropertySourceLink, @@ -20396,8 +27960,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing RollupPropertySourceLink resource. * @returns {string} A string representing the property. */ - matchPropertyFromRollupPropertySourceLinkName(rollupPropertySourceLinkName: string) { - return this.pathTemplates.rollupPropertySourceLinkPathTemplate.match(rollupPropertySourceLinkName).property; + matchPropertyFromRollupPropertySourceLinkName( + rollupPropertySourceLinkName: string, + ) { + return this.pathTemplates.rollupPropertySourceLinkPathTemplate.match( + rollupPropertySourceLinkName, + ).property; } /** @@ -20407,8 +27975,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing RollupPropertySourceLink resource. * @returns {string} A string representing the rollup_property_source_link. */ - matchRollupPropertySourceLinkFromRollupPropertySourceLinkName(rollupPropertySourceLinkName: string) { - return this.pathTemplates.rollupPropertySourceLinkPathTemplate.match(rollupPropertySourceLinkName).rollup_property_source_link; + matchRollupPropertySourceLinkFromRollupPropertySourceLinkName( + rollupPropertySourceLinkName: string, + ) { + return this.pathTemplates.rollupPropertySourceLinkPathTemplate.match( + rollupPropertySourceLinkName, + ).rollup_property_source_link; } /** @@ -20419,12 +27991,18 @@ export class AnalyticsAdminServiceClient { * @param {string} skadnetwork_conversion_value_schema * @returns {string} Resource name string. */ - sKAdNetworkConversionValueSchemaPath(property:string,dataStream:string,skadnetworkConversionValueSchema:string) { - return this.pathTemplates.sKAdNetworkConversionValueSchemaPathTemplate.render({ - property: property, - data_stream: dataStream, - skadnetwork_conversion_value_schema: skadnetworkConversionValueSchema, - }); + sKAdNetworkConversionValueSchemaPath( + property: string, + dataStream: string, + skadnetworkConversionValueSchema: string, + ) { + return this.pathTemplates.sKAdNetworkConversionValueSchemaPathTemplate.render( + { + property: property, + data_stream: dataStream, + skadnetwork_conversion_value_schema: skadnetworkConversionValueSchema, + }, + ); } /** @@ -20434,8 +28012,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing SKAdNetworkConversionValueSchema resource. * @returns {string} A string representing the property. */ - matchPropertyFromSKAdNetworkConversionValueSchemaName(sKAdNetworkConversionValueSchemaName: string) { - return this.pathTemplates.sKAdNetworkConversionValueSchemaPathTemplate.match(sKAdNetworkConversionValueSchemaName).property; + matchPropertyFromSKAdNetworkConversionValueSchemaName( + sKAdNetworkConversionValueSchemaName: string, + ) { + return this.pathTemplates.sKAdNetworkConversionValueSchemaPathTemplate.match( + sKAdNetworkConversionValueSchemaName, + ).property; } /** @@ -20445,8 +28027,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing SKAdNetworkConversionValueSchema resource. * @returns {string} A string representing the data_stream. */ - matchDataStreamFromSKAdNetworkConversionValueSchemaName(sKAdNetworkConversionValueSchemaName: string) { - return this.pathTemplates.sKAdNetworkConversionValueSchemaPathTemplate.match(sKAdNetworkConversionValueSchemaName).data_stream; + matchDataStreamFromSKAdNetworkConversionValueSchemaName( + sKAdNetworkConversionValueSchemaName: string, + ) { + return this.pathTemplates.sKAdNetworkConversionValueSchemaPathTemplate.match( + sKAdNetworkConversionValueSchemaName, + ).data_stream; } /** @@ -20456,8 +28042,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing SKAdNetworkConversionValueSchema resource. * @returns {string} A string representing the skadnetwork_conversion_value_schema. */ - matchSkadnetworkConversionValueSchemaFromSKAdNetworkConversionValueSchemaName(sKAdNetworkConversionValueSchemaName: string) { - return this.pathTemplates.sKAdNetworkConversionValueSchemaPathTemplate.match(sKAdNetworkConversionValueSchemaName).skadnetwork_conversion_value_schema; + matchSkadnetworkConversionValueSchemaFromSKAdNetworkConversionValueSchemaName( + sKAdNetworkConversionValueSchemaName: string, + ) { + return this.pathTemplates.sKAdNetworkConversionValueSchemaPathTemplate.match( + sKAdNetworkConversionValueSchemaName, + ).skadnetwork_conversion_value_schema; } /** @@ -20466,7 +28056,7 @@ export class AnalyticsAdminServiceClient { * @param {string} property * @returns {string} Resource name string. */ - searchAds360LinkPath(property:string) { + searchAds360LinkPath(property: string) { return this.pathTemplates.searchAds360LinkPathTemplate.render({ property: property, }); @@ -20480,7 +28070,9 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the property. */ matchPropertyFromSearchAds360LinkName(searchAds360LinkName: string) { - return this.pathTemplates.searchAds360LinkPathTemplate.match(searchAds360LinkName).property; + return this.pathTemplates.searchAds360LinkPathTemplate.match( + searchAds360LinkName, + ).property; } /** @@ -20490,7 +28082,7 @@ export class AnalyticsAdminServiceClient { * @param {string} sub_property_event_filter * @returns {string} Resource name string. */ - subpropertyEventFilterPath(property:string,subPropertyEventFilter:string) { + subpropertyEventFilterPath(property: string, subPropertyEventFilter: string) { return this.pathTemplates.subpropertyEventFilterPathTemplate.render({ property: property, sub_property_event_filter: subPropertyEventFilter, @@ -20504,8 +28096,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing SubpropertyEventFilter resource. * @returns {string} A string representing the property. */ - matchPropertyFromSubpropertyEventFilterName(subpropertyEventFilterName: string) { - return this.pathTemplates.subpropertyEventFilterPathTemplate.match(subpropertyEventFilterName).property; + matchPropertyFromSubpropertyEventFilterName( + subpropertyEventFilterName: string, + ) { + return this.pathTemplates.subpropertyEventFilterPathTemplate.match( + subpropertyEventFilterName, + ).property; } /** @@ -20515,8 +28111,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing SubpropertyEventFilter resource. * @returns {string} A string representing the sub_property_event_filter. */ - matchSubPropertyEventFilterFromSubpropertyEventFilterName(subpropertyEventFilterName: string) { - return this.pathTemplates.subpropertyEventFilterPathTemplate.match(subpropertyEventFilterName).sub_property_event_filter; + matchSubPropertyEventFilterFromSubpropertyEventFilterName( + subpropertyEventFilterName: string, + ) { + return this.pathTemplates.subpropertyEventFilterPathTemplate.match( + subpropertyEventFilterName, + ).sub_property_event_filter; } /** @@ -20526,7 +28126,7 @@ export class AnalyticsAdminServiceClient { * @param {string} subproperty_sync_config * @returns {string} Resource name string. */ - subpropertySyncConfigPath(property:string,subpropertySyncConfig:string) { + subpropertySyncConfigPath(property: string, subpropertySyncConfig: string) { return this.pathTemplates.subpropertySyncConfigPathTemplate.render({ property: property, subproperty_sync_config: subpropertySyncConfig, @@ -20540,8 +28140,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing SubpropertySyncConfig resource. * @returns {string} A string representing the property. */ - matchPropertyFromSubpropertySyncConfigName(subpropertySyncConfigName: string) { - return this.pathTemplates.subpropertySyncConfigPathTemplate.match(subpropertySyncConfigName).property; + matchPropertyFromSubpropertySyncConfigName( + subpropertySyncConfigName: string, + ) { + return this.pathTemplates.subpropertySyncConfigPathTemplate.match( + subpropertySyncConfigName, + ).property; } /** @@ -20551,8 +28155,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing SubpropertySyncConfig resource. * @returns {string} A string representing the subproperty_sync_config. */ - matchSubpropertySyncConfigFromSubpropertySyncConfigName(subpropertySyncConfigName: string) { - return this.pathTemplates.subpropertySyncConfigPathTemplate.match(subpropertySyncConfigName).subproperty_sync_config; + matchSubpropertySyncConfigFromSubpropertySyncConfigName( + subpropertySyncConfigName: string, + ) { + return this.pathTemplates.subpropertySyncConfigPathTemplate.match( + subpropertySyncConfigName, + ).subproperty_sync_config; } /** @@ -20561,7 +28169,7 @@ export class AnalyticsAdminServiceClient { * @param {string} property * @returns {string} Resource name string. */ - userProvidedDataSettingsPath(property:string) { + userProvidedDataSettingsPath(property: string) { return this.pathTemplates.userProvidedDataSettingsPathTemplate.render({ property: property, }); @@ -20574,8 +28182,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing UserProvidedDataSettings resource. * @returns {string} A string representing the property. */ - matchPropertyFromUserProvidedDataSettingsName(userProvidedDataSettingsName: string) { - return this.pathTemplates.userProvidedDataSettingsPathTemplate.match(userProvidedDataSettingsName).property; + matchPropertyFromUserProvidedDataSettingsName( + userProvidedDataSettingsName: string, + ) { + return this.pathTemplates.userProvidedDataSettingsPathTemplate.match( + userProvidedDataSettingsName, + ).property; } /** @@ -20586,7 +28198,7 @@ export class AnalyticsAdminServiceClient { */ close(): Promise { if (this.analyticsAdminServiceStub && !this._terminated) { - return this.analyticsAdminServiceStub.then(stub => { + return this.analyticsAdminServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -20594,4 +28206,4 @@ export class AnalyticsAdminServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-analytics-admin/src/v1alpha/index.ts b/packages/google-analytics-admin/src/v1alpha/index.ts index 8aabd5686dc9..7d116996ad4a 100644 --- a/packages/google-analytics-admin/src/v1alpha/index.ts +++ b/packages/google-analytics-admin/src/v1alpha/index.ts @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {AnalyticsAdminServiceClient} from './analytics_admin_service_client'; +export { AnalyticsAdminServiceClient } from './analytics_admin_service_client'; diff --git a/packages/google-analytics-admin/src/v1beta/analytics_admin_service_client.ts b/packages/google-analytics-admin/src/v1beta/analytics_admin_service_client.ts index 1bc619b3aa7d..ef9eff08dbfc 100644 --- a/packages/google-analytics-admin/src/v1beta/analytics_admin_service_client.ts +++ b/packages/google-analytics-admin/src/v1beta/analytics_admin_service_client.ts @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +51,7 @@ export class AnalyticsAdminServiceClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('admin'); @@ -57,9 +64,9 @@ export class AnalyticsAdminServiceClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - analyticsAdminServiceStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + analyticsAdminServiceStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of AnalyticsAdminServiceClient. @@ -100,21 +107,43 @@ export class AnalyticsAdminServiceClient { * const client = new AnalyticsAdminServiceClient({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 AnalyticsAdminServiceClient; - 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 staticMembers = this + .constructor as typeof AnalyticsAdminServiceClient; + 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 = 'analyticsadmin.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -139,7 +168,7 @@ export class AnalyticsAdminServiceClient { 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; @@ -153,10 +182,7 @@ export class AnalyticsAdminServiceClient { } // 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 { @@ -178,43 +204,43 @@ export class AnalyticsAdminServiceClient { // Create useful helper objects for these. this.pathTemplates = { accountPathTemplate: new this._gaxModule.PathTemplate( - 'accounts/{account}' + 'accounts/{account}', ), accountSummaryPathTemplate: new this._gaxModule.PathTemplate( - 'accountSummaries/{account_summary}' + 'accountSummaries/{account_summary}', ), conversionEventPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/conversionEvents/{conversion_event}' + 'properties/{property}/conversionEvents/{conversion_event}', ), customDimensionPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/customDimensions/{custom_dimension}' + 'properties/{property}/customDimensions/{custom_dimension}', ), customMetricPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/customMetrics/{custom_metric}' + 'properties/{property}/customMetrics/{custom_metric}', ), dataRetentionSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/dataRetentionSettings' + 'properties/{property}/dataRetentionSettings', ), dataSharingSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'accounts/{account}/dataSharingSettings' + 'accounts/{account}/dataSharingSettings', ), dataStreamPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/dataStreams/{data_stream}' + 'properties/{property}/dataStreams/{data_stream}', ), firebaseLinkPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/firebaseLinks/{firebase_link}' + 'properties/{property}/firebaseLinks/{firebase_link}', ), googleAdsLinkPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/googleAdsLinks/{google_ads_link}' + 'properties/{property}/googleAdsLinks/{google_ads_link}', ), keyEventPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/keyEvents/{key_event}' + 'properties/{property}/keyEvents/{key_event}', ), measurementProtocolSecretPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/dataStreams/{data_stream}/measurementProtocolSecrets/{measurement_protocol_secret}' + 'properties/{property}/dataStreams/{data_stream}/measurementProtocolSecrets/{measurement_protocol_secret}', ), propertyPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}' + 'properties/{property}', ), }; @@ -222,36 +248,75 @@ export class AnalyticsAdminServiceClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listAccounts: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'accounts'), - listAccountSummaries: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'accountSummaries'), - listProperties: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'properties'), - listFirebaseLinks: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'firebaseLinks'), - listGoogleAdsLinks: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'googleAdsLinks'), - listMeasurementProtocolSecrets: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'measurementProtocolSecrets'), - searchChangeHistoryEvents: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'changeHistoryEvents'), - listConversionEvents: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'conversionEvents'), - listKeyEvents: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'keyEvents'), - listCustomDimensions: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'customDimensions'), - listCustomMetrics: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'customMetrics'), - listDataStreams: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'dataStreams') + listAccounts: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'accounts', + ), + listAccountSummaries: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'accountSummaries', + ), + listProperties: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'properties', + ), + listFirebaseLinks: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'firebaseLinks', + ), + listGoogleAdsLinks: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'googleAdsLinks', + ), + listMeasurementProtocolSecrets: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'measurementProtocolSecrets', + ), + searchChangeHistoryEvents: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'changeHistoryEvents', + ), + listConversionEvents: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'conversionEvents', + ), + listKeyEvents: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'keyEvents', + ), + listCustomDimensions: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'customDimensions', + ), + listCustomMetrics: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'customMetrics', + ), + listDataStreams: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'dataStreams', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.analytics.admin.v1beta.AnalyticsAdminService', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.analytics.admin.v1beta.AnalyticsAdminService', + 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 @@ -282,37 +347,96 @@ export class AnalyticsAdminServiceClient { // Put together the "service stub" for // google.analytics.admin.v1beta.AnalyticsAdminService. this.analyticsAdminServiceStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.analytics.admin.v1beta.AnalyticsAdminService') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.analytics.admin.v1beta.AnalyticsAdminService, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.analytics.admin.v1beta.AnalyticsAdminService', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.analytics.admin.v1beta + .AnalyticsAdminService, + 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 analyticsAdminServiceStubMethods = - ['getAccount', 'listAccounts', 'deleteAccount', 'updateAccount', 'provisionAccountTicket', 'listAccountSummaries', 'getProperty', 'listProperties', 'createProperty', 'deleteProperty', 'updateProperty', 'createFirebaseLink', 'deleteFirebaseLink', 'listFirebaseLinks', 'createGoogleAdsLink', 'updateGoogleAdsLink', 'deleteGoogleAdsLink', 'listGoogleAdsLinks', 'getDataSharingSettings', 'getMeasurementProtocolSecret', 'listMeasurementProtocolSecrets', 'createMeasurementProtocolSecret', 'deleteMeasurementProtocolSecret', 'updateMeasurementProtocolSecret', 'acknowledgeUserDataCollection', 'searchChangeHistoryEvents', 'createConversionEvent', 'updateConversionEvent', 'getConversionEvent', 'deleteConversionEvent', 'listConversionEvents', 'createKeyEvent', 'updateKeyEvent', 'getKeyEvent', 'deleteKeyEvent', 'listKeyEvents', 'createCustomDimension', 'updateCustomDimension', 'listCustomDimensions', 'archiveCustomDimension', 'getCustomDimension', 'createCustomMetric', 'updateCustomMetric', 'listCustomMetrics', 'archiveCustomMetric', 'getCustomMetric', 'getDataRetentionSettings', 'updateDataRetentionSettings', 'createDataStream', 'deleteDataStream', 'updateDataStream', 'listDataStreams', 'getDataStream', 'runAccessReport']; + const analyticsAdminServiceStubMethods = [ + 'getAccount', + 'listAccounts', + 'deleteAccount', + 'updateAccount', + 'provisionAccountTicket', + 'listAccountSummaries', + 'getProperty', + 'listProperties', + 'createProperty', + 'deleteProperty', + 'updateProperty', + 'createFirebaseLink', + 'deleteFirebaseLink', + 'listFirebaseLinks', + 'createGoogleAdsLink', + 'updateGoogleAdsLink', + 'deleteGoogleAdsLink', + 'listGoogleAdsLinks', + 'getDataSharingSettings', + 'getMeasurementProtocolSecret', + 'listMeasurementProtocolSecrets', + 'createMeasurementProtocolSecret', + 'deleteMeasurementProtocolSecret', + 'updateMeasurementProtocolSecret', + 'acknowledgeUserDataCollection', + 'searchChangeHistoryEvents', + 'createConversionEvent', + 'updateConversionEvent', + 'getConversionEvent', + 'deleteConversionEvent', + 'listConversionEvents', + 'createKeyEvent', + 'updateKeyEvent', + 'getKeyEvent', + 'deleteKeyEvent', + 'listKeyEvents', + 'createCustomDimension', + 'updateCustomDimension', + 'listCustomDimensions', + 'archiveCustomDimension', + 'getCustomDimension', + 'createCustomMetric', + 'updateCustomMetric', + 'listCustomMetrics', + 'archiveCustomMetric', + 'getCustomMetric', + 'getDataRetentionSettings', + 'updateDataRetentionSettings', + 'createDataStream', + 'deleteDataStream', + 'updateDataStream', + 'listDataStreams', + 'getDataStream', + 'runAccessReport', + ]; for (const methodName of analyticsAdminServiceStubMethods) { const callPromise = this.analyticsAdminServiceStub.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] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -327,8 +451,14 @@ export class AnalyticsAdminServiceClient { * @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 'analyticsadmin.googleapis.com'; } @@ -339,8 +469,14 @@ export class AnalyticsAdminServiceClient { * @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 'analyticsadmin.googleapis.com'; } @@ -373,7 +509,7 @@ export class AnalyticsAdminServiceClient { static get scopes() { return [ 'https://www.googleapis.com/auth/analytics.edit', - 'https://www.googleapis.com/auth/analytics.readonly' + 'https://www.googleapis.com/auth/analytics.readonly', ]; } @@ -383,8 +519,9 @@ export class AnalyticsAdminServiceClient { * 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; @@ -395,4286 +532,6297 @@ export class AnalyticsAdminServiceClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Lookup for a single Account. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the account to lookup. - * Format: accounts/{account} - * Example: "accounts/100" - * @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.analytics.admin.v1beta.Account|Account}. - * 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/v1beta/analytics_admin_service.get_account.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_GetAccount_async - */ + /** + * Lookup for a single Account. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the account to lookup. + * Format: accounts/{account} + * Example: "accounts/100" + * @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.analytics.admin.v1beta.Account|Account}. + * 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/v1beta/analytics_admin_service.get_account.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_GetAccount_async + */ getAccount( - request?: protos.google.analytics.admin.v1beta.IGetAccountRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IAccount, - protos.google.analytics.admin.v1beta.IGetAccountRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IGetAccountRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IAccount, + protos.google.analytics.admin.v1beta.IGetAccountRequest | undefined, + {} | undefined, + ] + >; getAccount( - request: protos.google.analytics.admin.v1beta.IGetAccountRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IAccount, - protos.google.analytics.admin.v1beta.IGetAccountRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IGetAccountRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IAccount, + | protos.google.analytics.admin.v1beta.IGetAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAccount( - request: protos.google.analytics.admin.v1beta.IGetAccountRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IAccount, - protos.google.analytics.admin.v1beta.IGetAccountRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IGetAccountRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IAccount, + | protos.google.analytics.admin.v1beta.IGetAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAccount( - request?: protos.google.analytics.admin.v1beta.IGetAccountRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1beta.IAccount, - protos.google.analytics.admin.v1beta.IGetAccountRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.IGetAccountRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IAccount, - protos.google.analytics.admin.v1beta.IGetAccountRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IAccount, - protos.google.analytics.admin.v1beta.IGetAccountRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IGetAccountRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IAccount, + | protos.google.analytics.admin.v1beta.IGetAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IAccount, + protos.google.analytics.admin.v1beta.IGetAccountRequest | 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('getAccount request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IAccount, - protos.google.analytics.admin.v1beta.IGetAccountRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IAccount, + | protos.google.analytics.admin.v1beta.IGetAccountRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getAccount response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getAccount(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IAccount, - protos.google.analytics.admin.v1beta.IGetAccountRequest|undefined, - {}|undefined - ]) => { - this._log.info('getAccount response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getAccount(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IAccount, + protos.google.analytics.admin.v1beta.IGetAccountRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getAccount response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Marks target Account as soft-deleted (ie: "trashed") and returns it. - * - * This API does not have a method to restore soft-deleted accounts. - * However, they can be restored using the Trash Can UI. - * - * If the accounts are not restored before the expiration time, the account - * and all child resources (eg: Properties, GoogleAdsLinks, Streams, - * AccessBindings) will be permanently purged. - * https://support.google.com/analytics/answer/6154772 - * - * Returns an error if the target is not found. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the Account to soft-delete. - * Format: accounts/{account} - * Example: "accounts/100" - * @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/v1beta/analytics_admin_service.delete_account.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteAccount_async - */ + /** + * Marks target Account as soft-deleted (ie: "trashed") and returns it. + * + * This API does not have a method to restore soft-deleted accounts. + * However, they can be restored using the Trash Can UI. + * + * If the accounts are not restored before the expiration time, the account + * and all child resources (eg: Properties, GoogleAdsLinks, Streams, + * AccessBindings) will be permanently purged. + * https://support.google.com/analytics/answer/6154772 + * + * Returns an error if the target is not found. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the Account to soft-delete. + * Format: accounts/{account} + * Example: "accounts/100" + * @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/v1beta/analytics_admin_service.delete_account.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteAccount_async + */ deleteAccount( - request?: protos.google.analytics.admin.v1beta.IDeleteAccountRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteAccountRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IDeleteAccountRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.analytics.admin.v1beta.IDeleteAccountRequest | undefined, + {} | undefined, + ] + >; deleteAccount( - request: protos.google.analytics.admin.v1beta.IDeleteAccountRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteAccountRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IDeleteAccountRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteAccount( - request: protos.google.analytics.admin.v1beta.IDeleteAccountRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteAccountRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IDeleteAccountRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteAccount( - request?: protos.google.analytics.admin.v1beta.IDeleteAccountRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1beta.IDeleteAccountRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteAccountRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteAccountRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteAccountRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IDeleteAccountRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.analytics.admin.v1beta.IDeleteAccountRequest | 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('deleteAccount request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteAccountRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteAccountRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteAccount response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteAccount(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteAccountRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteAccount response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteAccount(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1beta.IDeleteAccountRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteAccount response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates an account. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1beta.Account} request.account - * Required. The account to update. - * The account's `name` field is used to identify the account. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Field names must be in snake - * case (for example, "field_to_update"). Omitted fields will not be updated. - * To replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1beta.Account|Account}. - * 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/v1beta/analytics_admin_service.update_account.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateAccount_async - */ + /** + * Updates an account. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1beta.Account} request.account + * Required. The account to update. + * The account's `name` field is used to identify the account. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Field names must be in snake + * case (for example, "field_to_update"). Omitted fields will not be updated. + * To replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1beta.Account|Account}. + * 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/v1beta/analytics_admin_service.update_account.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateAccount_async + */ updateAccount( - request?: protos.google.analytics.admin.v1beta.IUpdateAccountRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IAccount, - protos.google.analytics.admin.v1beta.IUpdateAccountRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IUpdateAccountRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IAccount, + protos.google.analytics.admin.v1beta.IUpdateAccountRequest | undefined, + {} | undefined, + ] + >; updateAccount( - request: protos.google.analytics.admin.v1beta.IUpdateAccountRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IAccount, - protos.google.analytics.admin.v1beta.IUpdateAccountRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IUpdateAccountRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IAccount, + | protos.google.analytics.admin.v1beta.IUpdateAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateAccount( - request: protos.google.analytics.admin.v1beta.IUpdateAccountRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IAccount, - protos.google.analytics.admin.v1beta.IUpdateAccountRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IUpdateAccountRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IAccount, + | protos.google.analytics.admin.v1beta.IUpdateAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateAccount( - request?: protos.google.analytics.admin.v1beta.IUpdateAccountRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1beta.IUpdateAccountRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IAccount, - protos.google.analytics.admin.v1beta.IUpdateAccountRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1beta.IAccount, - protos.google.analytics.admin.v1beta.IUpdateAccountRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IAccount, - protos.google.analytics.admin.v1beta.IUpdateAccountRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IUpdateAccountRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IAccount, + | protos.google.analytics.admin.v1beta.IUpdateAccountRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IAccount, + protos.google.analytics.admin.v1beta.IUpdateAccountRequest | 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({ - 'account.name': request.account!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'account.name': request.account!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateAccount request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IAccount, - protos.google.analytics.admin.v1beta.IUpdateAccountRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IAccount, + | protos.google.analytics.admin.v1beta.IUpdateAccountRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateAccount response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateAccount(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IAccount, - protos.google.analytics.admin.v1beta.IUpdateAccountRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateAccount response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateAccount(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IAccount, + ( + | protos.google.analytics.admin.v1beta.IUpdateAccountRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateAccount response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Requests a ticket for creating an account. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1beta.Account} request.account - * The account to create. - * @param {string} request.redirectUri - * Redirect URI where the user will be sent after accepting Terms of Service. - * Must be configured in Cloud Console as a Redirect URI. - * @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.analytics.admin.v1beta.ProvisionAccountTicketResponse|ProvisionAccountTicketResponse}. - * 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/v1beta/analytics_admin_service.provision_account_ticket.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ProvisionAccountTicket_async - */ + /** + * Requests a ticket for creating an account. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1beta.Account} request.account + * The account to create. + * @param {string} request.redirectUri + * Redirect URI where the user will be sent after accepting Terms of Service. + * Must be configured in Cloud Console as a Redirect URI. + * @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.analytics.admin.v1beta.ProvisionAccountTicketResponse|ProvisionAccountTicketResponse}. + * 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/v1beta/analytics_admin_service.provision_account_ticket.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ProvisionAccountTicket_async + */ provisionAccountTicket( - request?: protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IProvisionAccountTicketResponse, - protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IProvisionAccountTicketResponse, + ( + | protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest + | undefined + ), + {} | undefined, + ] + >; provisionAccountTicket( - request: protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IProvisionAccountTicketResponse, - protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IProvisionAccountTicketResponse, + | protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest + | null + | undefined, + {} | null | undefined + >, + ): void; provisionAccountTicket( - request: protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IProvisionAccountTicketResponse, - protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IProvisionAccountTicketResponse, + | protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest + | null + | undefined, + {} | null | undefined + >, + ): void; provisionAccountTicket( - request?: protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1beta.IProvisionAccountTicketResponse, - protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IProvisionAccountTicketResponse, - protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IProvisionAccountTicketResponse, - protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IProvisionAccountTicketResponse, + | protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IProvisionAccountTicketResponse, + ( + | protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest + | 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 || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('provisionAccountTicket request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IProvisionAccountTicketResponse, - protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IProvisionAccountTicketResponse, + | protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('provisionAccountTicket response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.provisionAccountTicket(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IProvisionAccountTicketResponse, - protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest|undefined, - {}|undefined - ]) => { - this._log.info('provisionAccountTicket response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .provisionAccountTicket(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IProvisionAccountTicketResponse, + ( + | protos.google.analytics.admin.v1beta.IProvisionAccountTicketRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('provisionAccountTicket response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for a single GA Property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the property to lookup. - * Format: properties/{property_id} - * Example: "properties/1000" - * @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.analytics.admin.v1beta.Property|Property}. - * 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/v1beta/analytics_admin_service.get_property.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_GetProperty_async - */ + /** + * Lookup for a single GA Property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the property to lookup. + * Format: properties/{property_id} + * Example: "properties/1000" + * @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.analytics.admin.v1beta.Property|Property}. + * 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/v1beta/analytics_admin_service.get_property.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_GetProperty_async + */ getProperty( - request?: protos.google.analytics.admin.v1beta.IGetPropertyRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IGetPropertyRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IGetPropertyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IProperty, + protos.google.analytics.admin.v1beta.IGetPropertyRequest | undefined, + {} | undefined, + ] + >; getProperty( - request: protos.google.analytics.admin.v1beta.IGetPropertyRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IGetPropertyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IGetPropertyRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IProperty, + | protos.google.analytics.admin.v1beta.IGetPropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getProperty( - request: protos.google.analytics.admin.v1beta.IGetPropertyRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IGetPropertyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IGetPropertyRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IProperty, + | protos.google.analytics.admin.v1beta.IGetPropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getProperty( - request?: protos.google.analytics.admin.v1beta.IGetPropertyRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1beta.IGetPropertyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IGetPropertyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IGetPropertyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IGetPropertyRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IGetPropertyRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IProperty, + | protos.google.analytics.admin.v1beta.IGetPropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IProperty, + protos.google.analytics.admin.v1beta.IGetPropertyRequest | 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('getProperty request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IGetPropertyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IProperty, + | protos.google.analytics.admin.v1beta.IGetPropertyRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getProperty response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getProperty(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IGetPropertyRequest|undefined, - {}|undefined - ]) => { - this._log.info('getProperty response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getProperty(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IProperty, + protos.google.analytics.admin.v1beta.IGetPropertyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getProperty response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a Google Analytics property with the specified location and - * attributes. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1beta.Property} request.property - * Required. The property to create. - * Note: the supplied property must specify its parent. - * @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.analytics.admin.v1beta.Property|Property}. - * 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/v1beta/analytics_admin_service.create_property.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateProperty_async - */ + /** + * Creates a Google Analytics property with the specified location and + * attributes. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1beta.Property} request.property + * Required. The property to create. + * Note: the supplied property must specify its parent. + * @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.analytics.admin.v1beta.Property|Property}. + * 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/v1beta/analytics_admin_service.create_property.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateProperty_async + */ createProperty( - request?: protos.google.analytics.admin.v1beta.ICreatePropertyRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.ICreatePropertyRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.ICreatePropertyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IProperty, + protos.google.analytics.admin.v1beta.ICreatePropertyRequest | undefined, + {} | undefined, + ] + >; createProperty( - request: protos.google.analytics.admin.v1beta.ICreatePropertyRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.ICreatePropertyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.ICreatePropertyRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IProperty, + | protos.google.analytics.admin.v1beta.ICreatePropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createProperty( - request: protos.google.analytics.admin.v1beta.ICreatePropertyRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.ICreatePropertyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.ICreatePropertyRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IProperty, + | protos.google.analytics.admin.v1beta.ICreatePropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createProperty( - request?: protos.google.analytics.admin.v1beta.ICreatePropertyRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1beta.ICreatePropertyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.ICreatePropertyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.ICreatePropertyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.ICreatePropertyRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.ICreatePropertyRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IProperty, + | protos.google.analytics.admin.v1beta.ICreatePropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IProperty, + protos.google.analytics.admin.v1beta.ICreatePropertyRequest | 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 || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('createProperty request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.ICreatePropertyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IProperty, + | protos.google.analytics.admin.v1beta.ICreatePropertyRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createProperty response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createProperty(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.ICreatePropertyRequest|undefined, - {}|undefined - ]) => { - this._log.info('createProperty response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createProperty(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IProperty, + ( + | protos.google.analytics.admin.v1beta.ICreatePropertyRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createProperty response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Marks target Property as soft-deleted (ie: "trashed") and returns it. - * - * This API does not have a method to restore soft-deleted properties. - * However, they can be restored using the Trash Can UI. - * - * If the properties are not restored before the expiration time, the Property - * and all child resources (eg: GoogleAdsLinks, Streams, AccessBindings) - * will be permanently purged. - * https://support.google.com/analytics/answer/6154772 - * - * Returns an error if the target is not found. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the Property to soft-delete. - * Format: properties/{property_id} - * Example: "properties/1000" - * @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.analytics.admin.v1beta.Property|Property}. - * 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/v1beta/analytics_admin_service.delete_property.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteProperty_async - */ + /** + * Marks target Property as soft-deleted (ie: "trashed") and returns it. + * + * This API does not have a method to restore soft-deleted properties. + * However, they can be restored using the Trash Can UI. + * + * If the properties are not restored before the expiration time, the Property + * and all child resources (eg: GoogleAdsLinks, Streams, AccessBindings) + * will be permanently purged. + * https://support.google.com/analytics/answer/6154772 + * + * Returns an error if the target is not found. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the Property to soft-delete. + * Format: properties/{property_id} + * Example: "properties/1000" + * @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.analytics.admin.v1beta.Property|Property}. + * 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/v1beta/analytics_admin_service.delete_property.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteProperty_async + */ deleteProperty( - request?: protos.google.analytics.admin.v1beta.IDeletePropertyRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IDeletePropertyRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IDeletePropertyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IProperty, + protos.google.analytics.admin.v1beta.IDeletePropertyRequest | undefined, + {} | undefined, + ] + >; deleteProperty( - request: protos.google.analytics.admin.v1beta.IDeletePropertyRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IDeletePropertyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IDeletePropertyRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IProperty, + | protos.google.analytics.admin.v1beta.IDeletePropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteProperty( - request: protos.google.analytics.admin.v1beta.IDeletePropertyRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IDeletePropertyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IDeletePropertyRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IProperty, + | protos.google.analytics.admin.v1beta.IDeletePropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteProperty( - request?: protos.google.analytics.admin.v1beta.IDeletePropertyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IDeletePropertyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.IDeletePropertyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IDeletePropertyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IDeletePropertyRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IDeletePropertyRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IProperty, + | protos.google.analytics.admin.v1beta.IDeletePropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IProperty, + protos.google.analytics.admin.v1beta.IDeletePropertyRequest | 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('deleteProperty request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IDeletePropertyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IProperty, + | protos.google.analytics.admin.v1beta.IDeletePropertyRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteProperty response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteProperty(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IDeletePropertyRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteProperty response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteProperty(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IProperty, + ( + | protos.google.analytics.admin.v1beta.IDeletePropertyRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteProperty response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1beta.Property} request.property - * Required. The property to update. - * The property's `name` field is used to identify the property to be - * updated. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Field names must be in snake - * case (e.g., "field_to_update"). Omitted fields will not be updated. To - * replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1beta.Property|Property}. - * 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/v1beta/analytics_admin_service.update_property.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateProperty_async - */ + /** + * Updates a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1beta.Property} request.property + * Required. The property to update. + * The property's `name` field is used to identify the property to be + * updated. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Field names must be in snake + * case (e.g., "field_to_update"). Omitted fields will not be updated. To + * replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1beta.Property|Property}. + * 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/v1beta/analytics_admin_service.update_property.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateProperty_async + */ updateProperty( - request?: protos.google.analytics.admin.v1beta.IUpdatePropertyRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IUpdatePropertyRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IUpdatePropertyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IProperty, + protos.google.analytics.admin.v1beta.IUpdatePropertyRequest | undefined, + {} | undefined, + ] + >; updateProperty( - request: protos.google.analytics.admin.v1beta.IUpdatePropertyRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IUpdatePropertyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IUpdatePropertyRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IProperty, + | protos.google.analytics.admin.v1beta.IUpdatePropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateProperty( - request: protos.google.analytics.admin.v1beta.IUpdatePropertyRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IUpdatePropertyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IUpdatePropertyRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IProperty, + | protos.google.analytics.admin.v1beta.IUpdatePropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateProperty( - request?: protos.google.analytics.admin.v1beta.IUpdatePropertyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IUpdatePropertyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.IUpdatePropertyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IUpdatePropertyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IUpdatePropertyRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IUpdatePropertyRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IProperty, + | protos.google.analytics.admin.v1beta.IUpdatePropertyRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IProperty, + protos.google.analytics.admin.v1beta.IUpdatePropertyRequest | 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({ - 'property.name': request.property!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'property.name': request.property!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateProperty request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IUpdatePropertyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IProperty, + | protos.google.analytics.admin.v1beta.IUpdatePropertyRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateProperty response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateProperty(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IProperty, - protos.google.analytics.admin.v1beta.IUpdatePropertyRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateProperty response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateProperty(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IProperty, + ( + | protos.google.analytics.admin.v1beta.IUpdatePropertyRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateProperty response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a FirebaseLink. - * - * Properties can have at most one FirebaseLink. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Format: properties/{property_id} - * - * Example: `properties/1234` - * @param {google.analytics.admin.v1beta.FirebaseLink} request.firebaseLink - * Required. The Firebase link 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.analytics.admin.v1beta.FirebaseLink|FirebaseLink}. - * 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/v1beta/analytics_admin_service.create_firebase_link.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateFirebaseLink_async - */ + /** + * Creates a FirebaseLink. + * + * Properties can have at most one FirebaseLink. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Format: properties/{property_id} + * + * Example: `properties/1234` + * @param {google.analytics.admin.v1beta.FirebaseLink} request.firebaseLink + * Required. The Firebase link 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.analytics.admin.v1beta.FirebaseLink|FirebaseLink}. + * 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/v1beta/analytics_admin_service.create_firebase_link.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateFirebaseLink_async + */ createFirebaseLink( - request?: protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IFirebaseLink, - protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IFirebaseLink, + ( + | protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest + | undefined + ), + {} | undefined, + ] + >; createFirebaseLink( - request: protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IFirebaseLink, - protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IFirebaseLink, + | protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createFirebaseLink( - request: protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IFirebaseLink, - protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IFirebaseLink, + | protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createFirebaseLink( - request?: protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IFirebaseLink, - protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1beta.IFirebaseLink, - protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IFirebaseLink, - protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IFirebaseLink, + | protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IFirebaseLink, + ( + | protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest + | 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('createFirebaseLink request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IFirebaseLink, - protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IFirebaseLink, + | protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createFirebaseLink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createFirebaseLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IFirebaseLink, - protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('createFirebaseLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createFirebaseLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IFirebaseLink, + ( + | protos.google.analytics.admin.v1beta.ICreateFirebaseLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createFirebaseLink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a FirebaseLink on a property - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Format: properties/{property_id}/firebaseLinks/{firebase_link_id} - * - * Example: `properties/1234/firebaseLinks/5678` - * @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/v1beta/analytics_admin_service.delete_firebase_link.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteFirebaseLink_async - */ + /** + * Deletes a FirebaseLink on a property + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Format: properties/{property_id}/firebaseLinks/{firebase_link_id} + * + * Example: `properties/1234/firebaseLinks/5678` + * @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/v1beta/analytics_admin_service.delete_firebase_link.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteFirebaseLink_async + */ deleteFirebaseLink( - request?: protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest + | undefined + ), + {} | undefined, + ] + >; deleteFirebaseLink( - request: protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteFirebaseLink( - request: protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteFirebaseLink( - request?: protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest + | 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('deleteFirebaseLink request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteFirebaseLink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteFirebaseLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteFirebaseLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteFirebaseLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1beta.IDeleteFirebaseLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteFirebaseLink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a GoogleAdsLink. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {google.analytics.admin.v1beta.GoogleAdsLink} request.googleAdsLink - * Required. The GoogleAdsLink 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.analytics.admin.v1beta.GoogleAdsLink|GoogleAdsLink}. - * 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/v1beta/analytics_admin_service.create_google_ads_link.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateGoogleAdsLink_async - */ + /** + * Creates a GoogleAdsLink. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {google.analytics.admin.v1beta.GoogleAdsLink} request.googleAdsLink + * Required. The GoogleAdsLink 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.analytics.admin.v1beta.GoogleAdsLink|GoogleAdsLink}. + * 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/v1beta/analytics_admin_service.create_google_ads_link.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateGoogleAdsLink_async + */ createGoogleAdsLink( - request?: protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IGoogleAdsLink, - protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IGoogleAdsLink, + ( + | protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest + | undefined + ), + {} | undefined, + ] + >; createGoogleAdsLink( - request: protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IGoogleAdsLink, - protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IGoogleAdsLink, + | protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createGoogleAdsLink( - request: protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IGoogleAdsLink, - protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IGoogleAdsLink, + | protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createGoogleAdsLink( - request?: protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1beta.IGoogleAdsLink, - protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IGoogleAdsLink, - protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IGoogleAdsLink, - protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IGoogleAdsLink, + | protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IGoogleAdsLink, + ( + | protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest + | 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('createGoogleAdsLink request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IGoogleAdsLink, - protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IGoogleAdsLink, + | protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createGoogleAdsLink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createGoogleAdsLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IGoogleAdsLink, - protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('createGoogleAdsLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createGoogleAdsLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IGoogleAdsLink, + ( + | protos.google.analytics.admin.v1beta.ICreateGoogleAdsLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createGoogleAdsLink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a GoogleAdsLink on a property - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1beta.GoogleAdsLink} request.googleAdsLink - * The GoogleAdsLink to update - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Field names must be in snake - * case (e.g., "field_to_update"). Omitted fields will not be updated. To - * replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1beta.GoogleAdsLink|GoogleAdsLink}. - * 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/v1beta/analytics_admin_service.update_google_ads_link.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateGoogleAdsLink_async - */ + /** + * Updates a GoogleAdsLink on a property + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1beta.GoogleAdsLink} request.googleAdsLink + * The GoogleAdsLink to update + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Field names must be in snake + * case (e.g., "field_to_update"). Omitted fields will not be updated. To + * replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1beta.GoogleAdsLink|GoogleAdsLink}. + * 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/v1beta/analytics_admin_service.update_google_ads_link.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateGoogleAdsLink_async + */ updateGoogleAdsLink( - request?: protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IGoogleAdsLink, - protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IGoogleAdsLink, + ( + | protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest + | undefined + ), + {} | undefined, + ] + >; updateGoogleAdsLink( - request: protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IGoogleAdsLink, - protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IGoogleAdsLink, + | protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateGoogleAdsLink( - request: protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IGoogleAdsLink, - protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IGoogleAdsLink, + | protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateGoogleAdsLink( - request?: protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1beta.IGoogleAdsLink, - protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IGoogleAdsLink, - protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IGoogleAdsLink, - protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IGoogleAdsLink, + | protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IGoogleAdsLink, + ( + | protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest + | 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({ - 'google_ads_link.name': request.googleAdsLink!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'google_ads_link.name': request.googleAdsLink!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateGoogleAdsLink request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IGoogleAdsLink, - protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IGoogleAdsLink, + | protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateGoogleAdsLink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateGoogleAdsLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IGoogleAdsLink, - protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateGoogleAdsLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateGoogleAdsLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IGoogleAdsLink, + ( + | protos.google.analytics.admin.v1beta.IUpdateGoogleAdsLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateGoogleAdsLink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a GoogleAdsLink on a property - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Example format: properties/1234/googleAdsLinks/5678 - * @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/v1beta/analytics_admin_service.delete_google_ads_link.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteGoogleAdsLink_async - */ + /** + * Deletes a GoogleAdsLink on a property + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Example format: properties/1234/googleAdsLinks/5678 + * @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/v1beta/analytics_admin_service.delete_google_ads_link.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteGoogleAdsLink_async + */ deleteGoogleAdsLink( - request?: protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest + | undefined + ), + {} | undefined, + ] + >; deleteGoogleAdsLink( - request: protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteGoogleAdsLink( - request: protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteGoogleAdsLink( - request?: protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest + | 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('deleteGoogleAdsLink request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteGoogleAdsLink response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteGoogleAdsLink(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteGoogleAdsLink response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteGoogleAdsLink(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1beta.IDeleteGoogleAdsLinkRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteGoogleAdsLink response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Get data sharing settings on an account. - * Data sharing settings are singletons. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the settings to lookup. - * Format: accounts/{account}/dataSharingSettings - * - * Example: `accounts/1000/dataSharingSettings` - * @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.analytics.admin.v1beta.DataSharingSettings|DataSharingSettings}. - * 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/v1beta/analytics_admin_service.get_data_sharing_settings.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataSharingSettings_async - */ - getDataSharingSettings( - request?: protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IDataSharingSettings, - protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest|undefined, {}|undefined - ]>; - getDataSharingSettings( - request: protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IDataSharingSettings, - protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest|null|undefined, - {}|null|undefined>): void; + /** + * Get data sharing settings on an account. + * Data sharing settings are singletons. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the settings to lookup. + * Format: accounts/{account}/dataSharingSettings + * + * Example: `accounts/1000/dataSharingSettings` + * @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.analytics.admin.v1beta.DataSharingSettings|DataSharingSettings}. + * 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/v1beta/analytics_admin_service.get_data_sharing_settings.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataSharingSettings_async + */ getDataSharingSettings( - request: protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IDataSharingSettings, - protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest|null|undefined, - {}|null|undefined>): void; + request?: protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IDataSharingSettings, + ( + | protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest + | undefined + ), + {} | undefined, + ] + >; getDataSharingSettings( - request?: protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1beta.IDataSharingSettings, - protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request: protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IDataSharingSettings, + | protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + getDataSharingSettings( + request: protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IDataSharingSettings, + | protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; + getDataSharingSettings( + request?: protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IDataSharingSettings, - protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IDataSharingSettings, - protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IDataSharingSettings, + | protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IDataSharingSettings, + ( + | protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest + | 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('getDataSharingSettings request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IDataSharingSettings, - protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IDataSharingSettings, + | protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getDataSharingSettings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getDataSharingSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IDataSharingSettings, - protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('getDataSharingSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getDataSharingSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IDataSharingSettings, + ( + | protos.google.analytics.admin.v1beta.IGetDataSharingSettingsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getDataSharingSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for a single MeasurementProtocolSecret. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the measurement protocol secret to lookup. - * Format: - * properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret} - * @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.analytics.admin.v1beta.MeasurementProtocolSecret|MeasurementProtocolSecret}. - * 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/v1beta/analytics_admin_service.get_measurement_protocol_secret.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_GetMeasurementProtocolSecret_async - */ + /** + * Lookup for a single MeasurementProtocolSecret. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the measurement protocol secret to lookup. + * Format: + * properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret} + * @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.analytics.admin.v1beta.MeasurementProtocolSecret|MeasurementProtocolSecret}. + * 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/v1beta/analytics_admin_service.get_measurement_protocol_secret.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_GetMeasurementProtocolSecret_async + */ getMeasurementProtocolSecret( - request?: protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, + ( + | protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest + | undefined + ), + {} | undefined, + ] + >; getMeasurementProtocolSecret( - request: protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getMeasurementProtocolSecret( - request: protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getMeasurementProtocolSecret( - request?: protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, + ( + | protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest + | 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('getMeasurementProtocolSecret request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getMeasurementProtocolSecret response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getMeasurementProtocolSecret(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest|undefined, - {}|undefined - ]) => { - this._log.info('getMeasurementProtocolSecret response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getMeasurementProtocolSecret(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, + ( + | protos.google.analytics.admin.v1beta.IGetMeasurementProtocolSecretRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getMeasurementProtocolSecret response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a measurement protocol secret. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource where this secret will be created. - * Format: properties/{property}/dataStreams/{dataStream} - * @param {google.analytics.admin.v1beta.MeasurementProtocolSecret} request.measurementProtocolSecret - * Required. The measurement protocol secret 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.analytics.admin.v1beta.MeasurementProtocolSecret|MeasurementProtocolSecret}. - * 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/v1beta/analytics_admin_service.create_measurement_protocol_secret.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateMeasurementProtocolSecret_async - */ + /** + * Creates a measurement protocol secret. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource where this secret will be created. + * Format: properties/{property}/dataStreams/{dataStream} + * @param {google.analytics.admin.v1beta.MeasurementProtocolSecret} request.measurementProtocolSecret + * Required. The measurement protocol secret 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.analytics.admin.v1beta.MeasurementProtocolSecret|MeasurementProtocolSecret}. + * 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/v1beta/analytics_admin_service.create_measurement_protocol_secret.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateMeasurementProtocolSecret_async + */ createMeasurementProtocolSecret( - request?: protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, + ( + | protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest + | undefined + ), + {} | undefined, + ] + >; createMeasurementProtocolSecret( - request: protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createMeasurementProtocolSecret( - request: protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createMeasurementProtocolSecret( - request?: protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, + ( + | protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest + | 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('createMeasurementProtocolSecret request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('createMeasurementProtocolSecret response %j', response); + this._log.info( + 'createMeasurementProtocolSecret response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createMeasurementProtocolSecret(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest|undefined, - {}|undefined - ]) => { - this._log.info('createMeasurementProtocolSecret response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createMeasurementProtocolSecret(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, + ( + | protos.google.analytics.admin.v1beta.ICreateMeasurementProtocolSecretRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'createMeasurementProtocolSecret response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes target MeasurementProtocolSecret. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the MeasurementProtocolSecret to delete. - * Format: - * properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret} - * @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/v1beta/analytics_admin_service.delete_measurement_protocol_secret.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteMeasurementProtocolSecret_async - */ + /** + * Deletes target MeasurementProtocolSecret. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the MeasurementProtocolSecret to delete. + * Format: + * properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret} + * @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/v1beta/analytics_admin_service.delete_measurement_protocol_secret.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteMeasurementProtocolSecret_async + */ deleteMeasurementProtocolSecret( - request?: protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest + | undefined + ), + {} | undefined, + ] + >; deleteMeasurementProtocolSecret( - request: protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteMeasurementProtocolSecret( - request: protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteMeasurementProtocolSecret( - request?: protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest + | 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('deleteMeasurementProtocolSecret request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('deleteMeasurementProtocolSecret response %j', response); + this._log.info( + 'deleteMeasurementProtocolSecret response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteMeasurementProtocolSecret(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteMeasurementProtocolSecret response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteMeasurementProtocolSecret(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1beta.IDeleteMeasurementProtocolSecretRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'deleteMeasurementProtocolSecret response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a measurement protocol secret. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1beta.MeasurementProtocolSecret} request.measurementProtocolSecret - * Required. The measurement protocol secret to update. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Omitted fields will not 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.analytics.admin.v1beta.MeasurementProtocolSecret|MeasurementProtocolSecret}. - * 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/v1beta/analytics_admin_service.update_measurement_protocol_secret.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateMeasurementProtocolSecret_async - */ + /** + * Updates a measurement protocol secret. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1beta.MeasurementProtocolSecret} request.measurementProtocolSecret + * Required. The measurement protocol secret to update. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Omitted fields will not 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.analytics.admin.v1beta.MeasurementProtocolSecret|MeasurementProtocolSecret}. + * 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/v1beta/analytics_admin_service.update_measurement_protocol_secret.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateMeasurementProtocolSecret_async + */ updateMeasurementProtocolSecret( - request?: protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, + ( + | protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest + | undefined + ), + {} | undefined, + ] + >; updateMeasurementProtocolSecret( - request: protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateMeasurementProtocolSecret( - request: protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateMeasurementProtocolSecret( - request?: protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, + ( + | protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest + | 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({ - 'measurement_protocol_secret.name': request.measurementProtocolSecret!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'measurement_protocol_secret.name': + request.measurementProtocolSecret!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateMeasurementProtocolSecret request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, + | protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { - this._log.info('updateMeasurementProtocolSecret response %j', response); + this._log.info( + 'updateMeasurementProtocolSecret response %j', + response, + ); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateMeasurementProtocolSecret(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, - protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateMeasurementProtocolSecret response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateMeasurementProtocolSecret(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret, + ( + | protos.google.analytics.admin.v1beta.IUpdateMeasurementProtocolSecretRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info( + 'updateMeasurementProtocolSecret response %j', + response, + ); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Acknowledges the terms of user data collection for the specified property. - * - * This acknowledgement must be completed (either in the Google Analytics UI - * or through this API) before MeasurementProtocolSecret resources may be - * created. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.property - * Required. The property for which to acknowledge user data collection. - * @param {string} request.acknowledgement - * Required. An acknowledgement that the caller of this method understands the - * terms of user data collection. - * - * This field must contain the exact value: - * "I acknowledge that I have the necessary privacy disclosures and rights - * from my end users for the collection and processing of their data, - * including the association of such data with the visitation information - * Google Analytics collects from my site and/or app property." - * @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.analytics.admin.v1beta.AcknowledgeUserDataCollectionResponse|AcknowledgeUserDataCollectionResponse}. - * 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/v1beta/analytics_admin_service.acknowledge_user_data_collection.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_AcknowledgeUserDataCollection_async - */ + /** + * Acknowledges the terms of user data collection for the specified property. + * + * This acknowledgement must be completed (either in the Google Analytics UI + * or through this API) before MeasurementProtocolSecret resources may be + * created. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.property + * Required. The property for which to acknowledge user data collection. + * @param {string} request.acknowledgement + * Required. An acknowledgement that the caller of this method understands the + * terms of user data collection. + * + * This field must contain the exact value: + * "I acknowledge that I have the necessary privacy disclosures and rights + * from my end users for the collection and processing of their data, + * including the association of such data with the visitation information + * Google Analytics collects from my site and/or app property." + * @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.analytics.admin.v1beta.AcknowledgeUserDataCollectionResponse|AcknowledgeUserDataCollectionResponse}. + * 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/v1beta/analytics_admin_service.acknowledge_user_data_collection.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_AcknowledgeUserDataCollection_async + */ acknowledgeUserDataCollection( - request?: protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionResponse, - protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionResponse, + ( + | protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest + | undefined + ), + {} | undefined, + ] + >; acknowledgeUserDataCollection( - request: protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionResponse, - protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionResponse, + | protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; acknowledgeUserDataCollection( - request: protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionResponse, - protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionResponse, + | protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; acknowledgeUserDataCollection( - request?: protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionResponse, - protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionResponse, - protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionResponse, - protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionResponse, + | protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionResponse, + ( + | protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest + | 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({ - 'property': request.property ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + property: request.property ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('acknowledgeUserDataCollection request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionResponse, - protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionResponse, + | protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('acknowledgeUserDataCollection response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.acknowledgeUserDataCollection(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionResponse, - protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest|undefined, - {}|undefined - ]) => { - this._log.info('acknowledgeUserDataCollection response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .acknowledgeUserDataCollection(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionResponse, + ( + | protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('acknowledgeUserDataCollection response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deprecated: Use `CreateKeyEvent` instead. - * Creates a conversion event with the specified attributes. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1beta.ConversionEvent} request.conversionEvent - * Required. The conversion event to create. - * @param {string} request.parent - * Required. The resource name of the parent property where this conversion - * event will be created. Format: properties/123 - * @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.analytics.admin.v1beta.ConversionEvent|ConversionEvent}. - * 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/v1beta/analytics_admin_service.create_conversion_event.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateConversionEvent_async - * @deprecated CreateConversionEvent is deprecated and may be removed in a future version. - */ + /** + * Deprecated: Use `CreateKeyEvent` instead. + * Creates a conversion event with the specified attributes. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1beta.ConversionEvent} request.conversionEvent + * Required. The conversion event to create. + * @param {string} request.parent + * Required. The resource name of the parent property where this conversion + * event will be created. Format: properties/123 + * @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.analytics.admin.v1beta.ConversionEvent|ConversionEvent}. + * 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/v1beta/analytics_admin_service.create_conversion_event.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateConversionEvent_async + * @deprecated CreateConversionEvent is deprecated and may be removed in a future version. + */ createConversionEvent( - request?: protos.google.analytics.admin.v1beta.ICreateConversionEventRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.ICreateConversionEventRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.ICreateConversionEventRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IConversionEvent, + ( + | protos.google.analytics.admin.v1beta.ICreateConversionEventRequest + | undefined + ), + {} | undefined, + ] + >; createConversionEvent( - request: protos.google.analytics.admin.v1beta.ICreateConversionEventRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.ICreateConversionEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.ICreateConversionEventRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IConversionEvent, + | protos.google.analytics.admin.v1beta.ICreateConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createConversionEvent( - request: protos.google.analytics.admin.v1beta.ICreateConversionEventRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.ICreateConversionEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.ICreateConversionEventRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IConversionEvent, + | protos.google.analytics.admin.v1beta.ICreateConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createConversionEvent( - request?: protos.google.analytics.admin.v1beta.ICreateConversionEventRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.ICreateConversionEventRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.ICreateConversionEventRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.ICreateConversionEventRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.ICreateConversionEventRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.ICreateConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IConversionEvent, + | protos.google.analytics.admin.v1beta.ICreateConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IConversionEvent, + ( + | protos.google.analytics.admin.v1beta.ICreateConversionEventRequest + | 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.warn('DEP$AnalyticsAdminService-$CreateConversionEvent','CreateConversionEvent is deprecated and may be removed in a future version.', 'DeprecationWarning'); + this.warn( + 'DEP$AnalyticsAdminService-$CreateConversionEvent', + 'CreateConversionEvent is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); this._log.info('createConversionEvent request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.ICreateConversionEventRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IConversionEvent, + | protos.google.analytics.admin.v1beta.ICreateConversionEventRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createConversionEvent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createConversionEvent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.ICreateConversionEventRequest|undefined, - {}|undefined - ]) => { - this._log.info('createConversionEvent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createConversionEvent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IConversionEvent, + ( + | protos.google.analytics.admin.v1beta.ICreateConversionEventRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createConversionEvent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deprecated: Use `UpdateKeyEvent` instead. - * Updates a conversion event with the specified attributes. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1beta.ConversionEvent} request.conversionEvent - * Required. The conversion event to update. - * The `name` field is used to identify the settings to be updated. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Field names must be in snake - * case (e.g., "field_to_update"). Omitted fields will not be updated. To - * replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1beta.ConversionEvent|ConversionEvent}. - * 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/v1beta/analytics_admin_service.update_conversion_event.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateConversionEvent_async - * @deprecated UpdateConversionEvent is deprecated and may be removed in a future version. - */ + /** + * Deprecated: Use `UpdateKeyEvent` instead. + * Updates a conversion event with the specified attributes. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1beta.ConversionEvent} request.conversionEvent + * Required. The conversion event to update. + * The `name` field is used to identify the settings to be updated. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Field names must be in snake + * case (e.g., "field_to_update"). Omitted fields will not be updated. To + * replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1beta.ConversionEvent|ConversionEvent}. + * 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/v1beta/analytics_admin_service.update_conversion_event.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateConversionEvent_async + * @deprecated UpdateConversionEvent is deprecated and may be removed in a future version. + */ updateConversionEvent( - request?: protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IConversionEvent, + ( + | protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest + | undefined + ), + {} | undefined, + ] + >; updateConversionEvent( - request: protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IConversionEvent, + | protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateConversionEvent( - request: protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IConversionEvent, + | protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateConversionEvent( - request?: protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IConversionEvent, + | protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IConversionEvent, + ( + | protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest + | 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({ - 'conversion_event.name': request.conversionEvent!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'conversion_event.name': request.conversionEvent!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - this.warn('DEP$AnalyticsAdminService-$UpdateConversionEvent','UpdateConversionEvent is deprecated and may be removed in a future version.', 'DeprecationWarning'); + this.warn( + 'DEP$AnalyticsAdminService-$UpdateConversionEvent', + 'UpdateConversionEvent is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); this._log.info('updateConversionEvent request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IConversionEvent, + | protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateConversionEvent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateConversionEvent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateConversionEvent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateConversionEvent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IConversionEvent, + ( + | protos.google.analytics.admin.v1beta.IUpdateConversionEventRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateConversionEvent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deprecated: Use `GetKeyEvent` instead. - * Retrieve a single conversion event. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the conversion event to retrieve. - * Format: properties/{property}/conversionEvents/{conversion_event} - * Example: "properties/123/conversionEvents/456" - * @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.analytics.admin.v1beta.ConversionEvent|ConversionEvent}. - * 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/v1beta/analytics_admin_service.get_conversion_event.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_GetConversionEvent_async - * @deprecated GetConversionEvent is deprecated and may be removed in a future version. - */ + /** + * Deprecated: Use `GetKeyEvent` instead. + * Retrieve a single conversion event. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the conversion event to retrieve. + * Format: properties/{property}/conversionEvents/{conversion_event} + * Example: "properties/123/conversionEvents/456" + * @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.analytics.admin.v1beta.ConversionEvent|ConversionEvent}. + * 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/v1beta/analytics_admin_service.get_conversion_event.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_GetConversionEvent_async + * @deprecated GetConversionEvent is deprecated and may be removed in a future version. + */ getConversionEvent( - request?: protos.google.analytics.admin.v1beta.IGetConversionEventRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.IGetConversionEventRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IGetConversionEventRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IConversionEvent, + ( + | protos.google.analytics.admin.v1beta.IGetConversionEventRequest + | undefined + ), + {} | undefined, + ] + >; getConversionEvent( - request: protos.google.analytics.admin.v1beta.IGetConversionEventRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.IGetConversionEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IGetConversionEventRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IConversionEvent, + | protos.google.analytics.admin.v1beta.IGetConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getConversionEvent( - request: protos.google.analytics.admin.v1beta.IGetConversionEventRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.IGetConversionEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IGetConversionEventRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IConversionEvent, + | protos.google.analytics.admin.v1beta.IGetConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getConversionEvent( - request?: protos.google.analytics.admin.v1beta.IGetConversionEventRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.IGetConversionEventRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.IGetConversionEventRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.IGetConversionEventRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.IGetConversionEventRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IGetConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IConversionEvent, + | protos.google.analytics.admin.v1beta.IGetConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IConversionEvent, + ( + | protos.google.analytics.admin.v1beta.IGetConversionEventRequest + | 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.warn('DEP$AnalyticsAdminService-$GetConversionEvent','GetConversionEvent is deprecated and may be removed in a future version.', 'DeprecationWarning'); + this.warn( + 'DEP$AnalyticsAdminService-$GetConversionEvent', + 'GetConversionEvent is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); this._log.info('getConversionEvent request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.IGetConversionEventRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IConversionEvent, + | protos.google.analytics.admin.v1beta.IGetConversionEventRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getConversionEvent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getConversionEvent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IConversionEvent, - protos.google.analytics.admin.v1beta.IGetConversionEventRequest|undefined, - {}|undefined - ]) => { - this._log.info('getConversionEvent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getConversionEvent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IConversionEvent, + ( + | protos.google.analytics.admin.v1beta.IGetConversionEventRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getConversionEvent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deprecated: Use `DeleteKeyEvent` instead. - * Deletes a conversion event in a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the conversion event to delete. - * Format: properties/{property}/conversionEvents/{conversion_event} - * Example: "properties/123/conversionEvents/456" - * @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/v1beta/analytics_admin_service.delete_conversion_event.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteConversionEvent_async - * @deprecated DeleteConversionEvent is deprecated and may be removed in a future version. - */ + /** + * Deprecated: Use `DeleteKeyEvent` instead. + * Deletes a conversion event in a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the conversion event to delete. + * Format: properties/{property}/conversionEvents/{conversion_event} + * Example: "properties/123/conversionEvents/456" + * @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/v1beta/analytics_admin_service.delete_conversion_event.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteConversionEvent_async + * @deprecated DeleteConversionEvent is deprecated and may be removed in a future version. + */ deleteConversionEvent( - request?: protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest + | undefined + ), + {} | undefined, + ] + >; deleteConversionEvent( - request: protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteConversionEvent( - request: protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteConversionEvent( - request?: protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest + | 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.warn('DEP$AnalyticsAdminService-$DeleteConversionEvent','DeleteConversionEvent is deprecated and may be removed in a future version.', 'DeprecationWarning'); + this.warn( + 'DEP$AnalyticsAdminService-$DeleteConversionEvent', + 'DeleteConversionEvent is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); this._log.info('deleteConversionEvent request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteConversionEvent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteConversionEvent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteConversionEvent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteConversionEvent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1beta.IDeleteConversionEventRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteConversionEvent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a Key Event. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1beta.KeyEvent} request.keyEvent - * Required. The Key Event to create. - * @param {string} request.parent - * Required. The resource name of the parent property where this Key Event - * will be created. Format: properties/123 - * @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.analytics.admin.v1beta.KeyEvent|KeyEvent}. - * 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/v1beta/analytics_admin_service.create_key_event.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateKeyEvent_async - */ + /** + * Creates a Key Event. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1beta.KeyEvent} request.keyEvent + * Required. The Key Event to create. + * @param {string} request.parent + * Required. The resource name of the parent property where this Key Event + * will be created. Format: properties/123 + * @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.analytics.admin.v1beta.KeyEvent|KeyEvent}. + * 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/v1beta/analytics_admin_service.create_key_event.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateKeyEvent_async + */ createKeyEvent( - request?: protos.google.analytics.admin.v1beta.ICreateKeyEventRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.ICreateKeyEventRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.ICreateKeyEventRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IKeyEvent, + protos.google.analytics.admin.v1beta.ICreateKeyEventRequest | undefined, + {} | undefined, + ] + >; createKeyEvent( - request: protos.google.analytics.admin.v1beta.ICreateKeyEventRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.ICreateKeyEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.ICreateKeyEventRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IKeyEvent, + | protos.google.analytics.admin.v1beta.ICreateKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createKeyEvent( - request: protos.google.analytics.admin.v1beta.ICreateKeyEventRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.ICreateKeyEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.ICreateKeyEventRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IKeyEvent, + | protos.google.analytics.admin.v1beta.ICreateKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createKeyEvent( - request?: protos.google.analytics.admin.v1beta.ICreateKeyEventRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.ICreateKeyEventRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.ICreateKeyEventRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.ICreateKeyEventRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.ICreateKeyEventRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.ICreateKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IKeyEvent, + | protos.google.analytics.admin.v1beta.ICreateKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IKeyEvent, + protos.google.analytics.admin.v1beta.ICreateKeyEventRequest | 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('createKeyEvent request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.ICreateKeyEventRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IKeyEvent, + | protos.google.analytics.admin.v1beta.ICreateKeyEventRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createKeyEvent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createKeyEvent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.ICreateKeyEventRequest|undefined, - {}|undefined - ]) => { - this._log.info('createKeyEvent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createKeyEvent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IKeyEvent, + ( + | protos.google.analytics.admin.v1beta.ICreateKeyEventRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createKeyEvent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a Key Event. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1beta.KeyEvent} request.keyEvent - * Required. The Key Event to update. - * The `name` field is used to identify the settings to be updated. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Field names must be in snake - * case (e.g., "field_to_update"). Omitted fields will not be updated. To - * replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1beta.KeyEvent|KeyEvent}. - * 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/v1beta/analytics_admin_service.update_key_event.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateKeyEvent_async - */ + /** + * Updates a Key Event. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1beta.KeyEvent} request.keyEvent + * Required. The Key Event to update. + * The `name` field is used to identify the settings to be updated. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Field names must be in snake + * case (e.g., "field_to_update"). Omitted fields will not be updated. To + * replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1beta.KeyEvent|KeyEvent}. + * 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/v1beta/analytics_admin_service.update_key_event.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateKeyEvent_async + */ updateKeyEvent( - request?: protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IKeyEvent, + protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest | undefined, + {} | undefined, + ] + >; updateKeyEvent( - request: protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IKeyEvent, + | protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateKeyEvent( - request: protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IKeyEvent, + | protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateKeyEvent( - request?: protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IKeyEvent, + | protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IKeyEvent, + protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest | 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({ - 'key_event.name': request.keyEvent!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'key_event.name': request.keyEvent!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateKeyEvent request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IKeyEvent, + | protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateKeyEvent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateKeyEvent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateKeyEvent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateKeyEvent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IKeyEvent, + ( + | protos.google.analytics.admin.v1beta.IUpdateKeyEventRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateKeyEvent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieve a single Key Event. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the Key Event to retrieve. - * Format: properties/{property}/keyEvents/{key_event} - * Example: "properties/123/keyEvents/456" - * @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.analytics.admin.v1beta.KeyEvent|KeyEvent}. - * 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/v1beta/analytics_admin_service.get_key_event.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_GetKeyEvent_async - */ + /** + * Retrieve a single Key Event. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Key Event to retrieve. + * Format: properties/{property}/keyEvents/{key_event} + * Example: "properties/123/keyEvents/456" + * @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.analytics.admin.v1beta.KeyEvent|KeyEvent}. + * 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/v1beta/analytics_admin_service.get_key_event.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_GetKeyEvent_async + */ getKeyEvent( - request?: protos.google.analytics.admin.v1beta.IGetKeyEventRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.IGetKeyEventRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IGetKeyEventRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IKeyEvent, + protos.google.analytics.admin.v1beta.IGetKeyEventRequest | undefined, + {} | undefined, + ] + >; getKeyEvent( - request: protos.google.analytics.admin.v1beta.IGetKeyEventRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.IGetKeyEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IGetKeyEventRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IKeyEvent, + | protos.google.analytics.admin.v1beta.IGetKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getKeyEvent( - request: protos.google.analytics.admin.v1beta.IGetKeyEventRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.IGetKeyEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IGetKeyEventRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IKeyEvent, + | protos.google.analytics.admin.v1beta.IGetKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getKeyEvent( - request?: protos.google.analytics.admin.v1beta.IGetKeyEventRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.IGetKeyEventRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.IGetKeyEventRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.IGetKeyEventRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.IGetKeyEventRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IGetKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IKeyEvent, + | protos.google.analytics.admin.v1beta.IGetKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IKeyEvent, + protos.google.analytics.admin.v1beta.IGetKeyEventRequest | 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('getKeyEvent request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.IGetKeyEventRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IKeyEvent, + | protos.google.analytics.admin.v1beta.IGetKeyEventRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getKeyEvent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getKeyEvent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IKeyEvent, - protos.google.analytics.admin.v1beta.IGetKeyEventRequest|undefined, - {}|undefined - ]) => { - this._log.info('getKeyEvent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getKeyEvent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IKeyEvent, + protos.google.analytics.admin.v1beta.IGetKeyEventRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getKeyEvent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a Key Event. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the Key Event to delete. - * Format: properties/{property}/keyEvents/{key_event} - * Example: "properties/123/keyEvents/456" - * @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/v1beta/analytics_admin_service.delete_key_event.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteKeyEvent_async - */ + /** + * Deletes a Key Event. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Key Event to delete. + * Format: properties/{property}/keyEvents/{key_event} + * Example: "properties/123/keyEvents/456" + * @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/v1beta/analytics_admin_service.delete_key_event.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteKeyEvent_async + */ deleteKeyEvent( - request?: protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest | undefined, + {} | undefined, + ] + >; deleteKeyEvent( - request: protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteKeyEvent( - request: protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteKeyEvent( - request?: protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest | 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('deleteKeyEvent request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteKeyEvent response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteKeyEvent(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteKeyEvent response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteKeyEvent(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1beta.IDeleteKeyEventRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteKeyEvent response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a CustomDimension. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {google.analytics.admin.v1beta.CustomDimension} request.customDimension - * Required. The CustomDimension 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.analytics.admin.v1beta.CustomDimension|CustomDimension}. - * 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/v1beta/analytics_admin_service.create_custom_dimension.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateCustomDimension_async - */ + /** + * Creates a CustomDimension. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {google.analytics.admin.v1beta.CustomDimension} request.customDimension + * Required. The CustomDimension 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.analytics.admin.v1beta.CustomDimension|CustomDimension}. + * 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/v1beta/analytics_admin_service.create_custom_dimension.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateCustomDimension_async + */ createCustomDimension( - request?: protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.ICustomDimension, + ( + | protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest + | undefined + ), + {} | undefined, + ] + >; createCustomDimension( - request: protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.ICustomDimension, + | protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createCustomDimension( - request: protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.ICustomDimension, + | protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createCustomDimension( - request?: protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.ICustomDimension, + | protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.ICustomDimension, + ( + | protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest + | 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('createCustomDimension request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.ICustomDimension, + | protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createCustomDimension response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createCustomDimension(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest|undefined, - {}|undefined - ]) => { - this._log.info('createCustomDimension response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createCustomDimension(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.ICustomDimension, + ( + | protos.google.analytics.admin.v1beta.ICreateCustomDimensionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createCustomDimension response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a CustomDimension on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1beta.CustomDimension} request.customDimension - * The CustomDimension to update - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Omitted fields will not be - * updated. To replace the entire entity, use one path with the string "*" to - * match all fields. - * @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.analytics.admin.v1beta.CustomDimension|CustomDimension}. - * 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/v1beta/analytics_admin_service.update_custom_dimension.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateCustomDimension_async - */ + /** + * Updates a CustomDimension on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1beta.CustomDimension} request.customDimension + * The CustomDimension to update + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Omitted fields will not be + * updated. To replace the entire entity, use one path with the string "*" to + * match all fields. + * @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.analytics.admin.v1beta.CustomDimension|CustomDimension}. + * 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/v1beta/analytics_admin_service.update_custom_dimension.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateCustomDimension_async + */ updateCustomDimension( - request?: protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.ICustomDimension, + ( + | protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest + | undefined + ), + {} | undefined, + ] + >; updateCustomDimension( - request: protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.ICustomDimension, + | protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCustomDimension( - request: protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.ICustomDimension, + | protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCustomDimension( - request?: protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.ICustomDimension, + | protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.ICustomDimension, + ( + | protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest + | 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({ - 'custom_dimension.name': request.customDimension!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'custom_dimension.name': request.customDimension!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateCustomDimension request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.ICustomDimension, + | protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateCustomDimension response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateCustomDimension(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateCustomDimension response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateCustomDimension(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.ICustomDimension, + ( + | protos.google.analytics.admin.v1beta.IUpdateCustomDimensionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateCustomDimension response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Archives a CustomDimension on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the CustomDimension to archive. - * Example format: properties/1234/customDimensions/5678 - * @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/v1beta/analytics_admin_service.archive_custom_dimension.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ArchiveCustomDimension_async - */ + /** + * Archives a CustomDimension on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the CustomDimension to archive. + * Example format: properties/1234/customDimensions/5678 + * @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/v1beta/analytics_admin_service.archive_custom_dimension.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ArchiveCustomDimension_async + */ archiveCustomDimension( - request?: protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest + | undefined + ), + {} | undefined, + ] + >; archiveCustomDimension( - request: protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; archiveCustomDimension( - request: protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; archiveCustomDimension( - request?: protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest + | 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('archiveCustomDimension request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('archiveCustomDimension response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.archiveCustomDimension(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest|undefined, - {}|undefined - ]) => { - this._log.info('archiveCustomDimension response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .archiveCustomDimension(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1beta.IArchiveCustomDimensionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('archiveCustomDimension response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for a single CustomDimension. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the CustomDimension to get. - * Example format: properties/1234/customDimensions/5678 - * @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.analytics.admin.v1beta.CustomDimension|CustomDimension}. - * 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/v1beta/analytics_admin_service.get_custom_dimension.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_GetCustomDimension_async - */ + /** + * Lookup for a single CustomDimension. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the CustomDimension to get. + * Example format: properties/1234/customDimensions/5678 + * @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.analytics.admin.v1beta.CustomDimension|CustomDimension}. + * 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/v1beta/analytics_admin_service.get_custom_dimension.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_GetCustomDimension_async + */ getCustomDimension( - request?: protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.ICustomDimension, + ( + | protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest + | undefined + ), + {} | undefined, + ] + >; getCustomDimension( - request: protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.ICustomDimension, + | protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getCustomDimension( - request: protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.ICustomDimension, + | protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getCustomDimension( - request?: protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.ICustomDimension, + | protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.ICustomDimension, + ( + | protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest + | 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('getCustomDimension request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.ICustomDimension, + | protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getCustomDimension response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getCustomDimension(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.ICustomDimension, - protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest|undefined, - {}|undefined - ]) => { - this._log.info('getCustomDimension response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getCustomDimension(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.ICustomDimension, + ( + | protos.google.analytics.admin.v1beta.IGetCustomDimensionRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getCustomDimension response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a CustomMetric. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {google.analytics.admin.v1beta.CustomMetric} request.customMetric - * Required. The CustomMetric 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.analytics.admin.v1beta.CustomMetric|CustomMetric}. - * 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/v1beta/analytics_admin_service.create_custom_metric.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateCustomMetric_async - */ + /** + * Creates a CustomMetric. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {google.analytics.admin.v1beta.CustomMetric} request.customMetric + * Required. The CustomMetric 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.analytics.admin.v1beta.CustomMetric|CustomMetric}. + * 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/v1beta/analytics_admin_service.create_custom_metric.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateCustomMetric_async + */ createCustomMetric( - request?: protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.ICustomMetric, + ( + | protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest + | undefined + ), + {} | undefined, + ] + >; createCustomMetric( - request: protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.ICustomMetric, + | protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createCustomMetric( - request: protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.ICustomMetric, + | protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createCustomMetric( - request?: protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.ICustomMetric, + | protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.ICustomMetric, + ( + | protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest + | 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('createCustomMetric request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.ICustomMetric, + | protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createCustomMetric response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createCustomMetric(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest|undefined, - {}|undefined - ]) => { - this._log.info('createCustomMetric response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createCustomMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.ICustomMetric, + ( + | protos.google.analytics.admin.v1beta.ICreateCustomMetricRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createCustomMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a CustomMetric on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1beta.CustomMetric} request.customMetric - * The CustomMetric to update - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Omitted fields will not be - * updated. To replace the entire entity, use one path with the string "*" to - * match all fields. - * @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.analytics.admin.v1beta.CustomMetric|CustomMetric}. - * 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/v1beta/analytics_admin_service.update_custom_metric.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateCustomMetric_async - */ + /** + * Updates a CustomMetric on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1beta.CustomMetric} request.customMetric + * The CustomMetric to update + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Omitted fields will not be + * updated. To replace the entire entity, use one path with the string "*" to + * match all fields. + * @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.analytics.admin.v1beta.CustomMetric|CustomMetric}. + * 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/v1beta/analytics_admin_service.update_custom_metric.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateCustomMetric_async + */ updateCustomMetric( - request?: protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.ICustomMetric, + ( + | protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest + | undefined + ), + {} | undefined, + ] + >; updateCustomMetric( - request: protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.ICustomMetric, + | protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCustomMetric( - request: protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.ICustomMetric, + | protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateCustomMetric( - request?: protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.ICustomMetric, + | protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.ICustomMetric, + ( + | protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest + | 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({ - 'custom_metric.name': request.customMetric!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'custom_metric.name': request.customMetric!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateCustomMetric request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.ICustomMetric, + | protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateCustomMetric response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateCustomMetric(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateCustomMetric response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateCustomMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.ICustomMetric, + ( + | protos.google.analytics.admin.v1beta.IUpdateCustomMetricRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateCustomMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Archives a CustomMetric on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the CustomMetric to archive. - * Example format: properties/1234/customMetrics/5678 - * @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/v1beta/analytics_admin_service.archive_custom_metric.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ArchiveCustomMetric_async - */ + /** + * Archives a CustomMetric on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the CustomMetric to archive. + * Example format: properties/1234/customMetrics/5678 + * @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/v1beta/analytics_admin_service.archive_custom_metric.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ArchiveCustomMetric_async + */ archiveCustomMetric( - request?: protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest + | undefined + ), + {} | undefined, + ] + >; archiveCustomMetric( - request: protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; archiveCustomMetric( - request: protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; archiveCustomMetric( - request?: protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest + | 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('archiveCustomMetric request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('archiveCustomMetric response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.archiveCustomMetric(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest|undefined, - {}|undefined - ]) => { - this._log.info('archiveCustomMetric response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .archiveCustomMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1beta.IArchiveCustomMetricRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('archiveCustomMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for a single CustomMetric. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the CustomMetric to get. - * Example format: properties/1234/customMetrics/5678 - * @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.analytics.admin.v1beta.CustomMetric|CustomMetric}. - * 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/v1beta/analytics_admin_service.get_custom_metric.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_GetCustomMetric_async - */ + /** + * Lookup for a single CustomMetric. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the CustomMetric to get. + * Example format: properties/1234/customMetrics/5678 + * @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.analytics.admin.v1beta.CustomMetric|CustomMetric}. + * 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/v1beta/analytics_admin_service.get_custom_metric.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_GetCustomMetric_async + */ getCustomMetric( - request?: protos.google.analytics.admin.v1beta.IGetCustomMetricRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.IGetCustomMetricRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IGetCustomMetricRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.ICustomMetric, + protos.google.analytics.admin.v1beta.IGetCustomMetricRequest | undefined, + {} | undefined, + ] + >; getCustomMetric( - request: protos.google.analytics.admin.v1beta.IGetCustomMetricRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.IGetCustomMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IGetCustomMetricRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.ICustomMetric, + | protos.google.analytics.admin.v1beta.IGetCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getCustomMetric( - request: protos.google.analytics.admin.v1beta.IGetCustomMetricRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.IGetCustomMetricRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IGetCustomMetricRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.ICustomMetric, + | protos.google.analytics.admin.v1beta.IGetCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getCustomMetric( - request?: protos.google.analytics.admin.v1beta.IGetCustomMetricRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1beta.IGetCustomMetricRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.IGetCustomMetricRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.IGetCustomMetricRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.IGetCustomMetricRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IGetCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.ICustomMetric, + | protos.google.analytics.admin.v1beta.IGetCustomMetricRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.ICustomMetric, + protos.google.analytics.admin.v1beta.IGetCustomMetricRequest | 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('getCustomMetric request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.IGetCustomMetricRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.ICustomMetric, + | protos.google.analytics.admin.v1beta.IGetCustomMetricRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getCustomMetric response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getCustomMetric(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.ICustomMetric, - protos.google.analytics.admin.v1beta.IGetCustomMetricRequest|undefined, - {}|undefined - ]) => { - this._log.info('getCustomMetric response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getCustomMetric(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.ICustomMetric, + ( + | protos.google.analytics.admin.v1beta.IGetCustomMetricRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getCustomMetric response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns the singleton data retention settings for this property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the settings to lookup. - * Format: - * properties/{property}/dataRetentionSettings - * Example: "properties/1000/dataRetentionSettings" - * @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.analytics.admin.v1beta.DataRetentionSettings|DataRetentionSettings}. - * 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/v1beta/analytics_admin_service.get_data_retention_settings.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataRetentionSettings_async - */ + /** + * Returns the singleton data retention settings for this property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the settings to lookup. + * Format: + * properties/{property}/dataRetentionSettings + * Example: "properties/1000/dataRetentionSettings" + * @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.analytics.admin.v1beta.DataRetentionSettings|DataRetentionSettings}. + * 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/v1beta/analytics_admin_service.get_data_retention_settings.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataRetentionSettings_async + */ getDataRetentionSettings( - request?: protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IDataRetentionSettings, - protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IDataRetentionSettings, + ( + | protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest + | undefined + ), + {} | undefined, + ] + >; getDataRetentionSettings( - request: protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IDataRetentionSettings, - protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IDataRetentionSettings, + | protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDataRetentionSettings( - request: protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IDataRetentionSettings, - protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IDataRetentionSettings, + | protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDataRetentionSettings( - request?: protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IDataRetentionSettings, - protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.analytics.admin.v1beta.IDataRetentionSettings, - protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IDataRetentionSettings, - protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IDataRetentionSettings, + | protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IDataRetentionSettings, + ( + | protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest + | 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('getDataRetentionSettings request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IDataRetentionSettings, - protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IDataRetentionSettings, + | protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getDataRetentionSettings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getDataRetentionSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IDataRetentionSettings, - protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('getDataRetentionSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getDataRetentionSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IDataRetentionSettings, + ( + | protos.google.analytics.admin.v1beta.IGetDataRetentionSettingsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getDataRetentionSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the singleton data retention settings for this property. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1beta.DataRetentionSettings} request.dataRetentionSettings - * Required. The settings to update. - * The `name` field is used to identify the settings to be updated. - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Field names must be in snake - * case (e.g., "field_to_update"). Omitted fields will not be updated. To - * replace the entire entity, use one path with the string "*" to match all - * fields. - * @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.analytics.admin.v1beta.DataRetentionSettings|DataRetentionSettings}. - * 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/v1beta/analytics_admin_service.update_data_retention_settings.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateDataRetentionSettings_async - */ + /** + * Updates the singleton data retention settings for this property. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1beta.DataRetentionSettings} request.dataRetentionSettings + * Required. The settings to update. + * The `name` field is used to identify the settings to be updated. + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Field names must be in snake + * case (e.g., "field_to_update"). Omitted fields will not be updated. To + * replace the entire entity, use one path with the string "*" to match all + * fields. + * @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.analytics.admin.v1beta.DataRetentionSettings|DataRetentionSettings}. + * 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/v1beta/analytics_admin_service.update_data_retention_settings.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateDataRetentionSettings_async + */ updateDataRetentionSettings( - request?: protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IDataRetentionSettings, - protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IDataRetentionSettings, + ( + | protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest + | undefined + ), + {} | undefined, + ] + >; updateDataRetentionSettings( - request: protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IDataRetentionSettings, - protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IDataRetentionSettings, + | protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDataRetentionSettings( - request: protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IDataRetentionSettings, - protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IDataRetentionSettings, + | protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDataRetentionSettings( - request?: protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1beta.IDataRetentionSettings, - protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IDataRetentionSettings, - protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IDataRetentionSettings, - protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IDataRetentionSettings, + | protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IDataRetentionSettings, + ( + | protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest + | 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({ - 'data_retention_settings.name': request.dataRetentionSettings!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'data_retention_settings.name': + request.dataRetentionSettings!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateDataRetentionSettings request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IDataRetentionSettings, - protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IDataRetentionSettings, + | protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateDataRetentionSettings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateDataRetentionSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IDataRetentionSettings, - protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateDataRetentionSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateDataRetentionSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IDataRetentionSettings, + ( + | protos.google.analytics.admin.v1beta.IUpdateDataRetentionSettingsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateDataRetentionSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a DataStream. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {google.analytics.admin.v1beta.DataStream} request.dataStream - * Required. The DataStream 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.analytics.admin.v1beta.DataStream|DataStream}. - * 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/v1beta/analytics_admin_service.create_data_stream.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateDataStream_async - */ + /** + * Creates a DataStream. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {google.analytics.admin.v1beta.DataStream} request.dataStream + * Required. The DataStream 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.analytics.admin.v1beta.DataStream|DataStream}. + * 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/v1beta/analytics_admin_service.create_data_stream.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateDataStream_async + */ createDataStream( - request?: protos.google.analytics.admin.v1beta.ICreateDataStreamRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.ICreateDataStreamRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.ICreateDataStreamRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IDataStream, + protos.google.analytics.admin.v1beta.ICreateDataStreamRequest | undefined, + {} | undefined, + ] + >; createDataStream( - request: protos.google.analytics.admin.v1beta.ICreateDataStreamRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.ICreateDataStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.ICreateDataStreamRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IDataStream, + | protos.google.analytics.admin.v1beta.ICreateDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createDataStream( - request: protos.google.analytics.admin.v1beta.ICreateDataStreamRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.ICreateDataStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.ICreateDataStreamRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IDataStream, + | protos.google.analytics.admin.v1beta.ICreateDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createDataStream( - request?: protos.google.analytics.admin.v1beta.ICreateDataStreamRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.ICreateDataStreamRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.ICreateDataStreamRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.ICreateDataStreamRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.ICreateDataStreamRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.ICreateDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IDataStream, + | protos.google.analytics.admin.v1beta.ICreateDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IDataStream, + protos.google.analytics.admin.v1beta.ICreateDataStreamRequest | 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('createDataStream request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.ICreateDataStreamRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IDataStream, + | protos.google.analytics.admin.v1beta.ICreateDataStreamRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createDataStream response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createDataStream(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.ICreateDataStreamRequest|undefined, - {}|undefined - ]) => { - this._log.info('createDataStream response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createDataStream(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IDataStream, + ( + | protos.google.analytics.admin.v1beta.ICreateDataStreamRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createDataStream response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Deletes a DataStream on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the DataStream to delete. - * Example format: properties/1234/dataStreams/5678 - * @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/v1beta/analytics_admin_service.delete_data_stream.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteDataStream_async - */ + /** + * Deletes a DataStream on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the DataStream to delete. + * Example format: properties/1234/dataStreams/5678 + * @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/v1beta/analytics_admin_service.delete_data_stream.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteDataStream_async + */ deleteDataStream( - request?: protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest | undefined, + {} | undefined, + ] + >; deleteDataStream( - request: protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteDataStream( - request: protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; deleteDataStream( - request?: protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest | 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('deleteDataStream request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteDataStream response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteDataStream(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteDataStream response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .deleteDataStream(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.analytics.admin.v1beta.IDeleteDataStreamRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteDataStream response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates a DataStream on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.analytics.admin.v1beta.DataStream} request.dataStream - * The DataStream to update - * @param {google.protobuf.FieldMask} request.updateMask - * Required. The list of fields to be updated. Omitted fields will not be - * updated. To replace the entire entity, use one path with the string "*" to - * match all fields. - * @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.analytics.admin.v1beta.DataStream|DataStream}. - * 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/v1beta/analytics_admin_service.update_data_stream.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateDataStream_async - */ + /** + * Updates a DataStream on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.analytics.admin.v1beta.DataStream} request.dataStream + * The DataStream to update + * @param {google.protobuf.FieldMask} request.updateMask + * Required. The list of fields to be updated. Omitted fields will not be + * updated. To replace the entire entity, use one path with the string "*" to + * match all fields. + * @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.analytics.admin.v1beta.DataStream|DataStream}. + * 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/v1beta/analytics_admin_service.update_data_stream.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateDataStream_async + */ updateDataStream( - request?: protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IDataStream, + protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest | undefined, + {} | undefined, + ] + >; updateDataStream( - request: protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IDataStream, + | protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDataStream( - request: protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IDataStream, + | protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateDataStream( - request?: protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IDataStream, + | protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IDataStream, + protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest | 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({ - 'data_stream.name': request.dataStream!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'data_stream.name': request.dataStream!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateDataStream request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IDataStream, + | protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateDataStream response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateDataStream(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateDataStream response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateDataStream(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IDataStream, + ( + | protos.google.analytics.admin.v1beta.IUpdateDataStreamRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateDataStream response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Lookup for a single DataStream. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the DataStream to get. - * Example format: properties/1234/dataStreams/5678 - * @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.analytics.admin.v1beta.DataStream|DataStream}. - * 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/v1beta/analytics_admin_service.get_data_stream.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataStream_async - */ + /** + * Lookup for a single DataStream. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the DataStream to get. + * Example format: properties/1234/dataStreams/5678 + * @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.analytics.admin.v1beta.DataStream|DataStream}. + * 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/v1beta/analytics_admin_service.get_data_stream.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataStream_async + */ getDataStream( - request?: protos.google.analytics.admin.v1beta.IGetDataStreamRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.IGetDataStreamRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IGetDataStreamRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IDataStream, + protos.google.analytics.admin.v1beta.IGetDataStreamRequest | undefined, + {} | undefined, + ] + >; getDataStream( - request: protos.google.analytics.admin.v1beta.IGetDataStreamRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.IGetDataStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IGetDataStreamRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IDataStream, + | protos.google.analytics.admin.v1beta.IGetDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDataStream( - request: protos.google.analytics.admin.v1beta.IGetDataStreamRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.IGetDataStreamRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IGetDataStreamRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IDataStream, + | protos.google.analytics.admin.v1beta.IGetDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getDataStream( - request?: protos.google.analytics.admin.v1beta.IGetDataStreamRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.IGetDataStreamRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.IGetDataStreamRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.IGetDataStreamRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.IGetDataStreamRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IGetDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IDataStream, + | protos.google.analytics.admin.v1beta.IGetDataStreamRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IDataStream, + protos.google.analytics.admin.v1beta.IGetDataStreamRequest | 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('getDataStream request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.IGetDataStreamRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IDataStream, + | protos.google.analytics.admin.v1beta.IGetDataStreamRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getDataStream response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getDataStream(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IDataStream, - protos.google.analytics.admin.v1beta.IGetDataStreamRequest|undefined, - {}|undefined - ]) => { - this._log.info('getDataStream response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getDataStream(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IDataStream, + ( + | protos.google.analytics.admin.v1beta.IGetDataStreamRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getDataStream response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns a customized report of data access records. The report provides - * records of each time a user reads Google Analytics reporting data. Access - * records are retained for up to 2 years. - * - * Data Access Reports can be requested for a property. Reports may be - * requested for any property, but dimensions that aren't related to quota can - * only be requested on Google Analytics 360 properties. This method is only - * available to Administrators. - * - * These data access records include GA UI Reporting, GA UI Explorations, - * GA Data API, and other products like Firebase & Admob that can retrieve - * data from Google Analytics through a linkage. These records don't include - * property configuration changes like adding a stream or changing a - * property's time zone. For configuration change history, see - * [searchChangeHistoryEvents](https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts/searchChangeHistoryEvents). - * - * To give your feedback on this API, complete the [Google Analytics Access - * Reports - * feedback](https://docs.google.com/forms/d/e/1FAIpQLSdmEBUrMzAEdiEKk5TV5dEHvDUZDRlgWYdQdAeSdtR4hVjEhw/viewform) - * form. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.entity - * The Data Access Report supports requesting at the property level or account - * level. If requested at the account level, Data Access Reports include all - * access for all properties under that account. - * - * To request at the property level, entity should be for example - * 'properties/123' if "123" is your Google Analytics property ID. To request - * at the account level, entity should be for example 'accounts/1234' if - * "1234" is your Google Analytics Account ID. - * @param {number[]} request.dimensions - * The dimensions requested and displayed in the response. Requests are - * allowed up to 9 dimensions. - * @param {number[]} request.metrics - * The metrics requested and displayed in the response. Requests are allowed - * up to 10 metrics. - * @param {number[]} request.dateRanges - * Date ranges of access records to read. If multiple date ranges are - * requested, each response row will contain a zero based date range index. If - * two date ranges overlap, the access records for the overlapping days is - * included in the response rows for both date ranges. Requests are allowed up - * to 2 date ranges. - * @param {google.analytics.admin.v1beta.AccessFilterExpression} request.dimensionFilter - * Dimension filters let you restrict report response to specific - * dimension values which match the filter. For example, filtering on access - * records of a single user. To learn more, see [Fundamentals of Dimension - * Filters](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#dimension_filters) - * for examples. Metrics cannot be used in this filter. - * @param {google.analytics.admin.v1beta.AccessFilterExpression} request.metricFilter - * Metric filters allow you to restrict report response to specific metric - * values which match the filter. Metric filters are applied after aggregating - * the report's rows, similar to SQL having-clause. Dimensions cannot be used - * in this filter. - * @param {number} request.offset - * The row count of the start row. The first row is counted as row 0. If - * offset is unspecified, it is treated as 0. If offset is zero, then this - * method will return the first page of results with `limit` entries. - * - * To learn more about this pagination parameter, see - * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). - * @param {number} request.limit - * The number of rows to return. If unspecified, 10,000 rows are returned. The - * API returns a maximum of 100,000 rows per request, no matter how many you - * ask for. `limit` must be positive. - * - * The API may return fewer rows than the requested `limit`, if there aren't - * as many remaining rows as the `limit`. For instance, there are fewer than - * 300 possible values for the dimension `country`, so when reporting on only - * `country`, you can't get more than 300 rows, even if you set `limit` to a - * higher value. - * - * To learn more about this pagination parameter, see - * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). - * @param {string} request.timeZone - * This request's time zone if specified. If unspecified, the property's time - * zone is used. The request's time zone is used to interpret the start & end - * dates of the report. - * - * Formatted as strings from the IANA Time Zone database - * (https://www.iana.org/time-zones); for example "America/New_York" or - * "Asia/Tokyo". - * @param {number[]} request.orderBys - * Specifies how rows are ordered in the response. - * @param {boolean} request.returnEntityQuota - * Toggles whether to return the current state of this Analytics Property's - * quota. Quota is returned in [AccessQuota](#AccessQuota). For account-level - * requests, this field must be false. - * @param {boolean} [request.includeAllUsers] - * Optional. Determines whether to include users who have never made an API - * call in the response. If true, all users with access to the specified - * property or account are included in the response, regardless of whether - * they have made an API call or not. If false, only the users who have made - * an API call will be included. - * @param {boolean} [request.expandGroups] - * Optional. Decides whether to return the users within user groups. This - * field works only when include_all_users is set to true. If true, it will - * return all users with access to the specified property or account. - * If false, only the users with direct access 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 {@link protos.google.analytics.admin.v1beta.RunAccessReportResponse|RunAccessReportResponse}. - * 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/v1beta/analytics_admin_service.run_access_report.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_RunAccessReport_async - */ + /** + * Returns a customized report of data access records. The report provides + * records of each time a user reads Google Analytics reporting data. Access + * records are retained for up to 2 years. + * + * Data Access Reports can be requested for a property. Reports may be + * requested for any property, but dimensions that aren't related to quota can + * only be requested on Google Analytics 360 properties. This method is only + * available to Administrators. + * + * These data access records include GA UI Reporting, GA UI Explorations, + * GA Data API, and other products like Firebase & Admob that can retrieve + * data from Google Analytics through a linkage. These records don't include + * property configuration changes like adding a stream or changing a + * property's time zone. For configuration change history, see + * [searchChangeHistoryEvents](https://developers.google.com/analytics/devguides/config/admin/v1/rest/v1alpha/accounts/searchChangeHistoryEvents). + * + * To give your feedback on this API, complete the [Google Analytics Access + * Reports + * feedback](https://docs.google.com/forms/d/e/1FAIpQLSdmEBUrMzAEdiEKk5TV5dEHvDUZDRlgWYdQdAeSdtR4hVjEhw/viewform) + * form. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.entity + * The Data Access Report supports requesting at the property level or account + * level. If requested at the account level, Data Access Reports include all + * access for all properties under that account. + * + * To request at the property level, entity should be for example + * 'properties/123' if "123" is your Google Analytics property ID. To request + * at the account level, entity should be for example 'accounts/1234' if + * "1234" is your Google Analytics Account ID. + * @param {number[]} request.dimensions + * The dimensions requested and displayed in the response. Requests are + * allowed up to 9 dimensions. + * @param {number[]} request.metrics + * The metrics requested and displayed in the response. Requests are allowed + * up to 10 metrics. + * @param {number[]} request.dateRanges + * Date ranges of access records to read. If multiple date ranges are + * requested, each response row will contain a zero based date range index. If + * two date ranges overlap, the access records for the overlapping days is + * included in the response rows for both date ranges. Requests are allowed up + * to 2 date ranges. + * @param {google.analytics.admin.v1beta.AccessFilterExpression} request.dimensionFilter + * Dimension filters let you restrict report response to specific + * dimension values which match the filter. For example, filtering on access + * records of a single user. To learn more, see [Fundamentals of Dimension + * Filters](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#dimension_filters) + * for examples. Metrics cannot be used in this filter. + * @param {google.analytics.admin.v1beta.AccessFilterExpression} request.metricFilter + * Metric filters allow you to restrict report response to specific metric + * values which match the filter. Metric filters are applied after aggregating + * the report's rows, similar to SQL having-clause. Dimensions cannot be used + * in this filter. + * @param {number} request.offset + * The row count of the start row. The first row is counted as row 0. If + * offset is unspecified, it is treated as 0. If offset is zero, then this + * method will return the first page of results with `limit` entries. + * + * To learn more about this pagination parameter, see + * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). + * @param {number} request.limit + * The number of rows to return. If unspecified, 10,000 rows are returned. The + * API returns a maximum of 100,000 rows per request, no matter how many you + * ask for. `limit` must be positive. + * + * The API may return fewer rows than the requested `limit`, if there aren't + * as many remaining rows as the `limit`. For instance, there are fewer than + * 300 possible values for the dimension `country`, so when reporting on only + * `country`, you can't get more than 300 rows, even if you set `limit` to a + * higher value. + * + * To learn more about this pagination parameter, see + * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). + * @param {string} request.timeZone + * This request's time zone if specified. If unspecified, the property's time + * zone is used. The request's time zone is used to interpret the start & end + * dates of the report. + * + * Formatted as strings from the IANA Time Zone database + * (https://www.iana.org/time-zones); for example "America/New_York" or + * "Asia/Tokyo". + * @param {number[]} request.orderBys + * Specifies how rows are ordered in the response. + * @param {boolean} request.returnEntityQuota + * Toggles whether to return the current state of this Analytics Property's + * quota. Quota is returned in [AccessQuota](#AccessQuota). For account-level + * requests, this field must be false. + * @param {boolean} [request.includeAllUsers] + * Optional. Determines whether to include users who have never made an API + * call in the response. If true, all users with access to the specified + * property or account are included in the response, regardless of whether + * they have made an API call or not. If false, only the users who have made + * an API call will be included. + * @param {boolean} [request.expandGroups] + * Optional. Decides whether to return the users within user groups. This + * field works only when include_all_users is set to true. If true, it will + * return all users with access to the specified property or account. + * If false, only the users with direct access 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 {@link protos.google.analytics.admin.v1beta.RunAccessReportResponse|RunAccessReportResponse}. + * 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/v1beta/analytics_admin_service.run_access_report.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_RunAccessReport_async + */ runAccessReport( - request?: protos.google.analytics.admin.v1beta.IRunAccessReportRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IRunAccessReportResponse, - protos.google.analytics.admin.v1beta.IRunAccessReportRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.admin.v1beta.IRunAccessReportRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IRunAccessReportResponse, + protos.google.analytics.admin.v1beta.IRunAccessReportRequest | undefined, + {} | undefined, + ] + >; runAccessReport( - request: protos.google.analytics.admin.v1beta.IRunAccessReportRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.admin.v1beta.IRunAccessReportResponse, - protos.google.analytics.admin.v1beta.IRunAccessReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IRunAccessReportRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.admin.v1beta.IRunAccessReportResponse, + | protos.google.analytics.admin.v1beta.IRunAccessReportRequest + | null + | undefined, + {} | null | undefined + >, + ): void; runAccessReport( - request: protos.google.analytics.admin.v1beta.IRunAccessReportRequest, - callback: Callback< - protos.google.analytics.admin.v1beta.IRunAccessReportResponse, - protos.google.analytics.admin.v1beta.IRunAccessReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.admin.v1beta.IRunAccessReportRequest, + callback: Callback< + protos.google.analytics.admin.v1beta.IRunAccessReportResponse, + | protos.google.analytics.admin.v1beta.IRunAccessReportRequest + | null + | undefined, + {} | null | undefined + >, + ): void; runAccessReport( - request?: protos.google.analytics.admin.v1beta.IRunAccessReportRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.admin.v1beta.IRunAccessReportResponse, - protos.google.analytics.admin.v1beta.IRunAccessReportRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.admin.v1beta.IRunAccessReportRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.admin.v1beta.IRunAccessReportResponse, - protos.google.analytics.admin.v1beta.IRunAccessReportRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.admin.v1beta.IRunAccessReportResponse, - protos.google.analytics.admin.v1beta.IRunAccessReportRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.admin.v1beta.IRunAccessReportRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.admin.v1beta.IRunAccessReportResponse, + | protos.google.analytics.admin.v1beta.IRunAccessReportRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IRunAccessReportResponse, + protos.google.analytics.admin.v1beta.IRunAccessReportRequest | 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({ - 'entity': request.entity ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + entity: request.entity ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('runAccessReport request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.admin.v1beta.IRunAccessReportResponse, - protos.google.analytics.admin.v1beta.IRunAccessReportRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.admin.v1beta.IRunAccessReportResponse, + | protos.google.analytics.admin.v1beta.IRunAccessReportRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('runAccessReport response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.runAccessReport(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.admin.v1beta.IRunAccessReportResponse, - protos.google.analytics.admin.v1beta.IRunAccessReportRequest|undefined, - {}|undefined - ]) => { - this._log.info('runAccessReport response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .runAccessReport(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.admin.v1beta.IRunAccessReportResponse, + ( + | protos.google.analytics.admin.v1beta.IRunAccessReportRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('runAccessReport response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Returns all accounts accessible by the caller. - * - * Note that these accounts might not currently have GA properties. - * Soft-deleted (ie: "trashed") accounts are excluded by default. - * Returns an empty list if no relevant accounts are found. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} request.pageToken - * A page token, received from a previous `ListAccounts` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListAccounts` must - * match the call that provided the page token. - * @param {boolean} request.showDeleted - * Whether to include soft-deleted (ie: "trashed") Accounts in the - * results. Accounts can be inspected to determine whether they are deleted or - * not. - * @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.analytics.admin.v1beta.Account|Account}. - * 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 `listAccountsAsync()` - * 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. - */ + /** + * Returns all accounts accessible by the caller. + * + * Note that these accounts might not currently have GA properties. + * Soft-deleted (ie: "trashed") accounts are excluded by default. + * Returns an empty list if no relevant accounts are found. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} request.pageToken + * A page token, received from a previous `ListAccounts` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListAccounts` must + * match the call that provided the page token. + * @param {boolean} request.showDeleted + * Whether to include soft-deleted (ie: "trashed") Accounts in the + * results. Accounts can be inspected to determine whether they are deleted or + * not. + * @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.analytics.admin.v1beta.Account|Account}. + * 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 `listAccountsAsync()` + * 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. + */ listAccounts( - request?: protos.google.analytics.admin.v1beta.IListAccountsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IAccount[], - protos.google.analytics.admin.v1beta.IListAccountsRequest|null, - protos.google.analytics.admin.v1beta.IListAccountsResponse - ]>; + request?: protos.google.analytics.admin.v1beta.IListAccountsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IAccount[], + protos.google.analytics.admin.v1beta.IListAccountsRequest | null, + protos.google.analytics.admin.v1beta.IListAccountsResponse, + ] + >; listAccounts( - request: protos.google.analytics.admin.v1beta.IListAccountsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListAccountsRequest, - protos.google.analytics.admin.v1beta.IListAccountsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IAccount>): void; + request: protos.google.analytics.admin.v1beta.IListAccountsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.IListAccountsRequest, + | protos.google.analytics.admin.v1beta.IListAccountsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IAccount + >, + ): void; listAccounts( - request: protos.google.analytics.admin.v1beta.IListAccountsRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListAccountsRequest, - protos.google.analytics.admin.v1beta.IListAccountsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IAccount>): void; + request: protos.google.analytics.admin.v1beta.IListAccountsRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.IListAccountsRequest, + | protos.google.analytics.admin.v1beta.IListAccountsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IAccount + >, + ): void; listAccounts( - request?: protos.google.analytics.admin.v1beta.IListAccountsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.admin.v1beta.IListAccountsRequest, - protos.google.analytics.admin.v1beta.IListAccountsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IAccount>, - callback?: PaginationCallback< + request?: protos.google.analytics.admin.v1beta.IListAccountsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1beta.IListAccountsRequest, - protos.google.analytics.admin.v1beta.IListAccountsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IAccount>): - Promise<[ - protos.google.analytics.admin.v1beta.IAccount[], - protos.google.analytics.admin.v1beta.IListAccountsRequest|null, - protos.google.analytics.admin.v1beta.IListAccountsResponse - ]>|void { + | protos.google.analytics.admin.v1beta.IListAccountsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IAccount + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1beta.IListAccountsRequest, + | protos.google.analytics.admin.v1beta.IListAccountsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IAccount + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IAccount[], + protos.google.analytics.admin.v1beta.IListAccountsRequest | null, + protos.google.analytics.admin.v1beta.IListAccountsResponse, + ] + > | 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 || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListAccountsRequest, - protos.google.analytics.admin.v1beta.IListAccountsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IAccount>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1beta.IListAccountsRequest, + | protos.google.analytics.admin.v1beta.IListAccountsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IAccount + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listAccounts values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -4683,194 +6831,226 @@ export class AnalyticsAdminServiceClient { this._log.info('listAccounts request %j', request); return this.innerApiCalls .listAccounts(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1beta.IAccount[], - protos.google.analytics.admin.v1beta.IListAccountsRequest|null, - protos.google.analytics.admin.v1beta.IListAccountsResponse - ]) => { - this._log.info('listAccounts values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1beta.IAccount[], + protos.google.analytics.admin.v1beta.IListAccountsRequest | null, + protos.google.analytics.admin.v1beta.IListAccountsResponse, + ]) => { + this._log.info('listAccounts values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listAccounts`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} request.pageToken - * A page token, received from a previous `ListAccounts` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListAccounts` must - * match the call that provided the page token. - * @param {boolean} request.showDeleted - * Whether to include soft-deleted (ie: "trashed") Accounts in the - * results. Accounts can be inspected to determine whether they are deleted or - * not. - * @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.analytics.admin.v1beta.Account|Account} 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 `listAccountsAsync()` - * 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 `listAccounts`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} request.pageToken + * A page token, received from a previous `ListAccounts` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListAccounts` must + * match the call that provided the page token. + * @param {boolean} request.showDeleted + * Whether to include soft-deleted (ie: "trashed") Accounts in the + * results. Accounts can be inspected to determine whether they are deleted or + * not. + * @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.analytics.admin.v1beta.Account|Account} 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 `listAccountsAsync()` + * 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. + */ listAccountsStream( - request?: protos.google.analytics.admin.v1beta.IListAccountsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1beta.IListAccountsRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listAccounts']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listAccounts stream %j', request); return this.descriptors.page.listAccounts.createStream( this.innerApiCalls.listAccounts as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listAccounts`, 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 {number} request.pageSize - * The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} request.pageToken - * A page token, received from a previous `ListAccounts` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListAccounts` must - * match the call that provided the page token. - * @param {boolean} request.showDeleted - * Whether to include soft-deleted (ie: "trashed") Accounts in the - * results. Accounts can be inspected to determine whether they are deleted or - * not. - * @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.analytics.admin.v1beta.Account|Account}. 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 include:samples/generated/v1beta/analytics_admin_service.list_accounts.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ListAccounts_async - */ + /** + * Equivalent to `listAccounts`, 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 {number} request.pageSize + * The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} request.pageToken + * A page token, received from a previous `ListAccounts` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListAccounts` must + * match the call that provided the page token. + * @param {boolean} request.showDeleted + * Whether to include soft-deleted (ie: "trashed") Accounts in the + * results. Accounts can be inspected to determine whether they are deleted or + * not. + * @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.analytics.admin.v1beta.Account|Account}. 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 include:samples/generated/v1beta/analytics_admin_service.list_accounts.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ListAccounts_async + */ listAccountsAsync( - request?: protos.google.analytics.admin.v1beta.IListAccountsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1beta.IListAccountsRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listAccounts']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listAccounts iterate %j', request); return this.descriptors.page.listAccounts.asyncIterate( this.innerApiCalls['listAccounts'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Returns summaries of all accounts accessible by the caller. - * - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of AccountSummary resources to return. The service may - * return fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} request.pageToken - * A page token, received from a previous `ListAccountSummaries` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListAccountSummaries` - * must match the call that provided the page token. - * @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.analytics.admin.v1beta.AccountSummary|AccountSummary}. - * 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 `listAccountSummariesAsync()` - * 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. - */ + /** + * Returns summaries of all accounts accessible by the caller. + * + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of AccountSummary resources to return. The service may + * return fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} request.pageToken + * A page token, received from a previous `ListAccountSummaries` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListAccountSummaries` + * must match the call that provided the page token. + * @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.analytics.admin.v1beta.AccountSummary|AccountSummary}. + * 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 `listAccountSummariesAsync()` + * 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. + */ listAccountSummaries( - request?: protos.google.analytics.admin.v1beta.IListAccountSummariesRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IAccountSummary[], - protos.google.analytics.admin.v1beta.IListAccountSummariesRequest|null, - protos.google.analytics.admin.v1beta.IListAccountSummariesResponse - ]>; + request?: protos.google.analytics.admin.v1beta.IListAccountSummariesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IAccountSummary[], + protos.google.analytics.admin.v1beta.IListAccountSummariesRequest | null, + protos.google.analytics.admin.v1beta.IListAccountSummariesResponse, + ] + >; listAccountSummaries( - request: protos.google.analytics.admin.v1beta.IListAccountSummariesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListAccountSummariesRequest, - protos.google.analytics.admin.v1beta.IListAccountSummariesResponse|null|undefined, - protos.google.analytics.admin.v1beta.IAccountSummary>): void; + request: protos.google.analytics.admin.v1beta.IListAccountSummariesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.IListAccountSummariesRequest, + | protos.google.analytics.admin.v1beta.IListAccountSummariesResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IAccountSummary + >, + ): void; listAccountSummaries( - request: protos.google.analytics.admin.v1beta.IListAccountSummariesRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListAccountSummariesRequest, - protos.google.analytics.admin.v1beta.IListAccountSummariesResponse|null|undefined, - protos.google.analytics.admin.v1beta.IAccountSummary>): void; + request: protos.google.analytics.admin.v1beta.IListAccountSummariesRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.IListAccountSummariesRequest, + | protos.google.analytics.admin.v1beta.IListAccountSummariesResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IAccountSummary + >, + ): void; listAccountSummaries( - request?: protos.google.analytics.admin.v1beta.IListAccountSummariesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.analytics.admin.v1beta.IListAccountSummariesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1beta.IListAccountSummariesRequest, - protos.google.analytics.admin.v1beta.IListAccountSummariesResponse|null|undefined, - protos.google.analytics.admin.v1beta.IAccountSummary>, - callback?: PaginationCallback< - protos.google.analytics.admin.v1beta.IListAccountSummariesRequest, - protos.google.analytics.admin.v1beta.IListAccountSummariesResponse|null|undefined, - protos.google.analytics.admin.v1beta.IAccountSummary>): - Promise<[ - protos.google.analytics.admin.v1beta.IAccountSummary[], - protos.google.analytics.admin.v1beta.IListAccountSummariesRequest|null, - protos.google.analytics.admin.v1beta.IListAccountSummariesResponse - ]>|void { + | protos.google.analytics.admin.v1beta.IListAccountSummariesResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IAccountSummary + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1beta.IListAccountSummariesRequest, + | protos.google.analytics.admin.v1beta.IListAccountSummariesResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IAccountSummary + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IAccountSummary[], + protos.google.analytics.admin.v1beta.IListAccountSummariesRequest | null, + protos.google.analytics.admin.v1beta.IListAccountSummariesResponse, + ] + > | 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 || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListAccountSummariesRequest, - protos.google.analytics.admin.v1beta.IListAccountSummariesResponse|null|undefined, - protos.google.analytics.admin.v1beta.IAccountSummary>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1beta.IListAccountSummariesRequest, + | protos.google.analytics.admin.v1beta.IListAccountSummariesResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IAccountSummary + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listAccountSummaries values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -4879,211 +7059,243 @@ export class AnalyticsAdminServiceClient { this._log.info('listAccountSummaries request %j', request); return this.innerApiCalls .listAccountSummaries(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1beta.IAccountSummary[], - protos.google.analytics.admin.v1beta.IListAccountSummariesRequest|null, - protos.google.analytics.admin.v1beta.IListAccountSummariesResponse - ]) => { - this._log.info('listAccountSummaries values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1beta.IAccountSummary[], + protos.google.analytics.admin.v1beta.IListAccountSummariesRequest | null, + protos.google.analytics.admin.v1beta.IListAccountSummariesResponse, + ]) => { + this._log.info('listAccountSummaries values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listAccountSummaries`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {number} request.pageSize - * The maximum number of AccountSummary resources to return. The service may - * return fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} request.pageToken - * A page token, received from a previous `ListAccountSummaries` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListAccountSummaries` - * must match the call that provided the page token. - * @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.analytics.admin.v1beta.AccountSummary|AccountSummary} 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 `listAccountSummariesAsync()` - * 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 `listAccountSummaries`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {number} request.pageSize + * The maximum number of AccountSummary resources to return. The service may + * return fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} request.pageToken + * A page token, received from a previous `ListAccountSummaries` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListAccountSummaries` + * must match the call that provided the page token. + * @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.analytics.admin.v1beta.AccountSummary|AccountSummary} 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 `listAccountSummariesAsync()` + * 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. + */ listAccountSummariesStream( - request?: protos.google.analytics.admin.v1beta.IListAccountSummariesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1beta.IListAccountSummariesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listAccountSummaries']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listAccountSummaries stream %j', request); return this.descriptors.page.listAccountSummaries.createStream( this.innerApiCalls.listAccountSummaries as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listAccountSummaries`, 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 {number} request.pageSize - * The maximum number of AccountSummary resources to return. The service may - * return fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} request.pageToken - * A page token, received from a previous `ListAccountSummaries` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListAccountSummaries` - * must match the call that provided the 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 protos.google.analytics.admin.v1beta.AccountSummary|AccountSummary}. 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 include:samples/generated/v1beta/analytics_admin_service.list_account_summaries.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ListAccountSummaries_async - */ + /** + * Equivalent to `listAccountSummaries`, 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 {number} request.pageSize + * The maximum number of AccountSummary resources to return. The service may + * return fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} request.pageToken + * A page token, received from a previous `ListAccountSummaries` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListAccountSummaries` + * must match the call that provided the 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 protos.google.analytics.admin.v1beta.AccountSummary|AccountSummary}. 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 include:samples/generated/v1beta/analytics_admin_service.list_account_summaries.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ListAccountSummaries_async + */ listAccountSummariesAsync( - request?: protos.google.analytics.admin.v1beta.IListAccountSummariesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1beta.IListAccountSummariesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listAccountSummaries']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listAccountSummaries iterate %j', request); return this.descriptors.page.listAccountSummaries.asyncIterate( this.innerApiCalls['listAccountSummaries'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Returns child Properties under the specified parent Account. - * - * Properties will be excluded if the caller does not have access. - * Soft-deleted (ie: "trashed") properties are excluded by default. - * Returns an empty list if no relevant properties are found. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.filter - * Required. An expression for filtering the results of the request. - * Fields eligible for filtering are: - * `parent:`(The resource name of the parent account/property) or - * `ancestor:`(The resource name of the parent account) or - * `firebase_project:`(The id or number of the linked firebase project). - * Some examples of filters: - * - * ``` - * | Filter | Description | - * |-----------------------------|-------------------------------------------| - * | parent:accounts/123 | The account with account id: 123. | - * | parent:properties/123 | The property with property id: 123. | - * | ancestor:accounts/123 | The account with account id: 123. | - * | firebase_project:project-id | The firebase project with id: project-id. | - * | firebase_project:123 | The firebase project with number: 123. | - * ``` - * @param {number} request.pageSize - * The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} request.pageToken - * A page token, received from a previous `ListProperties` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListProperties` must - * match the call that provided the page token. - * @param {boolean} request.showDeleted - * Whether to include soft-deleted (ie: "trashed") Properties in the - * results. Properties can be inspected to determine whether they are deleted - * or not. - * @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.analytics.admin.v1beta.Property|Property}. - * 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 `listPropertiesAsync()` - * 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. - */ + /** + * Returns child Properties under the specified parent Account. + * + * Properties will be excluded if the caller does not have access. + * Soft-deleted (ie: "trashed") properties are excluded by default. + * Returns an empty list if no relevant properties are found. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * Required. An expression for filtering the results of the request. + * Fields eligible for filtering are: + * `parent:`(The resource name of the parent account/property) or + * `ancestor:`(The resource name of the parent account) or + * `firebase_project:`(The id or number of the linked firebase project). + * Some examples of filters: + * + * ``` + * | Filter | Description | + * |-----------------------------|-------------------------------------------| + * | parent:accounts/123 | The account with account id: 123. | + * | parent:properties/123 | The property with property id: 123. | + * | ancestor:accounts/123 | The account with account id: 123. | + * | firebase_project:project-id | The firebase project with id: project-id. | + * | firebase_project:123 | The firebase project with number: 123. | + * ``` + * @param {number} request.pageSize + * The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} request.pageToken + * A page token, received from a previous `ListProperties` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListProperties` must + * match the call that provided the page token. + * @param {boolean} request.showDeleted + * Whether to include soft-deleted (ie: "trashed") Properties in the + * results. Properties can be inspected to determine whether they are deleted + * or not. + * @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.analytics.admin.v1beta.Property|Property}. + * 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 `listPropertiesAsync()` + * 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. + */ listProperties( - request?: protos.google.analytics.admin.v1beta.IListPropertiesRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IProperty[], - protos.google.analytics.admin.v1beta.IListPropertiesRequest|null, - protos.google.analytics.admin.v1beta.IListPropertiesResponse - ]>; + request?: protos.google.analytics.admin.v1beta.IListPropertiesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IProperty[], + protos.google.analytics.admin.v1beta.IListPropertiesRequest | null, + protos.google.analytics.admin.v1beta.IListPropertiesResponse, + ] + >; listProperties( - request: protos.google.analytics.admin.v1beta.IListPropertiesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListPropertiesRequest, - protos.google.analytics.admin.v1beta.IListPropertiesResponse|null|undefined, - protos.google.analytics.admin.v1beta.IProperty>): void; + request: protos.google.analytics.admin.v1beta.IListPropertiesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.IListPropertiesRequest, + | protos.google.analytics.admin.v1beta.IListPropertiesResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IProperty + >, + ): void; listProperties( - request: protos.google.analytics.admin.v1beta.IListPropertiesRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListPropertiesRequest, - protos.google.analytics.admin.v1beta.IListPropertiesResponse|null|undefined, - protos.google.analytics.admin.v1beta.IProperty>): void; + request: protos.google.analytics.admin.v1beta.IListPropertiesRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.IListPropertiesRequest, + | protos.google.analytics.admin.v1beta.IListPropertiesResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IProperty + >, + ): void; listProperties( - request?: protos.google.analytics.admin.v1beta.IListPropertiesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.admin.v1beta.IListPropertiesRequest, - protos.google.analytics.admin.v1beta.IListPropertiesResponse|null|undefined, - protos.google.analytics.admin.v1beta.IProperty>, - callback?: PaginationCallback< + request?: protos.google.analytics.admin.v1beta.IListPropertiesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1beta.IListPropertiesRequest, - protos.google.analytics.admin.v1beta.IListPropertiesResponse|null|undefined, - protos.google.analytics.admin.v1beta.IProperty>): - Promise<[ - protos.google.analytics.admin.v1beta.IProperty[], - protos.google.analytics.admin.v1beta.IListPropertiesRequest|null, - protos.google.analytics.admin.v1beta.IListPropertiesResponse - ]>|void { + | protos.google.analytics.admin.v1beta.IListPropertiesResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IProperty + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1beta.IListPropertiesRequest, + | protos.google.analytics.admin.v1beta.IListPropertiesResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IProperty + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IProperty[], + protos.google.analytics.admin.v1beta.IListPropertiesRequest | null, + protos.google.analytics.admin.v1beta.IListPropertiesResponse, + ] + > | 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 || {}; - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListPropertiesRequest, - protos.google.analytics.admin.v1beta.IListPropertiesResponse|null|undefined, - protos.google.analytics.admin.v1beta.IProperty>|undefined = callback + this.initialize().catch((err) => { + throw err; + }); + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1beta.IListPropertiesRequest, + | protos.google.analytics.admin.v1beta.IListPropertiesResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IProperty + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listProperties values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -5092,238 +7304,269 @@ export class AnalyticsAdminServiceClient { this._log.info('listProperties request %j', request); return this.innerApiCalls .listProperties(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1beta.IProperty[], - protos.google.analytics.admin.v1beta.IListPropertiesRequest|null, - protos.google.analytics.admin.v1beta.IListPropertiesResponse - ]) => { - this._log.info('listProperties values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1beta.IProperty[], + protos.google.analytics.admin.v1beta.IListPropertiesRequest | null, + protos.google.analytics.admin.v1beta.IListPropertiesResponse, + ]) => { + this._log.info('listProperties values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listProperties`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.filter - * Required. An expression for filtering the results of the request. - * Fields eligible for filtering are: - * `parent:`(The resource name of the parent account/property) or - * `ancestor:`(The resource name of the parent account) or - * `firebase_project:`(The id or number of the linked firebase project). - * Some examples of filters: - * - * ``` - * | Filter | Description | - * |-----------------------------|-------------------------------------------| - * | parent:accounts/123 | The account with account id: 123. | - * | parent:properties/123 | The property with property id: 123. | - * | ancestor:accounts/123 | The account with account id: 123. | - * | firebase_project:project-id | The firebase project with id: project-id. | - * | firebase_project:123 | The firebase project with number: 123. | - * ``` - * @param {number} request.pageSize - * The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} request.pageToken - * A page token, received from a previous `ListProperties` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListProperties` must - * match the call that provided the page token. - * @param {boolean} request.showDeleted - * Whether to include soft-deleted (ie: "trashed") Properties in the - * results. Properties can be inspected to determine whether they are deleted - * or not. - * @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.analytics.admin.v1beta.Property|Property} 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 `listPropertiesAsync()` - * 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 `listProperties`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.filter + * Required. An expression for filtering the results of the request. + * Fields eligible for filtering are: + * `parent:`(The resource name of the parent account/property) or + * `ancestor:`(The resource name of the parent account) or + * `firebase_project:`(The id or number of the linked firebase project). + * Some examples of filters: + * + * ``` + * | Filter | Description | + * |-----------------------------|-------------------------------------------| + * | parent:accounts/123 | The account with account id: 123. | + * | parent:properties/123 | The property with property id: 123. | + * | ancestor:accounts/123 | The account with account id: 123. | + * | firebase_project:project-id | The firebase project with id: project-id. | + * | firebase_project:123 | The firebase project with number: 123. | + * ``` + * @param {number} request.pageSize + * The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} request.pageToken + * A page token, received from a previous `ListProperties` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListProperties` must + * match the call that provided the page token. + * @param {boolean} request.showDeleted + * Whether to include soft-deleted (ie: "trashed") Properties in the + * results. Properties can be inspected to determine whether they are deleted + * or not. + * @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.analytics.admin.v1beta.Property|Property} 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 `listPropertiesAsync()` + * 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. + */ listPropertiesStream( - request?: protos.google.analytics.admin.v1beta.IListPropertiesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1beta.IListPropertiesRequest, + options?: CallOptions, + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listProperties']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listProperties stream %j', request); return this.descriptors.page.listProperties.createStream( this.innerApiCalls.listProperties as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listProperties`, 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.filter - * Required. An expression for filtering the results of the request. - * Fields eligible for filtering are: - * `parent:`(The resource name of the parent account/property) or - * `ancestor:`(The resource name of the parent account) or - * `firebase_project:`(The id or number of the linked firebase project). - * Some examples of filters: - * - * ``` - * | Filter | Description | - * |-----------------------------|-------------------------------------------| - * | parent:accounts/123 | The account with account id: 123. | - * | parent:properties/123 | The property with property id: 123. | - * | ancestor:accounts/123 | The account with account id: 123. | - * | firebase_project:project-id | The firebase project with id: project-id. | - * | firebase_project:123 | The firebase project with number: 123. | - * ``` - * @param {number} request.pageSize - * The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} request.pageToken - * A page token, received from a previous `ListProperties` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListProperties` must - * match the call that provided the page token. - * @param {boolean} request.showDeleted - * Whether to include soft-deleted (ie: "trashed") Properties in the - * results. Properties can be inspected to determine whether they are deleted - * or not. - * @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.analytics.admin.v1beta.Property|Property}. 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 include:samples/generated/v1beta/analytics_admin_service.list_properties.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ListProperties_async - */ + /** + * Equivalent to `listProperties`, 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.filter + * Required. An expression for filtering the results of the request. + * Fields eligible for filtering are: + * `parent:`(The resource name of the parent account/property) or + * `ancestor:`(The resource name of the parent account) or + * `firebase_project:`(The id or number of the linked firebase project). + * Some examples of filters: + * + * ``` + * | Filter | Description | + * |-----------------------------|-------------------------------------------| + * | parent:accounts/123 | The account with account id: 123. | + * | parent:properties/123 | The property with property id: 123. | + * | ancestor:accounts/123 | The account with account id: 123. | + * | firebase_project:project-id | The firebase project with id: project-id. | + * | firebase_project:123 | The firebase project with number: 123. | + * ``` + * @param {number} request.pageSize + * The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} request.pageToken + * A page token, received from a previous `ListProperties` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListProperties` must + * match the call that provided the page token. + * @param {boolean} request.showDeleted + * Whether to include soft-deleted (ie: "trashed") Properties in the + * results. Properties can be inspected to determine whether they are deleted + * or not. + * @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.analytics.admin.v1beta.Property|Property}. 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 include:samples/generated/v1beta/analytics_admin_service.list_properties.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ListProperties_async + */ listPropertiesAsync( - request?: protos.google.analytics.admin.v1beta.IListPropertiesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1beta.IListPropertiesRequest, + options?: CallOptions, + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; const defaultCallSettings = this._defaults['listProperties']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listProperties iterate %j', request); return this.descriptors.page.listProperties.asyncIterate( this.innerApiCalls['listProperties'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists FirebaseLinks on a property. - * Properties can have at most one FirebaseLink. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Format: properties/{property_id} - * - * Example: `properties/1234` - * @param {number} request.pageSize - * The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} request.pageToken - * A page token, received from a previous `ListFirebaseLinks` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListFirebaseLinks` must - * match the call that provided the page token. - * @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.analytics.admin.v1beta.FirebaseLink|FirebaseLink}. - * 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 `listFirebaseLinksAsync()` - * 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 FirebaseLinks on a property. + * Properties can have at most one FirebaseLink. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Format: properties/{property_id} + * + * Example: `properties/1234` + * @param {number} request.pageSize + * The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} request.pageToken + * A page token, received from a previous `ListFirebaseLinks` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListFirebaseLinks` must + * match the call that provided the page token. + * @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.analytics.admin.v1beta.FirebaseLink|FirebaseLink}. + * 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 `listFirebaseLinksAsync()` + * 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. + */ listFirebaseLinks( - request?: protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IFirebaseLink[], - protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest|null, - protos.google.analytics.admin.v1beta.IListFirebaseLinksResponse - ]>; + request?: protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IFirebaseLink[], + protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest | null, + protos.google.analytics.admin.v1beta.IListFirebaseLinksResponse, + ] + >; listFirebaseLinks( - request: protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest, - protos.google.analytics.admin.v1beta.IListFirebaseLinksResponse|null|undefined, - protos.google.analytics.admin.v1beta.IFirebaseLink>): void; + request: protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest, + | protos.google.analytics.admin.v1beta.IListFirebaseLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IFirebaseLink + >, + ): void; listFirebaseLinks( - request: protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest, - protos.google.analytics.admin.v1beta.IListFirebaseLinksResponse|null|undefined, - protos.google.analytics.admin.v1beta.IFirebaseLink>): void; + request: protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest, + | protos.google.analytics.admin.v1beta.IListFirebaseLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IFirebaseLink + >, + ): void; listFirebaseLinks( - request?: protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest, - protos.google.analytics.admin.v1beta.IListFirebaseLinksResponse|null|undefined, - protos.google.analytics.admin.v1beta.IFirebaseLink>, - callback?: PaginationCallback< + request?: protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest, - protos.google.analytics.admin.v1beta.IListFirebaseLinksResponse|null|undefined, - protos.google.analytics.admin.v1beta.IFirebaseLink>): - Promise<[ - protos.google.analytics.admin.v1beta.IFirebaseLink[], - protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest|null, - protos.google.analytics.admin.v1beta.IListFirebaseLinksResponse - ]>|void { + | protos.google.analytics.admin.v1beta.IListFirebaseLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IFirebaseLink + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest, + | protos.google.analytics.admin.v1beta.IListFirebaseLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IFirebaseLink + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IFirebaseLink[], + protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest | null, + protos.google.analytics.admin.v1beta.IListFirebaseLinksResponse, + ] + > | 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.analytics.admin.v1beta.IListFirebaseLinksRequest, - protos.google.analytics.admin.v1beta.IListFirebaseLinksResponse|null|undefined, - protos.google.analytics.admin.v1beta.IFirebaseLink>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest, + | protos.google.analytics.admin.v1beta.IListFirebaseLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IFirebaseLink + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listFirebaseLinks values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -5332,211 +7575,240 @@ export class AnalyticsAdminServiceClient { this._log.info('listFirebaseLinks request %j', request); return this.innerApiCalls .listFirebaseLinks(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1beta.IFirebaseLink[], - protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest|null, - protos.google.analytics.admin.v1beta.IListFirebaseLinksResponse - ]) => { - this._log.info('listFirebaseLinks values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1beta.IFirebaseLink[], + protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest | null, + protos.google.analytics.admin.v1beta.IListFirebaseLinksResponse, + ]) => { + this._log.info('listFirebaseLinks values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listFirebaseLinks`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Format: properties/{property_id} - * - * Example: `properties/1234` - * @param {number} request.pageSize - * The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} request.pageToken - * A page token, received from a previous `ListFirebaseLinks` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListFirebaseLinks` must - * match the call that provided the page token. - * @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.analytics.admin.v1beta.FirebaseLink|FirebaseLink} 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 `listFirebaseLinksAsync()` - * 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 `listFirebaseLinks`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Format: properties/{property_id} + * + * Example: `properties/1234` + * @param {number} request.pageSize + * The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} request.pageToken + * A page token, received from a previous `ListFirebaseLinks` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListFirebaseLinks` must + * match the call that provided the page token. + * @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.analytics.admin.v1beta.FirebaseLink|FirebaseLink} 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 `listFirebaseLinksAsync()` + * 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. + */ listFirebaseLinksStream( - request?: protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest, + 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['listFirebaseLinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listFirebaseLinks stream %j', request); return this.descriptors.page.listFirebaseLinks.createStream( this.innerApiCalls.listFirebaseLinks as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listFirebaseLinks`, 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. Format: properties/{property_id} - * - * Example: `properties/1234` - * @param {number} request.pageSize - * The maximum number of resources to return. The service may return - * fewer than this value, even if there are additional pages. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} request.pageToken - * A page token, received from a previous `ListFirebaseLinks` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListFirebaseLinks` must - * match the call that provided the 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 protos.google.analytics.admin.v1beta.FirebaseLink|FirebaseLink}. 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 include:samples/generated/v1beta/analytics_admin_service.list_firebase_links.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ListFirebaseLinks_async - */ + /** + * Equivalent to `listFirebaseLinks`, 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. Format: properties/{property_id} + * + * Example: `properties/1234` + * @param {number} request.pageSize + * The maximum number of resources to return. The service may return + * fewer than this value, even if there are additional pages. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} request.pageToken + * A page token, received from a previous `ListFirebaseLinks` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListFirebaseLinks` must + * match the call that provided the 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 protos.google.analytics.admin.v1beta.FirebaseLink|FirebaseLink}. 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 include:samples/generated/v1beta/analytics_admin_service.list_firebase_links.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ListFirebaseLinks_async + */ listFirebaseLinksAsync( - request?: protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1beta.IListFirebaseLinksRequest, + 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['listFirebaseLinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listFirebaseLinks iterate %j', request); return this.descriptors.page.listFirebaseLinks.asyncIterate( this.innerApiCalls['listFirebaseLinks'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists GoogleAdsLinks on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListGoogleAdsLinks` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListGoogleAdsLinks` must - * match the call that provided the page token. - * @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.analytics.admin.v1beta.GoogleAdsLink|GoogleAdsLink}. - * 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 `listGoogleAdsLinksAsync()` - * 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 GoogleAdsLinks on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListGoogleAdsLinks` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListGoogleAdsLinks` must + * match the call that provided the page token. + * @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.analytics.admin.v1beta.GoogleAdsLink|GoogleAdsLink}. + * 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 `listGoogleAdsLinksAsync()` + * 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. + */ listGoogleAdsLinks( - request?: protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IGoogleAdsLink[], - protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest|null, - protos.google.analytics.admin.v1beta.IListGoogleAdsLinksResponse - ]>; + request?: protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IGoogleAdsLink[], + protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest | null, + protos.google.analytics.admin.v1beta.IListGoogleAdsLinksResponse, + ] + >; listGoogleAdsLinks( - request: protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest, - protos.google.analytics.admin.v1beta.IListGoogleAdsLinksResponse|null|undefined, - protos.google.analytics.admin.v1beta.IGoogleAdsLink>): void; + request: protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest, + | protos.google.analytics.admin.v1beta.IListGoogleAdsLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IGoogleAdsLink + >, + ): void; listGoogleAdsLinks( - request: protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest, - protos.google.analytics.admin.v1beta.IListGoogleAdsLinksResponse|null|undefined, - protos.google.analytics.admin.v1beta.IGoogleAdsLink>): void; + request: protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest, + | protos.google.analytics.admin.v1beta.IListGoogleAdsLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IGoogleAdsLink + >, + ): void; listGoogleAdsLinks( - request?: protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest, - protos.google.analytics.admin.v1beta.IListGoogleAdsLinksResponse|null|undefined, - protos.google.analytics.admin.v1beta.IGoogleAdsLink>, - callback?: PaginationCallback< + request?: protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest, - protos.google.analytics.admin.v1beta.IListGoogleAdsLinksResponse|null|undefined, - protos.google.analytics.admin.v1beta.IGoogleAdsLink>): - Promise<[ - protos.google.analytics.admin.v1beta.IGoogleAdsLink[], - protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest|null, - protos.google.analytics.admin.v1beta.IListGoogleAdsLinksResponse - ]>|void { + | protos.google.analytics.admin.v1beta.IListGoogleAdsLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IGoogleAdsLink + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest, + | protos.google.analytics.admin.v1beta.IListGoogleAdsLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IGoogleAdsLink + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IGoogleAdsLink[], + protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest | null, + protos.google.analytics.admin.v1beta.IListGoogleAdsLinksResponse, + ] + > | 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.analytics.admin.v1beta.IListGoogleAdsLinksRequest, - protos.google.analytics.admin.v1beta.IListGoogleAdsLinksResponse|null|undefined, - protos.google.analytics.admin.v1beta.IGoogleAdsLink>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest, + | protos.google.analytics.admin.v1beta.IListGoogleAdsLinksResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IGoogleAdsLink + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listGoogleAdsLinks values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -5545,209 +7817,238 @@ export class AnalyticsAdminServiceClient { this._log.info('listGoogleAdsLinks request %j', request); return this.innerApiCalls .listGoogleAdsLinks(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1beta.IGoogleAdsLink[], - protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest|null, - protos.google.analytics.admin.v1beta.IListGoogleAdsLinksResponse - ]) => { - this._log.info('listGoogleAdsLinks values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1beta.IGoogleAdsLink[], + protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest | null, + protos.google.analytics.admin.v1beta.IListGoogleAdsLinksResponse, + ]) => { + this._log.info('listGoogleAdsLinks values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listGoogleAdsLinks`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListGoogleAdsLinks` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListGoogleAdsLinks` must - * match the call that provided the page token. - * @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.analytics.admin.v1beta.GoogleAdsLink|GoogleAdsLink} 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 `listGoogleAdsLinksAsync()` - * 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 `listGoogleAdsLinks`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListGoogleAdsLinks` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListGoogleAdsLinks` must + * match the call that provided the page token. + * @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.analytics.admin.v1beta.GoogleAdsLink|GoogleAdsLink} 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 `listGoogleAdsLinksAsync()` + * 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. + */ listGoogleAdsLinksStream( - request?: protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest, + 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['listGoogleAdsLinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listGoogleAdsLinks stream %j', request); return this.descriptors.page.listGoogleAdsLinks.createStream( this.innerApiCalls.listGoogleAdsLinks as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listGoogleAdsLinks`, 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. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListGoogleAdsLinks` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListGoogleAdsLinks` must - * match the call that provided the 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 protos.google.analytics.admin.v1beta.GoogleAdsLink|GoogleAdsLink}. 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 include:samples/generated/v1beta/analytics_admin_service.list_google_ads_links.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ListGoogleAdsLinks_async - */ + /** + * Equivalent to `listGoogleAdsLinks`, 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. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListGoogleAdsLinks` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListGoogleAdsLinks` must + * match the call that provided the 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 protos.google.analytics.admin.v1beta.GoogleAdsLink|GoogleAdsLink}. 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 include:samples/generated/v1beta/analytics_admin_service.list_google_ads_links.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ListGoogleAdsLinks_async + */ listGoogleAdsLinksAsync( - request?: protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1beta.IListGoogleAdsLinksRequest, + 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['listGoogleAdsLinks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listGoogleAdsLinks iterate %j', request); return this.descriptors.page.listGoogleAdsLinks.asyncIterate( this.innerApiCalls['listGoogleAdsLinks'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Returns child MeasurementProtocolSecrets under the specified parent - * Property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the parent stream. - * Format: - * properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 10 resources will be returned. - * The maximum value is 10. Higher values will be coerced to the maximum. - * @param {string} request.pageToken - * A page token, received from a previous `ListMeasurementProtocolSecrets` - * call. Provide this to retrieve the subsequent page. When paginating, all - * other parameters provided to `ListMeasurementProtocolSecrets` must match - * the call that provided the page token. - * @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.analytics.admin.v1beta.MeasurementProtocolSecret|MeasurementProtocolSecret}. - * 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 `listMeasurementProtocolSecretsAsync()` - * 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. - */ + /** + * Returns child MeasurementProtocolSecrets under the specified parent + * Property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the parent stream. + * Format: + * properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 10 resources will be returned. + * The maximum value is 10. Higher values will be coerced to the maximum. + * @param {string} request.pageToken + * A page token, received from a previous `ListMeasurementProtocolSecrets` + * call. Provide this to retrieve the subsequent page. When paginating, all + * other parameters provided to `ListMeasurementProtocolSecrets` must match + * the call that provided the page token. + * @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.analytics.admin.v1beta.MeasurementProtocolSecret|MeasurementProtocolSecret}. + * 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 `listMeasurementProtocolSecretsAsync()` + * 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. + */ listMeasurementProtocolSecrets( - request?: protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret[], - protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest|null, - protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsResponse - ]>; + request?: protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret[], + protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest | null, + protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsResponse, + ] + >; listMeasurementProtocolSecrets( - request: protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest, - protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret>): void; + request: protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest, + | protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret + >, + ): void; listMeasurementProtocolSecrets( - request: protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest, - protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret>): void; + request: protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest, + | protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret + >, + ): void; listMeasurementProtocolSecrets( - request?: protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest, - protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret>, - callback?: PaginationCallback< - protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest, - protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret>): - Promise<[ - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret[], - protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest|null, - protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsResponse - ]>|void { + | protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest, + | protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret[], + protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest | null, + protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsResponse, + ] + > | 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.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest, - protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest, + | protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listMeasurementProtocolSecrets values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -5756,241 +8057,272 @@ export class AnalyticsAdminServiceClient { this._log.info('listMeasurementProtocolSecrets request %j', request); return this.innerApiCalls .listMeasurementProtocolSecrets(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret[], - protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest|null, - protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsResponse - ]) => { - this._log.info('listMeasurementProtocolSecrets values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret[], + protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest | null, + protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsResponse, + ]) => { + this._log.info('listMeasurementProtocolSecrets values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listMeasurementProtocolSecrets`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the parent stream. - * Format: - * properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 10 resources will be returned. - * The maximum value is 10. Higher values will be coerced to the maximum. - * @param {string} request.pageToken - * A page token, received from a previous `ListMeasurementProtocolSecrets` - * call. Provide this to retrieve the subsequent page. When paginating, all - * other parameters provided to `ListMeasurementProtocolSecrets` must match - * the call that provided the page token. - * @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.analytics.admin.v1beta.MeasurementProtocolSecret|MeasurementProtocolSecret} 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 `listMeasurementProtocolSecretsAsync()` - * 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 `listMeasurementProtocolSecrets`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the parent stream. + * Format: + * properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 10 resources will be returned. + * The maximum value is 10. Higher values will be coerced to the maximum. + * @param {string} request.pageToken + * A page token, received from a previous `ListMeasurementProtocolSecrets` + * call. Provide this to retrieve the subsequent page. When paginating, all + * other parameters provided to `ListMeasurementProtocolSecrets` must match + * the call that provided the page token. + * @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.analytics.admin.v1beta.MeasurementProtocolSecret|MeasurementProtocolSecret} 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 `listMeasurementProtocolSecretsAsync()` + * 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. + */ listMeasurementProtocolSecretsStream( - request?: protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest, + 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 ?? '', - }); - const defaultCallSettings = this._defaults['listMeasurementProtocolSecrets']; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = + this._defaults['listMeasurementProtocolSecrets']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listMeasurementProtocolSecrets stream %j', request); return this.descriptors.page.listMeasurementProtocolSecrets.createStream( this.innerApiCalls.listMeasurementProtocolSecrets as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listMeasurementProtocolSecrets`, 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 resource name of the parent stream. - * Format: - * properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 10 resources will be returned. - * The maximum value is 10. Higher values will be coerced to the maximum. - * @param {string} request.pageToken - * A page token, received from a previous `ListMeasurementProtocolSecrets` - * call. Provide this to retrieve the subsequent page. When paginating, all - * other parameters provided to `ListMeasurementProtocolSecrets` must match - * the call that provided the 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 protos.google.analytics.admin.v1beta.MeasurementProtocolSecret|MeasurementProtocolSecret}. 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 include:samples/generated/v1beta/analytics_admin_service.list_measurement_protocol_secrets.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ListMeasurementProtocolSecrets_async - */ + /** + * Equivalent to `listMeasurementProtocolSecrets`, 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 resource name of the parent stream. + * Format: + * properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 10 resources will be returned. + * The maximum value is 10. Higher values will be coerced to the maximum. + * @param {string} request.pageToken + * A page token, received from a previous `ListMeasurementProtocolSecrets` + * call. Provide this to retrieve the subsequent page. When paginating, all + * other parameters provided to `ListMeasurementProtocolSecrets` must match + * the call that provided the 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 protos.google.analytics.admin.v1beta.MeasurementProtocolSecret|MeasurementProtocolSecret}. 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 include:samples/generated/v1beta/analytics_admin_service.list_measurement_protocol_secrets.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ListMeasurementProtocolSecrets_async + */ listMeasurementProtocolSecretsAsync( - request?: protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1beta.IListMeasurementProtocolSecretsRequest, + 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 ?? '', - }); - const defaultCallSettings = this._defaults['listMeasurementProtocolSecrets']; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + const defaultCallSettings = + this._defaults['listMeasurementProtocolSecrets']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listMeasurementProtocolSecrets iterate %j', request); return this.descriptors.page.listMeasurementProtocolSecrets.asyncIterate( this.innerApiCalls['listMeasurementProtocolSecrets'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Searches through all changes to an account or its children given the - * specified set of filters. - * - * Only returns the subset of changes supported by the API. The UI may return - * additional changes. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.account - * Required. The account resource for which to return change history - * resources. Format: accounts/{account} - * - * Example: `accounts/100` - * @param {string} [request.property] - * Optional. Resource name for a child property. If set, only return changes - * made to this property or its child resources. - * Format: properties/{propertyId} - * - * Example: `properties/100` - * @param {number[]} [request.resourceType] - * Optional. If set, only return changes if they are for a resource that - * matches at least one of these types. - * @param {number[]} [request.action] - * Optional. If set, only return changes that match one or more of these types - * of actions. - * @param {string[]} [request.actorEmail] - * Optional. If set, only return changes if they are made by a user in this - * list. - * @param {google.protobuf.Timestamp} [request.earliestChangeTime] - * Optional. If set, only return changes made after this time (inclusive). - * @param {google.protobuf.Timestamp} [request.latestChangeTime] - * Optional. If set, only return changes made before this time (inclusive). - * @param {number} [request.pageSize] - * Optional. The maximum number of ChangeHistoryEvent items to return. - * If unspecified, at most 50 items will be returned. The maximum value is 200 - * (higher values will be coerced to the maximum). - * - * Note that the service may return a page with fewer items than this value - * specifies (potentially even zero), and that there still may be additional - * pages. If you want a particular number of items, you'll need to continue - * requesting additional pages using `page_token` until you get the needed - * number. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `SearchChangeHistoryEvents` call. Provide this to retrieve the subsequent - * page. When paginating, all other parameters provided to - * `SearchChangeHistoryEvents` must match the call that provided the page - * token. - * @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.analytics.admin.v1beta.ChangeHistoryEvent|ChangeHistoryEvent}. - * 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 `searchChangeHistoryEventsAsync()` - * 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. - */ + /** + * Searches through all changes to an account or its children given the + * specified set of filters. + * + * Only returns the subset of changes supported by the API. The UI may return + * additional changes. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.account + * Required. The account resource for which to return change history + * resources. Format: accounts/{account} + * + * Example: `accounts/100` + * @param {string} [request.property] + * Optional. Resource name for a child property. If set, only return changes + * made to this property or its child resources. + * Format: properties/{propertyId} + * + * Example: `properties/100` + * @param {number[]} [request.resourceType] + * Optional. If set, only return changes if they are for a resource that + * matches at least one of these types. + * @param {number[]} [request.action] + * Optional. If set, only return changes that match one or more of these types + * of actions. + * @param {string[]} [request.actorEmail] + * Optional. If set, only return changes if they are made by a user in this + * list. + * @param {google.protobuf.Timestamp} [request.earliestChangeTime] + * Optional. If set, only return changes made after this time (inclusive). + * @param {google.protobuf.Timestamp} [request.latestChangeTime] + * Optional. If set, only return changes made before this time (inclusive). + * @param {number} [request.pageSize] + * Optional. The maximum number of ChangeHistoryEvent items to return. + * If unspecified, at most 50 items will be returned. The maximum value is 200 + * (higher values will be coerced to the maximum). + * + * Note that the service may return a page with fewer items than this value + * specifies (potentially even zero), and that there still may be additional + * pages. If you want a particular number of items, you'll need to continue + * requesting additional pages using `page_token` until you get the needed + * number. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `SearchChangeHistoryEvents` call. Provide this to retrieve the subsequent + * page. When paginating, all other parameters provided to + * `SearchChangeHistoryEvents` must match the call that provided the page + * token. + * @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.analytics.admin.v1beta.ChangeHistoryEvent|ChangeHistoryEvent}. + * 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 `searchChangeHistoryEventsAsync()` + * 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. + */ searchChangeHistoryEvents( - request?: protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IChangeHistoryEvent[], - protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest|null, - protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsResponse - ]>; + request?: protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IChangeHistoryEvent[], + protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest | null, + protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsResponse, + ] + >; searchChangeHistoryEvents( - request: protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest, - protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IChangeHistoryEvent>): void; + request: protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest, + | protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IChangeHistoryEvent + >, + ): void; searchChangeHistoryEvents( - request: protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest, - protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IChangeHistoryEvent>): void; + request: protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest, + | protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IChangeHistoryEvent + >, + ): void; searchChangeHistoryEvents( - request?: protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest, - protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IChangeHistoryEvent>, - callback?: PaginationCallback< + request?: protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest, - protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IChangeHistoryEvent>): - Promise<[ - protos.google.analytics.admin.v1beta.IChangeHistoryEvent[], - protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest|null, - protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsResponse - ]>|void { + | protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IChangeHistoryEvent + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest, + | protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IChangeHistoryEvent + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IChangeHistoryEvent[], + protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest | null, + protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsResponse, + ] + > | 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({ - 'account': request.account ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + account: request.account ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest, - protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IChangeHistoryEvent>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest, + | protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IChangeHistoryEvent + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('searchChangeHistoryEvents values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -5999,268 +8331,301 @@ export class AnalyticsAdminServiceClient { this._log.info('searchChangeHistoryEvents request %j', request); return this.innerApiCalls .searchChangeHistoryEvents(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1beta.IChangeHistoryEvent[], - protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest|null, - protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsResponse - ]) => { - this._log.info('searchChangeHistoryEvents values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1beta.IChangeHistoryEvent[], + protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest | null, + protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsResponse, + ]) => { + this._log.info('searchChangeHistoryEvents values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `searchChangeHistoryEvents`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.account - * Required. The account resource for which to return change history - * resources. Format: accounts/{account} - * - * Example: `accounts/100` - * @param {string} [request.property] - * Optional. Resource name for a child property. If set, only return changes - * made to this property or its child resources. - * Format: properties/{propertyId} - * - * Example: `properties/100` - * @param {number[]} [request.resourceType] - * Optional. If set, only return changes if they are for a resource that - * matches at least one of these types. - * @param {number[]} [request.action] - * Optional. If set, only return changes that match one or more of these types - * of actions. - * @param {string[]} [request.actorEmail] - * Optional. If set, only return changes if they are made by a user in this - * list. - * @param {google.protobuf.Timestamp} [request.earliestChangeTime] - * Optional. If set, only return changes made after this time (inclusive). - * @param {google.protobuf.Timestamp} [request.latestChangeTime] - * Optional. If set, only return changes made before this time (inclusive). - * @param {number} [request.pageSize] - * Optional. The maximum number of ChangeHistoryEvent items to return. - * If unspecified, at most 50 items will be returned. The maximum value is 200 - * (higher values will be coerced to the maximum). - * - * Note that the service may return a page with fewer items than this value - * specifies (potentially even zero), and that there still may be additional - * pages. If you want a particular number of items, you'll need to continue - * requesting additional pages using `page_token` until you get the needed - * number. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `SearchChangeHistoryEvents` call. Provide this to retrieve the subsequent - * page. When paginating, all other parameters provided to - * `SearchChangeHistoryEvents` must match the call that provided the page - * token. - * @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.analytics.admin.v1beta.ChangeHistoryEvent|ChangeHistoryEvent} 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 `searchChangeHistoryEventsAsync()` - * 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 `searchChangeHistoryEvents`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.account + * Required. The account resource for which to return change history + * resources. Format: accounts/{account} + * + * Example: `accounts/100` + * @param {string} [request.property] + * Optional. Resource name for a child property. If set, only return changes + * made to this property or its child resources. + * Format: properties/{propertyId} + * + * Example: `properties/100` + * @param {number[]} [request.resourceType] + * Optional. If set, only return changes if they are for a resource that + * matches at least one of these types. + * @param {number[]} [request.action] + * Optional. If set, only return changes that match one or more of these types + * of actions. + * @param {string[]} [request.actorEmail] + * Optional. If set, only return changes if they are made by a user in this + * list. + * @param {google.protobuf.Timestamp} [request.earliestChangeTime] + * Optional. If set, only return changes made after this time (inclusive). + * @param {google.protobuf.Timestamp} [request.latestChangeTime] + * Optional. If set, only return changes made before this time (inclusive). + * @param {number} [request.pageSize] + * Optional. The maximum number of ChangeHistoryEvent items to return. + * If unspecified, at most 50 items will be returned. The maximum value is 200 + * (higher values will be coerced to the maximum). + * + * Note that the service may return a page with fewer items than this value + * specifies (potentially even zero), and that there still may be additional + * pages. If you want a particular number of items, you'll need to continue + * requesting additional pages using `page_token` until you get the needed + * number. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `SearchChangeHistoryEvents` call. Provide this to retrieve the subsequent + * page. When paginating, all other parameters provided to + * `SearchChangeHistoryEvents` must match the call that provided the page + * token. + * @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.analytics.admin.v1beta.ChangeHistoryEvent|ChangeHistoryEvent} 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 `searchChangeHistoryEventsAsync()` + * 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. + */ searchChangeHistoryEventsStream( - request?: protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest, + 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({ - 'account': request.account ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + account: request.account ?? '', + }); const defaultCallSettings = this._defaults['searchChangeHistoryEvents']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('searchChangeHistoryEvents stream %j', request); return this.descriptors.page.searchChangeHistoryEvents.createStream( this.innerApiCalls.searchChangeHistoryEvents as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `searchChangeHistoryEvents`, 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.account - * Required. The account resource for which to return change history - * resources. Format: accounts/{account} - * - * Example: `accounts/100` - * @param {string} [request.property] - * Optional. Resource name for a child property. If set, only return changes - * made to this property or its child resources. - * Format: properties/{propertyId} - * - * Example: `properties/100` - * @param {number[]} [request.resourceType] - * Optional. If set, only return changes if they are for a resource that - * matches at least one of these types. - * @param {number[]} [request.action] - * Optional. If set, only return changes that match one or more of these types - * of actions. - * @param {string[]} [request.actorEmail] - * Optional. If set, only return changes if they are made by a user in this - * list. - * @param {google.protobuf.Timestamp} [request.earliestChangeTime] - * Optional. If set, only return changes made after this time (inclusive). - * @param {google.protobuf.Timestamp} [request.latestChangeTime] - * Optional. If set, only return changes made before this time (inclusive). - * @param {number} [request.pageSize] - * Optional. The maximum number of ChangeHistoryEvent items to return. - * If unspecified, at most 50 items will be returned. The maximum value is 200 - * (higher values will be coerced to the maximum). - * - * Note that the service may return a page with fewer items than this value - * specifies (potentially even zero), and that there still may be additional - * pages. If you want a particular number of items, you'll need to continue - * requesting additional pages using `page_token` until you get the needed - * number. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `SearchChangeHistoryEvents` call. Provide this to retrieve the subsequent - * page. When paginating, all other parameters provided to - * `SearchChangeHistoryEvents` must match the call that provided the 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 protos.google.analytics.admin.v1beta.ChangeHistoryEvent|ChangeHistoryEvent}. 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 include:samples/generated/v1beta/analytics_admin_service.search_change_history_events.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_SearchChangeHistoryEvents_async - */ + /** + * Equivalent to `searchChangeHistoryEvents`, 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.account + * Required. The account resource for which to return change history + * resources. Format: accounts/{account} + * + * Example: `accounts/100` + * @param {string} [request.property] + * Optional. Resource name for a child property. If set, only return changes + * made to this property or its child resources. + * Format: properties/{propertyId} + * + * Example: `properties/100` + * @param {number[]} [request.resourceType] + * Optional. If set, only return changes if they are for a resource that + * matches at least one of these types. + * @param {number[]} [request.action] + * Optional. If set, only return changes that match one or more of these types + * of actions. + * @param {string[]} [request.actorEmail] + * Optional. If set, only return changes if they are made by a user in this + * list. + * @param {google.protobuf.Timestamp} [request.earliestChangeTime] + * Optional. If set, only return changes made after this time (inclusive). + * @param {google.protobuf.Timestamp} [request.latestChangeTime] + * Optional. If set, only return changes made before this time (inclusive). + * @param {number} [request.pageSize] + * Optional. The maximum number of ChangeHistoryEvent items to return. + * If unspecified, at most 50 items will be returned. The maximum value is 200 + * (higher values will be coerced to the maximum). + * + * Note that the service may return a page with fewer items than this value + * specifies (potentially even zero), and that there still may be additional + * pages. If you want a particular number of items, you'll need to continue + * requesting additional pages using `page_token` until you get the needed + * number. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `SearchChangeHistoryEvents` call. Provide this to retrieve the subsequent + * page. When paginating, all other parameters provided to + * `SearchChangeHistoryEvents` must match the call that provided the 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 protos.google.analytics.admin.v1beta.ChangeHistoryEvent|ChangeHistoryEvent}. 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 include:samples/generated/v1beta/analytics_admin_service.search_change_history_events.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_SearchChangeHistoryEvents_async + */ searchChangeHistoryEventsAsync( - request?: protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1beta.ISearchChangeHistoryEventsRequest, + 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({ - 'account': request.account ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + account: request.account ?? '', + }); const defaultCallSettings = this._defaults['searchChangeHistoryEvents']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('searchChangeHistoryEvents iterate %j', request); return this.descriptors.page.searchChangeHistoryEvents.asyncIterate( this.innerApiCalls['searchChangeHistoryEvents'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Deprecated: Use `ListKeyEvents` instead. - * Returns a list of conversion events in the specified parent property. - * - * Returns an empty list if no conversion events are found. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the parent property. - * Example: 'properties/123' - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} request.pageToken - * A page token, received from a previous `ListConversionEvents` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListConversionEvents` - * must match the call that provided the page token. - * @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.analytics.admin.v1beta.ConversionEvent|ConversionEvent}. - * 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 `listConversionEventsAsync()` - * 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. - * @deprecated ListConversionEvents is deprecated and may be removed in a future version. - */ + /** + * Deprecated: Use `ListKeyEvents` instead. + * Returns a list of conversion events in the specified parent property. + * + * Returns an empty list if no conversion events are found. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the parent property. + * Example: 'properties/123' + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} request.pageToken + * A page token, received from a previous `ListConversionEvents` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListConversionEvents` + * must match the call that provided the page token. + * @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.analytics.admin.v1beta.ConversionEvent|ConversionEvent}. + * 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 `listConversionEventsAsync()` + * 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. + * @deprecated ListConversionEvents is deprecated and may be removed in a future version. + */ listConversionEvents( - request?: protos.google.analytics.admin.v1beta.IListConversionEventsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IConversionEvent[], - protos.google.analytics.admin.v1beta.IListConversionEventsRequest|null, - protos.google.analytics.admin.v1beta.IListConversionEventsResponse - ]>; + request?: protos.google.analytics.admin.v1beta.IListConversionEventsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IConversionEvent[], + protos.google.analytics.admin.v1beta.IListConversionEventsRequest | null, + protos.google.analytics.admin.v1beta.IListConversionEventsResponse, + ] + >; listConversionEvents( - request: protos.google.analytics.admin.v1beta.IListConversionEventsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListConversionEventsRequest, - protos.google.analytics.admin.v1beta.IListConversionEventsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IConversionEvent>): void; + request: protos.google.analytics.admin.v1beta.IListConversionEventsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.IListConversionEventsRequest, + | protos.google.analytics.admin.v1beta.IListConversionEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IConversionEvent + >, + ): void; listConversionEvents( - request: protos.google.analytics.admin.v1beta.IListConversionEventsRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListConversionEventsRequest, - protos.google.analytics.admin.v1beta.IListConversionEventsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IConversionEvent>): void; + request: protos.google.analytics.admin.v1beta.IListConversionEventsRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.IListConversionEventsRequest, + | protos.google.analytics.admin.v1beta.IListConversionEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IConversionEvent + >, + ): void; listConversionEvents( - request?: protos.google.analytics.admin.v1beta.IListConversionEventsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.admin.v1beta.IListConversionEventsRequest, - protos.google.analytics.admin.v1beta.IListConversionEventsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IConversionEvent>, - callback?: PaginationCallback< + request?: protos.google.analytics.admin.v1beta.IListConversionEventsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1beta.IListConversionEventsRequest, - protos.google.analytics.admin.v1beta.IListConversionEventsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IConversionEvent>): - Promise<[ - protos.google.analytics.admin.v1beta.IConversionEvent[], - protos.google.analytics.admin.v1beta.IListConversionEventsRequest|null, - protos.google.analytics.admin.v1beta.IListConversionEventsResponse - ]>|void { + | protos.google.analytics.admin.v1beta.IListConversionEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IConversionEvent + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1beta.IListConversionEventsRequest, + | protos.google.analytics.admin.v1beta.IListConversionEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IConversionEvent + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IConversionEvent[], + protos.google.analytics.admin.v1beta.IListConversionEventsRequest | null, + protos.google.analytics.admin.v1beta.IListConversionEventsResponse, + ] + > | 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.warn('DEP$AnalyticsAdminService-$ListConversionEvents','ListConversionEvents is deprecated and may be removed in a future version.', 'DeprecationWarning'); - const wrappedCallback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListConversionEventsRequest, - protos.google.analytics.admin.v1beta.IListConversionEventsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IConversionEvent>|undefined = callback + this.warn( + 'DEP$AnalyticsAdminService-$ListConversionEvents', + 'ListConversionEvents is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1beta.IListConversionEventsRequest, + | protos.google.analytics.admin.v1beta.IListConversionEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IConversionEvent + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listConversionEvents values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -6269,212 +8634,249 @@ export class AnalyticsAdminServiceClient { this._log.info('listConversionEvents request %j', request); return this.innerApiCalls .listConversionEvents(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1beta.IConversionEvent[], - protos.google.analytics.admin.v1beta.IListConversionEventsRequest|null, - protos.google.analytics.admin.v1beta.IListConversionEventsResponse - ]) => { - this._log.info('listConversionEvents values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1beta.IConversionEvent[], + protos.google.analytics.admin.v1beta.IListConversionEventsRequest | null, + protos.google.analytics.admin.v1beta.IListConversionEventsResponse, + ]) => { + this._log.info('listConversionEvents values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listConversionEvents`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the parent property. - * Example: 'properties/123' - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} request.pageToken - * A page token, received from a previous `ListConversionEvents` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListConversionEvents` - * must match the call that provided the page token. - * @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.analytics.admin.v1beta.ConversionEvent|ConversionEvent} 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 `listConversionEventsAsync()` - * 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. - * @deprecated ListConversionEvents is deprecated and may be removed in a future version. - */ + /** + * Equivalent to `listConversionEvents`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the parent property. + * Example: 'properties/123' + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} request.pageToken + * A page token, received from a previous `ListConversionEvents` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListConversionEvents` + * must match the call that provided the page token. + * @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.analytics.admin.v1beta.ConversionEvent|ConversionEvent} 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 `listConversionEventsAsync()` + * 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. + * @deprecated ListConversionEvents is deprecated and may be removed in a future version. + */ listConversionEventsStream( - request?: protos.google.analytics.admin.v1beta.IListConversionEventsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1beta.IListConversionEventsRequest, + 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['listConversionEvents']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); - this.warn('DEP$AnalyticsAdminService-$ListConversionEvents','ListConversionEvents is deprecated and may be removed in a future version.', 'DeprecationWarning'); + this.initialize().catch((err) => { + throw err; + }); + this.warn( + 'DEP$AnalyticsAdminService-$ListConversionEvents', + 'ListConversionEvents is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); this._log.info('listConversionEvents stream %j', request); return this.descriptors.page.listConversionEvents.createStream( this.innerApiCalls.listConversionEvents as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listConversionEvents`, 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 resource name of the parent property. - * Example: 'properties/123' - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} request.pageToken - * A page token, received from a previous `ListConversionEvents` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListConversionEvents` - * must match the call that provided the 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 protos.google.analytics.admin.v1beta.ConversionEvent|ConversionEvent}. 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 include:samples/generated/v1beta/analytics_admin_service.list_conversion_events.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ListConversionEvents_async - * @deprecated ListConversionEvents is deprecated and may be removed in a future version. - */ + /** + * Equivalent to `listConversionEvents`, 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 resource name of the parent property. + * Example: 'properties/123' + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} request.pageToken + * A page token, received from a previous `ListConversionEvents` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListConversionEvents` + * must match the call that provided the 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 protos.google.analytics.admin.v1beta.ConversionEvent|ConversionEvent}. 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 include:samples/generated/v1beta/analytics_admin_service.list_conversion_events.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ListConversionEvents_async + * @deprecated ListConversionEvents is deprecated and may be removed in a future version. + */ listConversionEventsAsync( - request?: protos.google.analytics.admin.v1beta.IListConversionEventsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1beta.IListConversionEventsRequest, + 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['listConversionEvents']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); - this.warn('DEP$AnalyticsAdminService-$ListConversionEvents','ListConversionEvents is deprecated and may be removed in a future version.', 'DeprecationWarning'); + this.initialize().catch((err) => { + throw err; + }); + this.warn( + 'DEP$AnalyticsAdminService-$ListConversionEvents', + 'ListConversionEvents is deprecated and may be removed in a future version.', + 'DeprecationWarning', + ); this._log.info('listConversionEvents iterate %j', request); return this.descriptors.page.listConversionEvents.asyncIterate( this.innerApiCalls['listConversionEvents'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Returns a list of Key Events in the specified parent property. - * Returns an empty list if no Key Events are found. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the parent property. - * Example: 'properties/123' - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} request.pageToken - * A page token, received from a previous `ListKeyEvents` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListKeyEvents` - * must match the call that provided the page token. - * @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.analytics.admin.v1beta.KeyEvent|KeyEvent}. - * 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 `listKeyEventsAsync()` - * 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. - */ + /** + * Returns a list of Key Events in the specified parent property. + * Returns an empty list if no Key Events are found. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the parent property. + * Example: 'properties/123' + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} request.pageToken + * A page token, received from a previous `ListKeyEvents` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListKeyEvents` + * must match the call that provided the page token. + * @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.analytics.admin.v1beta.KeyEvent|KeyEvent}. + * 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 `listKeyEventsAsync()` + * 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. + */ listKeyEvents( - request?: protos.google.analytics.admin.v1beta.IListKeyEventsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IKeyEvent[], - protos.google.analytics.admin.v1beta.IListKeyEventsRequest|null, - protos.google.analytics.admin.v1beta.IListKeyEventsResponse - ]>; + request?: protos.google.analytics.admin.v1beta.IListKeyEventsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IKeyEvent[], + protos.google.analytics.admin.v1beta.IListKeyEventsRequest | null, + protos.google.analytics.admin.v1beta.IListKeyEventsResponse, + ] + >; listKeyEvents( - request: protos.google.analytics.admin.v1beta.IListKeyEventsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListKeyEventsRequest, - protos.google.analytics.admin.v1beta.IListKeyEventsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IKeyEvent>): void; + request: protos.google.analytics.admin.v1beta.IListKeyEventsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.IListKeyEventsRequest, + | protos.google.analytics.admin.v1beta.IListKeyEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IKeyEvent + >, + ): void; listKeyEvents( - request: protos.google.analytics.admin.v1beta.IListKeyEventsRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListKeyEventsRequest, - protos.google.analytics.admin.v1beta.IListKeyEventsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IKeyEvent>): void; + request: protos.google.analytics.admin.v1beta.IListKeyEventsRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.IListKeyEventsRequest, + | protos.google.analytics.admin.v1beta.IListKeyEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IKeyEvent + >, + ): void; listKeyEvents( - request?: protos.google.analytics.admin.v1beta.IListKeyEventsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.admin.v1beta.IListKeyEventsRequest, - protos.google.analytics.admin.v1beta.IListKeyEventsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IKeyEvent>, - callback?: PaginationCallback< + request?: protos.google.analytics.admin.v1beta.IListKeyEventsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1beta.IListKeyEventsRequest, - protos.google.analytics.admin.v1beta.IListKeyEventsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IKeyEvent>): - Promise<[ - protos.google.analytics.admin.v1beta.IKeyEvent[], - protos.google.analytics.admin.v1beta.IListKeyEventsRequest|null, - protos.google.analytics.admin.v1beta.IListKeyEventsResponse - ]>|void { + | protos.google.analytics.admin.v1beta.IListKeyEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IKeyEvent + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1beta.IListKeyEventsRequest, + | protos.google.analytics.admin.v1beta.IListKeyEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IKeyEvent + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IKeyEvent[], + protos.google.analytics.admin.v1beta.IListKeyEventsRequest | null, + protos.google.analytics.admin.v1beta.IListKeyEventsResponse, + ] + > | 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.analytics.admin.v1beta.IListKeyEventsRequest, - protos.google.analytics.admin.v1beta.IListKeyEventsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IKeyEvent>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1beta.IListKeyEventsRequest, + | protos.google.analytics.admin.v1beta.IListKeyEventsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IKeyEvent + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listKeyEvents values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -6483,207 +8885,236 @@ export class AnalyticsAdminServiceClient { this._log.info('listKeyEvents request %j', request); return this.innerApiCalls .listKeyEvents(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1beta.IKeyEvent[], - protos.google.analytics.admin.v1beta.IListKeyEventsRequest|null, - protos.google.analytics.admin.v1beta.IListKeyEventsResponse - ]) => { - this._log.info('listKeyEvents values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1beta.IKeyEvent[], + protos.google.analytics.admin.v1beta.IListKeyEventsRequest | null, + protos.google.analytics.admin.v1beta.IListKeyEventsResponse, + ]) => { + this._log.info('listKeyEvents values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listKeyEvents`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name of the parent property. - * Example: 'properties/123' - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} request.pageToken - * A page token, received from a previous `ListKeyEvents` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListKeyEvents` - * must match the call that provided the page token. - * @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.analytics.admin.v1beta.KeyEvent|KeyEvent} 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 `listKeyEventsAsync()` - * 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 `listKeyEvents`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The resource name of the parent property. + * Example: 'properties/123' + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} request.pageToken + * A page token, received from a previous `ListKeyEvents` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListKeyEvents` + * must match the call that provided the page token. + * @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.analytics.admin.v1beta.KeyEvent|KeyEvent} 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 `listKeyEventsAsync()` + * 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. + */ listKeyEventsStream( - request?: protos.google.analytics.admin.v1beta.IListKeyEventsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1beta.IListKeyEventsRequest, + 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['listKeyEvents']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listKeyEvents stream %j', request); return this.descriptors.page.listKeyEvents.createStream( this.innerApiCalls.listKeyEvents as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listKeyEvents`, 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 resource name of the parent property. - * Example: 'properties/123' - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200; (higher values will be coerced to the maximum) - * @param {string} request.pageToken - * A page token, received from a previous `ListKeyEvents` call. - * Provide this to retrieve the subsequent page. - * When paginating, all other parameters provided to `ListKeyEvents` - * must match the call that provided the 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 protos.google.analytics.admin.v1beta.KeyEvent|KeyEvent}. 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 include:samples/generated/v1beta/analytics_admin_service.list_key_events.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ListKeyEvents_async - */ + /** + * Equivalent to `listKeyEvents`, 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 resource name of the parent property. + * Example: 'properties/123' + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200; (higher values will be coerced to the maximum) + * @param {string} request.pageToken + * A page token, received from a previous `ListKeyEvents` call. + * Provide this to retrieve the subsequent page. + * When paginating, all other parameters provided to `ListKeyEvents` + * must match the call that provided the 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 protos.google.analytics.admin.v1beta.KeyEvent|KeyEvent}. 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 include:samples/generated/v1beta/analytics_admin_service.list_key_events.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ListKeyEvents_async + */ listKeyEventsAsync( - request?: protos.google.analytics.admin.v1beta.IListKeyEventsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1beta.IListKeyEventsRequest, + 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['listKeyEvents']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listKeyEvents iterate %j', request); return this.descriptors.page.listKeyEvents.asyncIterate( this.innerApiCalls['listKeyEvents'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists CustomDimensions on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListCustomDimensions` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListCustomDimensions` - * must match the call that provided the page token. - * @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.analytics.admin.v1beta.CustomDimension|CustomDimension}. - * 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 `listCustomDimensionsAsync()` - * 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 CustomDimensions on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListCustomDimensions` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListCustomDimensions` + * must match the call that provided the page token. + * @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.analytics.admin.v1beta.CustomDimension|CustomDimension}. + * 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 `listCustomDimensionsAsync()` + * 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. + */ listCustomDimensions( - request?: protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.ICustomDimension[], - protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest|null, - protos.google.analytics.admin.v1beta.IListCustomDimensionsResponse - ]>; + request?: protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.ICustomDimension[], + protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest | null, + protos.google.analytics.admin.v1beta.IListCustomDimensionsResponse, + ] + >; listCustomDimensions( - request: protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest, - protos.google.analytics.admin.v1beta.IListCustomDimensionsResponse|null|undefined, - protos.google.analytics.admin.v1beta.ICustomDimension>): void; + request: protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest, + | protos.google.analytics.admin.v1beta.IListCustomDimensionsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.ICustomDimension + >, + ): void; listCustomDimensions( - request: protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest, - protos.google.analytics.admin.v1beta.IListCustomDimensionsResponse|null|undefined, - protos.google.analytics.admin.v1beta.ICustomDimension>): void; + request: protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest, + | protos.google.analytics.admin.v1beta.IListCustomDimensionsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.ICustomDimension + >, + ): void; listCustomDimensions( - request?: protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest, - protos.google.analytics.admin.v1beta.IListCustomDimensionsResponse|null|undefined, - protos.google.analytics.admin.v1beta.ICustomDimension>, - callback?: PaginationCallback< + request?: protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest, - protos.google.analytics.admin.v1beta.IListCustomDimensionsResponse|null|undefined, - protos.google.analytics.admin.v1beta.ICustomDimension>): - Promise<[ - protos.google.analytics.admin.v1beta.ICustomDimension[], - protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest|null, - protos.google.analytics.admin.v1beta.IListCustomDimensionsResponse - ]>|void { + | protos.google.analytics.admin.v1beta.IListCustomDimensionsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.ICustomDimension + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest, + | protos.google.analytics.admin.v1beta.IListCustomDimensionsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.ICustomDimension + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.ICustomDimension[], + protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest | null, + protos.google.analytics.admin.v1beta.IListCustomDimensionsResponse, + ] + > | 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.analytics.admin.v1beta.IListCustomDimensionsRequest, - protos.google.analytics.admin.v1beta.IListCustomDimensionsResponse|null|undefined, - protos.google.analytics.admin.v1beta.ICustomDimension>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest, + | protos.google.analytics.admin.v1beta.IListCustomDimensionsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.ICustomDimension + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listCustomDimensions values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -6692,207 +9123,236 @@ export class AnalyticsAdminServiceClient { this._log.info('listCustomDimensions request %j', request); return this.innerApiCalls .listCustomDimensions(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1beta.ICustomDimension[], - protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest|null, - protos.google.analytics.admin.v1beta.IListCustomDimensionsResponse - ]) => { - this._log.info('listCustomDimensions values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1beta.ICustomDimension[], + protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest | null, + protos.google.analytics.admin.v1beta.IListCustomDimensionsResponse, + ]) => { + this._log.info('listCustomDimensions values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listCustomDimensions`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListCustomDimensions` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListCustomDimensions` - * must match the call that provided the page token. - * @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.analytics.admin.v1beta.CustomDimension|CustomDimension} 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 `listCustomDimensionsAsync()` - * 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 `listCustomDimensions`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListCustomDimensions` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListCustomDimensions` + * must match the call that provided the page token. + * @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.analytics.admin.v1beta.CustomDimension|CustomDimension} 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 `listCustomDimensionsAsync()` + * 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. + */ listCustomDimensionsStream( - request?: protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest, + 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['listCustomDimensions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCustomDimensions stream %j', request); return this.descriptors.page.listCustomDimensions.createStream( this.innerApiCalls.listCustomDimensions as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listCustomDimensions`, 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. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListCustomDimensions` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListCustomDimensions` - * must match the call that provided the 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 protos.google.analytics.admin.v1beta.CustomDimension|CustomDimension}. 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 include:samples/generated/v1beta/analytics_admin_service.list_custom_dimensions.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ListCustomDimensions_async - */ + /** + * Equivalent to `listCustomDimensions`, 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. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListCustomDimensions` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListCustomDimensions` + * must match the call that provided the 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 protos.google.analytics.admin.v1beta.CustomDimension|CustomDimension}. 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 include:samples/generated/v1beta/analytics_admin_service.list_custom_dimensions.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ListCustomDimensions_async + */ listCustomDimensionsAsync( - request?: protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1beta.IListCustomDimensionsRequest, + 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['listCustomDimensions']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCustomDimensions iterate %j', request); return this.descriptors.page.listCustomDimensions.asyncIterate( this.innerApiCalls['listCustomDimensions'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists CustomMetrics on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListCustomMetrics` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListCustomMetrics` must - * match the call that provided the page token. - * @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.analytics.admin.v1beta.CustomMetric|CustomMetric}. - * 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 `listCustomMetricsAsync()` - * 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 CustomMetrics on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListCustomMetrics` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListCustomMetrics` must + * match the call that provided the page token. + * @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.analytics.admin.v1beta.CustomMetric|CustomMetric}. + * 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 `listCustomMetricsAsync()` + * 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. + */ listCustomMetrics( - request?: protos.google.analytics.admin.v1beta.IListCustomMetricsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.ICustomMetric[], - protos.google.analytics.admin.v1beta.IListCustomMetricsRequest|null, - protos.google.analytics.admin.v1beta.IListCustomMetricsResponse - ]>; + request?: protos.google.analytics.admin.v1beta.IListCustomMetricsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.ICustomMetric[], + protos.google.analytics.admin.v1beta.IListCustomMetricsRequest | null, + protos.google.analytics.admin.v1beta.IListCustomMetricsResponse, + ] + >; listCustomMetrics( - request: protos.google.analytics.admin.v1beta.IListCustomMetricsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListCustomMetricsRequest, - protos.google.analytics.admin.v1beta.IListCustomMetricsResponse|null|undefined, - protos.google.analytics.admin.v1beta.ICustomMetric>): void; + request: protos.google.analytics.admin.v1beta.IListCustomMetricsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.IListCustomMetricsRequest, + | protos.google.analytics.admin.v1beta.IListCustomMetricsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.ICustomMetric + >, + ): void; listCustomMetrics( - request: protos.google.analytics.admin.v1beta.IListCustomMetricsRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListCustomMetricsRequest, - protos.google.analytics.admin.v1beta.IListCustomMetricsResponse|null|undefined, - protos.google.analytics.admin.v1beta.ICustomMetric>): void; + request: protos.google.analytics.admin.v1beta.IListCustomMetricsRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.IListCustomMetricsRequest, + | protos.google.analytics.admin.v1beta.IListCustomMetricsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.ICustomMetric + >, + ): void; listCustomMetrics( - request?: protos.google.analytics.admin.v1beta.IListCustomMetricsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.admin.v1beta.IListCustomMetricsRequest, - protos.google.analytics.admin.v1beta.IListCustomMetricsResponse|null|undefined, - protos.google.analytics.admin.v1beta.ICustomMetric>, - callback?: PaginationCallback< + request?: protos.google.analytics.admin.v1beta.IListCustomMetricsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1beta.IListCustomMetricsRequest, - protos.google.analytics.admin.v1beta.IListCustomMetricsResponse|null|undefined, - protos.google.analytics.admin.v1beta.ICustomMetric>): - Promise<[ - protos.google.analytics.admin.v1beta.ICustomMetric[], - protos.google.analytics.admin.v1beta.IListCustomMetricsRequest|null, - protos.google.analytics.admin.v1beta.IListCustomMetricsResponse - ]>|void { + | protos.google.analytics.admin.v1beta.IListCustomMetricsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.ICustomMetric + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1beta.IListCustomMetricsRequest, + | protos.google.analytics.admin.v1beta.IListCustomMetricsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.ICustomMetric + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.ICustomMetric[], + protos.google.analytics.admin.v1beta.IListCustomMetricsRequest | null, + protos.google.analytics.admin.v1beta.IListCustomMetricsResponse, + ] + > | 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.analytics.admin.v1beta.IListCustomMetricsRequest, - protos.google.analytics.admin.v1beta.IListCustomMetricsResponse|null|undefined, - protos.google.analytics.admin.v1beta.ICustomMetric>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1beta.IListCustomMetricsRequest, + | protos.google.analytics.admin.v1beta.IListCustomMetricsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.ICustomMetric + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listCustomMetrics values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -6901,207 +9361,236 @@ export class AnalyticsAdminServiceClient { this._log.info('listCustomMetrics request %j', request); return this.innerApiCalls .listCustomMetrics(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1beta.ICustomMetric[], - protos.google.analytics.admin.v1beta.IListCustomMetricsRequest|null, - protos.google.analytics.admin.v1beta.IListCustomMetricsResponse - ]) => { - this._log.info('listCustomMetrics values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1beta.ICustomMetric[], + protos.google.analytics.admin.v1beta.IListCustomMetricsRequest | null, + protos.google.analytics.admin.v1beta.IListCustomMetricsResponse, + ]) => { + this._log.info('listCustomMetrics values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listCustomMetrics`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListCustomMetrics` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListCustomMetrics` must - * match the call that provided the page token. - * @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.analytics.admin.v1beta.CustomMetric|CustomMetric} 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 `listCustomMetricsAsync()` - * 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 `listCustomMetrics`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListCustomMetrics` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListCustomMetrics` must + * match the call that provided the page token. + * @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.analytics.admin.v1beta.CustomMetric|CustomMetric} 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 `listCustomMetricsAsync()` + * 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. + */ listCustomMetricsStream( - request?: protos.google.analytics.admin.v1beta.IListCustomMetricsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1beta.IListCustomMetricsRequest, + 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['listCustomMetrics']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCustomMetrics stream %j', request); return this.descriptors.page.listCustomMetrics.createStream( this.innerApiCalls.listCustomMetrics as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listCustomMetrics`, 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. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListCustomMetrics` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListCustomMetrics` must - * match the call that provided the 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 protos.google.analytics.admin.v1beta.CustomMetric|CustomMetric}. 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 include:samples/generated/v1beta/analytics_admin_service.list_custom_metrics.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ListCustomMetrics_async - */ + /** + * Equivalent to `listCustomMetrics`, 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. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListCustomMetrics` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListCustomMetrics` must + * match the call that provided the 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 protos.google.analytics.admin.v1beta.CustomMetric|CustomMetric}. 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 include:samples/generated/v1beta/analytics_admin_service.list_custom_metrics.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ListCustomMetrics_async + */ listCustomMetricsAsync( - request?: protos.google.analytics.admin.v1beta.IListCustomMetricsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1beta.IListCustomMetricsRequest, + 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['listCustomMetrics']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listCustomMetrics iterate %j', request); return this.descriptors.page.listCustomMetrics.asyncIterate( this.innerApiCalls['listCustomMetrics'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists DataStreams on a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListDataStreams` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListDataStreams` must - * match the call that provided the page token. - * @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.analytics.admin.v1beta.DataStream|DataStream}. - * 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 `listDataStreamsAsync()` - * 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 DataStreams on a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListDataStreams` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListDataStreams` must + * match the call that provided the page token. + * @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.analytics.admin.v1beta.DataStream|DataStream}. + * 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 `listDataStreamsAsync()` + * 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. + */ listDataStreams( - request?: protos.google.analytics.admin.v1beta.IListDataStreamsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.admin.v1beta.IDataStream[], - protos.google.analytics.admin.v1beta.IListDataStreamsRequest|null, - protos.google.analytics.admin.v1beta.IListDataStreamsResponse - ]>; + request?: protos.google.analytics.admin.v1beta.IListDataStreamsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IDataStream[], + protos.google.analytics.admin.v1beta.IListDataStreamsRequest | null, + protos.google.analytics.admin.v1beta.IListDataStreamsResponse, + ] + >; listDataStreams( - request: protos.google.analytics.admin.v1beta.IListDataStreamsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListDataStreamsRequest, - protos.google.analytics.admin.v1beta.IListDataStreamsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IDataStream>): void; + request: protos.google.analytics.admin.v1beta.IListDataStreamsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.IListDataStreamsRequest, + | protos.google.analytics.admin.v1beta.IListDataStreamsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IDataStream + >, + ): void; listDataStreams( - request: protos.google.analytics.admin.v1beta.IListDataStreamsRequest, - callback: PaginationCallback< - protos.google.analytics.admin.v1beta.IListDataStreamsRequest, - protos.google.analytics.admin.v1beta.IListDataStreamsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IDataStream>): void; + request: protos.google.analytics.admin.v1beta.IListDataStreamsRequest, + callback: PaginationCallback< + protos.google.analytics.admin.v1beta.IListDataStreamsRequest, + | protos.google.analytics.admin.v1beta.IListDataStreamsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IDataStream + >, + ): void; listDataStreams( - request?: protos.google.analytics.admin.v1beta.IListDataStreamsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.admin.v1beta.IListDataStreamsRequest, - protos.google.analytics.admin.v1beta.IListDataStreamsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IDataStream>, - callback?: PaginationCallback< + request?: protos.google.analytics.admin.v1beta.IListDataStreamsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.admin.v1beta.IListDataStreamsRequest, - protos.google.analytics.admin.v1beta.IListDataStreamsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IDataStream>): - Promise<[ - protos.google.analytics.admin.v1beta.IDataStream[], - protos.google.analytics.admin.v1beta.IListDataStreamsRequest|null, - protos.google.analytics.admin.v1beta.IListDataStreamsResponse - ]>|void { + | protos.google.analytics.admin.v1beta.IListDataStreamsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IDataStream + >, + callback?: PaginationCallback< + protos.google.analytics.admin.v1beta.IListDataStreamsRequest, + | protos.google.analytics.admin.v1beta.IListDataStreamsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IDataStream + >, + ): Promise< + [ + protos.google.analytics.admin.v1beta.IDataStream[], + protos.google.analytics.admin.v1beta.IListDataStreamsRequest | null, + protos.google.analytics.admin.v1beta.IListDataStreamsResponse, + ] + > | 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.analytics.admin.v1beta.IListDataStreamsRequest, - protos.google.analytics.admin.v1beta.IListDataStreamsResponse|null|undefined, - protos.google.analytics.admin.v1beta.IDataStream>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.admin.v1beta.IListDataStreamsRequest, + | protos.google.analytics.admin.v1beta.IListDataStreamsResponse + | null + | undefined, + protos.google.analytics.admin.v1beta.IDataStream + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listDataStreams values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -7110,118 +9599,122 @@ export class AnalyticsAdminServiceClient { this._log.info('listDataStreams request %j', request); return this.innerApiCalls .listDataStreams(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.admin.v1beta.IDataStream[], - protos.google.analytics.admin.v1beta.IListDataStreamsRequest|null, - protos.google.analytics.admin.v1beta.IListDataStreamsResponse - ]) => { - this._log.info('listDataStreams values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.admin.v1beta.IDataStream[], + protos.google.analytics.admin.v1beta.IListDataStreamsRequest | null, + protos.google.analytics.admin.v1beta.IListDataStreamsResponse, + ]) => { + this._log.info('listDataStreams values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listDataStreams`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListDataStreams` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListDataStreams` must - * match the call that provided the page token. - * @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.analytics.admin.v1beta.DataStream|DataStream} 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 `listDataStreamsAsync()` - * 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 `listDataStreams`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListDataStreams` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListDataStreams` must + * match the call that provided the page token. + * @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.analytics.admin.v1beta.DataStream|DataStream} 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 `listDataStreamsAsync()` + * 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. + */ listDataStreamsStream( - request?: protos.google.analytics.admin.v1beta.IListDataStreamsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.admin.v1beta.IListDataStreamsRequest, + 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['listDataStreams']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listDataStreams stream %j', request); return this.descriptors.page.listDataStreams.createStream( this.innerApiCalls.listDataStreams as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listDataStreams`, 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. Example format: properties/1234 - * @param {number} request.pageSize - * The maximum number of resources to return. - * If unspecified, at most 50 resources will be returned. - * The maximum value is 200 (higher values will be coerced to the maximum). - * @param {string} request.pageToken - * A page token, received from a previous `ListDataStreams` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListDataStreams` must - * match the call that provided the 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 protos.google.analytics.admin.v1beta.DataStream|DataStream}. 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 include:samples/generated/v1beta/analytics_admin_service.list_data_streams.js - * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ListDataStreams_async - */ + /** + * Equivalent to `listDataStreams`, 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. Example format: properties/1234 + * @param {number} request.pageSize + * The maximum number of resources to return. + * If unspecified, at most 50 resources will be returned. + * The maximum value is 200 (higher values will be coerced to the maximum). + * @param {string} request.pageToken + * A page token, received from a previous `ListDataStreams` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListDataStreams` must + * match the call that provided the 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 protos.google.analytics.admin.v1beta.DataStream|DataStream}. 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 include:samples/generated/v1beta/analytics_admin_service.list_data_streams.js + * region_tag:analyticsadmin_v1beta_generated_AnalyticsAdminService_ListDataStreams_async + */ listDataStreamsAsync( - request?: protos.google.analytics.admin.v1beta.IListDataStreamsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.admin.v1beta.IListDataStreamsRequest, + 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['listDataStreams']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listDataStreams iterate %j', request); return this.descriptors.page.listDataStreams.asyncIterate( this.innerApiCalls['listDataStreams'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -7234,7 +9727,7 @@ export class AnalyticsAdminServiceClient { * @param {string} account * @returns {string} Resource name string. */ - accountPath(account:string) { + accountPath(account: string) { return this.pathTemplates.accountPathTemplate.render({ account: account, }); @@ -7257,7 +9750,7 @@ export class AnalyticsAdminServiceClient { * @param {string} account_summary * @returns {string} Resource name string. */ - accountSummaryPath(accountSummary:string) { + accountSummaryPath(accountSummary: string) { return this.pathTemplates.accountSummaryPathTemplate.render({ account_summary: accountSummary, }); @@ -7271,7 +9764,9 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the account_summary. */ matchAccountSummaryFromAccountSummaryName(accountSummaryName: string) { - return this.pathTemplates.accountSummaryPathTemplate.match(accountSummaryName).account_summary; + return this.pathTemplates.accountSummaryPathTemplate.match( + accountSummaryName, + ).account_summary; } /** @@ -7281,7 +9776,7 @@ export class AnalyticsAdminServiceClient { * @param {string} conversion_event * @returns {string} Resource name string. */ - conversionEventPath(property:string,conversionEvent:string) { + conversionEventPath(property: string, conversionEvent: string) { return this.pathTemplates.conversionEventPathTemplate.render({ property: property, conversion_event: conversionEvent, @@ -7296,7 +9791,9 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the property. */ matchPropertyFromConversionEventName(conversionEventName: string) { - return this.pathTemplates.conversionEventPathTemplate.match(conversionEventName).property; + return this.pathTemplates.conversionEventPathTemplate.match( + conversionEventName, + ).property; } /** @@ -7307,7 +9804,9 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the conversion_event. */ matchConversionEventFromConversionEventName(conversionEventName: string) { - return this.pathTemplates.conversionEventPathTemplate.match(conversionEventName).conversion_event; + return this.pathTemplates.conversionEventPathTemplate.match( + conversionEventName, + ).conversion_event; } /** @@ -7317,7 +9816,7 @@ export class AnalyticsAdminServiceClient { * @param {string} custom_dimension * @returns {string} Resource name string. */ - customDimensionPath(property:string,customDimension:string) { + customDimensionPath(property: string, customDimension: string) { return this.pathTemplates.customDimensionPathTemplate.render({ property: property, custom_dimension: customDimension, @@ -7332,7 +9831,9 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the property. */ matchPropertyFromCustomDimensionName(customDimensionName: string) { - return this.pathTemplates.customDimensionPathTemplate.match(customDimensionName).property; + return this.pathTemplates.customDimensionPathTemplate.match( + customDimensionName, + ).property; } /** @@ -7343,7 +9844,9 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the custom_dimension. */ matchCustomDimensionFromCustomDimensionName(customDimensionName: string) { - return this.pathTemplates.customDimensionPathTemplate.match(customDimensionName).custom_dimension; + return this.pathTemplates.customDimensionPathTemplate.match( + customDimensionName, + ).custom_dimension; } /** @@ -7353,7 +9856,7 @@ export class AnalyticsAdminServiceClient { * @param {string} custom_metric * @returns {string} Resource name string. */ - customMetricPath(property:string,customMetric:string) { + customMetricPath(property: string, customMetric: string) { return this.pathTemplates.customMetricPathTemplate.render({ property: property, custom_metric: customMetric, @@ -7368,7 +9871,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the property. */ matchPropertyFromCustomMetricName(customMetricName: string) { - return this.pathTemplates.customMetricPathTemplate.match(customMetricName).property; + return this.pathTemplates.customMetricPathTemplate.match(customMetricName) + .property; } /** @@ -7379,7 +9883,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the custom_metric. */ matchCustomMetricFromCustomMetricName(customMetricName: string) { - return this.pathTemplates.customMetricPathTemplate.match(customMetricName).custom_metric; + return this.pathTemplates.customMetricPathTemplate.match(customMetricName) + .custom_metric; } /** @@ -7388,7 +9893,7 @@ export class AnalyticsAdminServiceClient { * @param {string} property * @returns {string} Resource name string. */ - dataRetentionSettingsPath(property:string) { + dataRetentionSettingsPath(property: string) { return this.pathTemplates.dataRetentionSettingsPathTemplate.render({ property: property, }); @@ -7401,8 +9906,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing DataRetentionSettings resource. * @returns {string} A string representing the property. */ - matchPropertyFromDataRetentionSettingsName(dataRetentionSettingsName: string) { - return this.pathTemplates.dataRetentionSettingsPathTemplate.match(dataRetentionSettingsName).property; + matchPropertyFromDataRetentionSettingsName( + dataRetentionSettingsName: string, + ) { + return this.pathTemplates.dataRetentionSettingsPathTemplate.match( + dataRetentionSettingsName, + ).property; } /** @@ -7411,7 +9920,7 @@ export class AnalyticsAdminServiceClient { * @param {string} account * @returns {string} Resource name string. */ - dataSharingSettingsPath(account:string) { + dataSharingSettingsPath(account: string) { return this.pathTemplates.dataSharingSettingsPathTemplate.render({ account: account, }); @@ -7425,7 +9934,9 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the account. */ matchAccountFromDataSharingSettingsName(dataSharingSettingsName: string) { - return this.pathTemplates.dataSharingSettingsPathTemplate.match(dataSharingSettingsName).account; + return this.pathTemplates.dataSharingSettingsPathTemplate.match( + dataSharingSettingsName, + ).account; } /** @@ -7435,7 +9946,7 @@ export class AnalyticsAdminServiceClient { * @param {string} data_stream * @returns {string} Resource name string. */ - dataStreamPath(property:string,dataStream:string) { + dataStreamPath(property: string, dataStream: string) { return this.pathTemplates.dataStreamPathTemplate.render({ property: property, data_stream: dataStream, @@ -7450,7 +9961,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the property. */ matchPropertyFromDataStreamName(dataStreamName: string) { - return this.pathTemplates.dataStreamPathTemplate.match(dataStreamName).property; + return this.pathTemplates.dataStreamPathTemplate.match(dataStreamName) + .property; } /** @@ -7461,7 +9973,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the data_stream. */ matchDataStreamFromDataStreamName(dataStreamName: string) { - return this.pathTemplates.dataStreamPathTemplate.match(dataStreamName).data_stream; + return this.pathTemplates.dataStreamPathTemplate.match(dataStreamName) + .data_stream; } /** @@ -7471,7 +9984,7 @@ export class AnalyticsAdminServiceClient { * @param {string} firebase_link * @returns {string} Resource name string. */ - firebaseLinkPath(property:string,firebaseLink:string) { + firebaseLinkPath(property: string, firebaseLink: string) { return this.pathTemplates.firebaseLinkPathTemplate.render({ property: property, firebase_link: firebaseLink, @@ -7486,7 +9999,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the property. */ matchPropertyFromFirebaseLinkName(firebaseLinkName: string) { - return this.pathTemplates.firebaseLinkPathTemplate.match(firebaseLinkName).property; + return this.pathTemplates.firebaseLinkPathTemplate.match(firebaseLinkName) + .property; } /** @@ -7497,7 +10011,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the firebase_link. */ matchFirebaseLinkFromFirebaseLinkName(firebaseLinkName: string) { - return this.pathTemplates.firebaseLinkPathTemplate.match(firebaseLinkName).firebase_link; + return this.pathTemplates.firebaseLinkPathTemplate.match(firebaseLinkName) + .firebase_link; } /** @@ -7507,7 +10022,7 @@ export class AnalyticsAdminServiceClient { * @param {string} google_ads_link * @returns {string} Resource name string. */ - googleAdsLinkPath(property:string,googleAdsLink:string) { + googleAdsLinkPath(property: string, googleAdsLink: string) { return this.pathTemplates.googleAdsLinkPathTemplate.render({ property: property, google_ads_link: googleAdsLink, @@ -7522,7 +10037,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the property. */ matchPropertyFromGoogleAdsLinkName(googleAdsLinkName: string) { - return this.pathTemplates.googleAdsLinkPathTemplate.match(googleAdsLinkName).property; + return this.pathTemplates.googleAdsLinkPathTemplate.match(googleAdsLinkName) + .property; } /** @@ -7533,7 +10049,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the google_ads_link. */ matchGoogleAdsLinkFromGoogleAdsLinkName(googleAdsLinkName: string) { - return this.pathTemplates.googleAdsLinkPathTemplate.match(googleAdsLinkName).google_ads_link; + return this.pathTemplates.googleAdsLinkPathTemplate.match(googleAdsLinkName) + .google_ads_link; } /** @@ -7543,7 +10060,7 @@ export class AnalyticsAdminServiceClient { * @param {string} key_event * @returns {string} Resource name string. */ - keyEventPath(property:string,keyEvent:string) { + keyEventPath(property: string, keyEvent: string) { return this.pathTemplates.keyEventPathTemplate.render({ property: property, key_event: keyEvent, @@ -7569,7 +10086,8 @@ export class AnalyticsAdminServiceClient { * @returns {string} A string representing the key_event. */ matchKeyEventFromKeyEventName(keyEventName: string) { - return this.pathTemplates.keyEventPathTemplate.match(keyEventName).key_event; + return this.pathTemplates.keyEventPathTemplate.match(keyEventName) + .key_event; } /** @@ -7580,7 +10098,11 @@ export class AnalyticsAdminServiceClient { * @param {string} measurement_protocol_secret * @returns {string} Resource name string. */ - measurementProtocolSecretPath(property:string,dataStream:string,measurementProtocolSecret:string) { + measurementProtocolSecretPath( + property: string, + dataStream: string, + measurementProtocolSecret: string, + ) { return this.pathTemplates.measurementProtocolSecretPathTemplate.render({ property: property, data_stream: dataStream, @@ -7595,8 +10117,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing MeasurementProtocolSecret resource. * @returns {string} A string representing the property. */ - matchPropertyFromMeasurementProtocolSecretName(measurementProtocolSecretName: string) { - return this.pathTemplates.measurementProtocolSecretPathTemplate.match(measurementProtocolSecretName).property; + matchPropertyFromMeasurementProtocolSecretName( + measurementProtocolSecretName: string, + ) { + return this.pathTemplates.measurementProtocolSecretPathTemplate.match( + measurementProtocolSecretName, + ).property; } /** @@ -7606,8 +10132,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing MeasurementProtocolSecret resource. * @returns {string} A string representing the data_stream. */ - matchDataStreamFromMeasurementProtocolSecretName(measurementProtocolSecretName: string) { - return this.pathTemplates.measurementProtocolSecretPathTemplate.match(measurementProtocolSecretName).data_stream; + matchDataStreamFromMeasurementProtocolSecretName( + measurementProtocolSecretName: string, + ) { + return this.pathTemplates.measurementProtocolSecretPathTemplate.match( + measurementProtocolSecretName, + ).data_stream; } /** @@ -7617,8 +10147,12 @@ export class AnalyticsAdminServiceClient { * A fully-qualified path representing MeasurementProtocolSecret resource. * @returns {string} A string representing the measurement_protocol_secret. */ - matchMeasurementProtocolSecretFromMeasurementProtocolSecretName(measurementProtocolSecretName: string) { - return this.pathTemplates.measurementProtocolSecretPathTemplate.match(measurementProtocolSecretName).measurement_protocol_secret; + matchMeasurementProtocolSecretFromMeasurementProtocolSecretName( + measurementProtocolSecretName: string, + ) { + return this.pathTemplates.measurementProtocolSecretPathTemplate.match( + measurementProtocolSecretName, + ).measurement_protocol_secret; } /** @@ -7627,7 +10161,7 @@ export class AnalyticsAdminServiceClient { * @param {string} property * @returns {string} Resource name string. */ - propertyPath(property:string) { + propertyPath(property: string) { return this.pathTemplates.propertyPathTemplate.render({ property: property, }); @@ -7652,7 +10186,7 @@ export class AnalyticsAdminServiceClient { */ close(): Promise { if (this.analyticsAdminServiceStub && !this._terminated) { - return this.analyticsAdminServiceStub.then(stub => { + return this.analyticsAdminServiceStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -7660,4 +10194,4 @@ export class AnalyticsAdminServiceClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-analytics-admin/src/v1beta/index.ts b/packages/google-analytics-admin/src/v1beta/index.ts index 8aabd5686dc9..7d116996ad4a 100644 --- a/packages/google-analytics-admin/src/v1beta/index.ts +++ b/packages/google-analytics-admin/src/v1beta/index.ts @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {AnalyticsAdminServiceClient} from './analytics_admin_service_client'; +export { AnalyticsAdminServiceClient } from './analytics_admin_service_client'; diff --git a/packages/google-analytics-admin/system-test/fixtures/sample/src/index.ts b/packages/google-analytics-admin/system-test/fixtures/sample/src/index.ts index a6e3b7253316..2a7b55f6139c 100644 --- a/packages/google-analytics-admin/system-test/fixtures/sample/src/index.ts +++ b/packages/google-analytics-admin/system-test/fixtures/sample/src/index.ts @@ -16,10 +16,12 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {AnalyticsAdminServiceClient} from '@google-analytics/admin'; +import { AnalyticsAdminServiceClient } from '@google-analytics/admin'; // check that the client class type name can be used -function doStuffWithAnalyticsAdminServiceClient(client: AnalyticsAdminServiceClient) { +function doStuffWithAnalyticsAdminServiceClient( + client: AnalyticsAdminServiceClient, +) { client.close(); } diff --git a/packages/google-analytics-admin/system-test/install.ts b/packages/google-analytics-admin/system-test/install.ts index f66069aa3940..ccf167042d2e 100644 --- a/packages/google-analytics-admin/system-test/install.ts +++ b/packages/google-analytics-admin/system-test/install.ts @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - cjs: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/packages/google-analytics-admin/test/gapic_analytics_admin_service_v1alpha.ts b/packages/google-analytics-admin/test/gapic_analytics_admin_service_v1alpha.ts index 7bdbecf5d27a..dfbc4890f7ac 100644 --- a/packages/google-analytics-admin/test/gapic_analytics_admin_service_v1alpha.ts +++ b/packages/google-analytics-admin/test/gapic_analytics_admin_service_v1alpha.ts @@ -19,22155 +19,29915 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as analyticsadminserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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 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('v1alpha.AnalyticsAdminServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'analyticsadmin.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient(); - 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 = analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient.servicePath; - assert.strictEqual(servicePath, 'analyticsadmin.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'analyticsadmin.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'analyticsadmin.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'analyticsadmin.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 analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'analyticsadmin.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 analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'analyticsadmin.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 analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.analyticsAdminServiceStub, undefined); - await client.initialize(); - assert(client.analyticsAdminServiceStub); - }); - - it('has close method for the initialized client', done => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.analyticsAdminServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.analyticsAdminServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - 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 analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - 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('getAccount', () => { - it('invokes getAccount without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetAccountRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.Account() - ); - client.innerApiCalls.getAccount = stubSimpleCall(expectedResponse); - const [response] = await client.getAccount(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAccount without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetAccountRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.Account() - ); - client.innerApiCalls.getAccount = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getAccount( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IAccount|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAccount with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetAccountRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getAccount = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getAccount(request), expectedError); - const actualRequest = (client.innerApiCalls.getAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAccount with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetAccountRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getAccount(request), expectedError); - }); - }); - - describe('deleteAccount', () => { - it('invokes deleteAccount without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteAccountRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteAccount = stubSimpleCall(expectedResponse); - const [response] = await client.deleteAccount(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteAccount without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteAccountRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteAccount = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteAccount( - 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.deleteAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteAccount with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteAccountRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteAccount = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteAccount(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteAccount with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteAccountRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteAccount(request), expectedError); - }); - }); - - describe('updateAccount', () => { - it('invokes updateAccount without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateAccountRequest() - ); - request.account ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateAccountRequest', ['account', 'name']); - request.account.name = defaultValue1; - const expectedHeaderRequestParams = `account.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.Account() - ); - client.innerApiCalls.updateAccount = stubSimpleCall(expectedResponse); - const [response] = await client.updateAccount(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateAccount without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateAccountRequest() - ); - request.account ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateAccountRequest', ['account', 'name']); - request.account.name = defaultValue1; - const expectedHeaderRequestParams = `account.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.Account() - ); - client.innerApiCalls.updateAccount = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateAccount( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IAccount|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateAccount with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateAccountRequest() - ); - request.account ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateAccountRequest', ['account', 'name']); - request.account.name = defaultValue1; - const expectedHeaderRequestParams = `account.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateAccount = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateAccount(request), expectedError); - const actualRequest = (client.innerApiCalls.updateAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateAccount with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateAccountRequest() - ); - request.account ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateAccountRequest', ['account', 'name']); - request.account.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateAccount(request), expectedError); - }); - }); - - describe('provisionAccountTicket', () => { - it('invokes provisionAccountTicket without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ProvisionAccountTicketRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ProvisionAccountTicketResponse() - ); - client.innerApiCalls.provisionAccountTicket = stubSimpleCall(expectedResponse); - const [response] = await client.provisionAccountTicket(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes provisionAccountTicket without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ProvisionAccountTicketRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ProvisionAccountTicketResponse() - ); - client.innerApiCalls.provisionAccountTicket = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.provisionAccountTicket( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IProvisionAccountTicketResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes provisionAccountTicket with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ProvisionAccountTicketRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.provisionAccountTicket = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.provisionAccountTicket(request), expectedError); - }); - - it('invokes provisionAccountTicket with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ProvisionAccountTicketRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.provisionAccountTicket(request), expectedError); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'analyticsadmin.googleapis.com'); + }); + + it('has universeDomain', () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient(); + 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 = + analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient + .servicePath; + assert.strictEqual(servicePath, 'analyticsadmin.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient + .apiEndpoint; + assert.strictEqual(apiEndpoint, 'analyticsadmin.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + universeDomain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'analyticsadmin.example.com'); }); - describe('getProperty', () => { - it('invokes getProperty without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetPropertyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetPropertyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.Property() - ); - client.innerApiCalls.getProperty = stubSimpleCall(expectedResponse); - const [response] = await client.getProperty(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getProperty as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getProperty as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getProperty without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetPropertyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetPropertyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.Property() - ); - client.innerApiCalls.getProperty = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getProperty( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IProperty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getProperty as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getProperty as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getProperty with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetPropertyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetPropertyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getProperty = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getProperty(request), expectedError); - const actualRequest = (client.innerApiCalls.getProperty as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getProperty as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getProperty with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetPropertyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetPropertyRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getProperty(request), expectedError); - }); - }); - - describe('createProperty', () => { - it('invokes createProperty without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreatePropertyRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.Property() - ); - client.innerApiCalls.createProperty = stubSimpleCall(expectedResponse); - const [response] = await client.createProperty(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes createProperty without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreatePropertyRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.Property() - ); - client.innerApiCalls.createProperty = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createProperty( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IProperty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes createProperty with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreatePropertyRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createProperty = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createProperty(request), expectedError); - }); - - it('invokes createProperty with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreatePropertyRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createProperty(request), expectedError); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + universe_domain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'analyticsadmin.example.com'); }); - describe('deleteProperty', () => { - it('invokes deleteProperty without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeletePropertyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeletePropertyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.Property() - ); - client.innerApiCalls.deleteProperty = stubSimpleCall(expectedResponse); - const [response] = await client.deleteProperty(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteProperty as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteProperty as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteProperty without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeletePropertyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeletePropertyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.Property() - ); - client.innerApiCalls.deleteProperty = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteProperty( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IProperty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteProperty as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteProperty as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteProperty with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeletePropertyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeletePropertyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteProperty = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteProperty(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteProperty as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteProperty as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteProperty with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeletePropertyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeletePropertyRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteProperty(request), expectedError); - }); - }); - - describe('updateProperty', () => { - it('invokes updateProperty without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdatePropertyRequest() - ); - request.property ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdatePropertyRequest', ['property', 'name']); - request.property.name = defaultValue1; - const expectedHeaderRequestParams = `property.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.Property() - ); - client.innerApiCalls.updateProperty = stubSimpleCall(expectedResponse); - const [response] = await client.updateProperty(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateProperty as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateProperty as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateProperty without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdatePropertyRequest() - ); - request.property ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdatePropertyRequest', ['property', 'name']); - request.property.name = defaultValue1; - const expectedHeaderRequestParams = `property.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.Property() - ); - client.innerApiCalls.updateProperty = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateProperty( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IProperty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateProperty as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateProperty as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateProperty with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdatePropertyRequest() - ); - request.property ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdatePropertyRequest', ['property', 'name']); - request.property.name = defaultValue1; - const expectedHeaderRequestParams = `property.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateProperty = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateProperty(request), expectedError); - const actualRequest = (client.innerApiCalls.updateProperty as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateProperty as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateProperty with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdatePropertyRequest() - ); - request.property ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdatePropertyRequest', ['property', 'name']); - request.property.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateProperty(request), expectedError); - }); - }); - - describe('createFirebaseLink', () => { - it('invokes createFirebaseLink without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateFirebaseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateFirebaseLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.FirebaseLink() - ); - client.innerApiCalls.createFirebaseLink = stubSimpleCall(expectedResponse); - const [response] = await client.createFirebaseLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createFirebaseLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createFirebaseLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createFirebaseLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateFirebaseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateFirebaseLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.FirebaseLink() - ); - client.innerApiCalls.createFirebaseLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createFirebaseLink( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IFirebaseLink|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createFirebaseLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createFirebaseLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createFirebaseLink with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateFirebaseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateFirebaseLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createFirebaseLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createFirebaseLink(request), expectedError); - const actualRequest = (client.innerApiCalls.createFirebaseLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createFirebaseLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createFirebaseLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateFirebaseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateFirebaseLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createFirebaseLink(request), expectedError); - }); - }); - - describe('deleteFirebaseLink', () => { - it('invokes deleteFirebaseLink without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteFirebaseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteFirebaseLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteFirebaseLink = stubSimpleCall(expectedResponse); - const [response] = await client.deleteFirebaseLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteFirebaseLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteFirebaseLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteFirebaseLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteFirebaseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteFirebaseLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteFirebaseLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteFirebaseLink( - 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.deleteFirebaseLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteFirebaseLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteFirebaseLink with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteFirebaseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteFirebaseLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteFirebaseLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteFirebaseLink(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteFirebaseLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteFirebaseLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteFirebaseLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteFirebaseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteFirebaseLinkRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteFirebaseLink(request), expectedError); - }); - }); - - describe('getGlobalSiteTag', () => { - it('invokes getGlobalSiteTag without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetGlobalSiteTagRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetGlobalSiteTagRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GlobalSiteTag() - ); - client.innerApiCalls.getGlobalSiteTag = stubSimpleCall(expectedResponse); - const [response] = await client.getGlobalSiteTag(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getGlobalSiteTag as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGlobalSiteTag as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getGlobalSiteTag without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetGlobalSiteTagRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetGlobalSiteTagRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GlobalSiteTag() - ); - client.innerApiCalls.getGlobalSiteTag = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getGlobalSiteTag( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IGlobalSiteTag|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getGlobalSiteTag as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGlobalSiteTag as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getGlobalSiteTag with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetGlobalSiteTagRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetGlobalSiteTagRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getGlobalSiteTag = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getGlobalSiteTag(request), expectedError); - const actualRequest = (client.innerApiCalls.getGlobalSiteTag as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGlobalSiteTag as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getGlobalSiteTag with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetGlobalSiteTagRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetGlobalSiteTagRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getGlobalSiteTag(request), expectedError); - }); - }); - - describe('createGoogleAdsLink', () => { - it('invokes createGoogleAdsLink without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateGoogleAdsLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateGoogleAdsLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GoogleAdsLink() - ); - client.innerApiCalls.createGoogleAdsLink = stubSimpleCall(expectedResponse); - const [response] = await client.createGoogleAdsLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createGoogleAdsLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createGoogleAdsLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createGoogleAdsLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateGoogleAdsLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateGoogleAdsLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GoogleAdsLink() - ); - client.innerApiCalls.createGoogleAdsLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createGoogleAdsLink( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IGoogleAdsLink|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createGoogleAdsLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createGoogleAdsLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createGoogleAdsLink with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateGoogleAdsLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateGoogleAdsLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createGoogleAdsLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createGoogleAdsLink(request), expectedError); - const actualRequest = (client.innerApiCalls.createGoogleAdsLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createGoogleAdsLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createGoogleAdsLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateGoogleAdsLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateGoogleAdsLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createGoogleAdsLink(request), expectedError); - }); - }); - - describe('updateGoogleAdsLink', () => { - it('invokes updateGoogleAdsLink without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest() - ); - request.googleAdsLink ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest', ['googleAdsLink', 'name']); - request.googleAdsLink.name = defaultValue1; - const expectedHeaderRequestParams = `google_ads_link.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GoogleAdsLink() - ); - client.innerApiCalls.updateGoogleAdsLink = stubSimpleCall(expectedResponse); - const [response] = await client.updateGoogleAdsLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateGoogleAdsLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGoogleAdsLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateGoogleAdsLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest() - ); - request.googleAdsLink ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest', ['googleAdsLink', 'name']); - request.googleAdsLink.name = defaultValue1; - const expectedHeaderRequestParams = `google_ads_link.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GoogleAdsLink() - ); - client.innerApiCalls.updateGoogleAdsLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateGoogleAdsLink( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IGoogleAdsLink|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateGoogleAdsLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGoogleAdsLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateGoogleAdsLink with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest() - ); - request.googleAdsLink ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest', ['googleAdsLink', 'name']); - request.googleAdsLink.name = defaultValue1; - const expectedHeaderRequestParams = `google_ads_link.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateGoogleAdsLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateGoogleAdsLink(request), expectedError); - const actualRequest = (client.innerApiCalls.updateGoogleAdsLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGoogleAdsLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateGoogleAdsLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest() - ); - request.googleAdsLink ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest', ['googleAdsLink', 'name']); - request.googleAdsLink.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateGoogleAdsLink(request), expectedError); - }); - }); - - describe('deleteGoogleAdsLink', () => { - it('invokes deleteGoogleAdsLink without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteGoogleAdsLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteGoogleAdsLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteGoogleAdsLink = stubSimpleCall(expectedResponse); - const [response] = await client.deleteGoogleAdsLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteGoogleAdsLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteGoogleAdsLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteGoogleAdsLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteGoogleAdsLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteGoogleAdsLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteGoogleAdsLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteGoogleAdsLink( - 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.deleteGoogleAdsLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteGoogleAdsLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteGoogleAdsLink with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteGoogleAdsLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteGoogleAdsLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteGoogleAdsLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteGoogleAdsLink(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteGoogleAdsLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteGoogleAdsLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteGoogleAdsLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteGoogleAdsLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteGoogleAdsLinkRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteGoogleAdsLink(request), expectedError); - }); - }); - - describe('getDataSharingSettings', () => { - it('invokes getDataSharingSettings without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDataSharingSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDataSharingSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DataSharingSettings() - ); - client.innerApiCalls.getDataSharingSettings = stubSimpleCall(expectedResponse); - const [response] = await client.getDataSharingSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDataSharingSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataSharingSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDataSharingSettings without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDataSharingSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDataSharingSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DataSharingSettings() - ); - client.innerApiCalls.getDataSharingSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getDataSharingSettings( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IDataSharingSettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDataSharingSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataSharingSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDataSharingSettings with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDataSharingSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDataSharingSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getDataSharingSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getDataSharingSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.getDataSharingSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataSharingSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDataSharingSettings with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDataSharingSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDataSharingSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getDataSharingSettings(request), expectedError); - }); - }); - - describe('getMeasurementProtocolSecret', () => { - it('invokes getMeasurementProtocolSecret without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret() - ); - client.innerApiCalls.getMeasurementProtocolSecret = stubSimpleCall(expectedResponse); - const [response] = await client.getMeasurementProtocolSecret(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getMeasurementProtocolSecret without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret() - ); - client.innerApiCalls.getMeasurementProtocolSecret = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getMeasurementProtocolSecret( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getMeasurementProtocolSecret with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getMeasurementProtocolSecret = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getMeasurementProtocolSecret(request), expectedError); - const actualRequest = (client.innerApiCalls.getMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getMeasurementProtocolSecret with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getMeasurementProtocolSecret(request), expectedError); - }); - }); - - describe('createMeasurementProtocolSecret', () => { - it('invokes createMeasurementProtocolSecret without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateMeasurementProtocolSecretRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret() - ); - client.innerApiCalls.createMeasurementProtocolSecret = stubSimpleCall(expectedResponse); - const [response] = await client.createMeasurementProtocolSecret(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createMeasurementProtocolSecret without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateMeasurementProtocolSecretRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret() - ); - client.innerApiCalls.createMeasurementProtocolSecret = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createMeasurementProtocolSecret( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createMeasurementProtocolSecret with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateMeasurementProtocolSecretRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createMeasurementProtocolSecret = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createMeasurementProtocolSecret(request), expectedError); - const actualRequest = (client.innerApiCalls.createMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createMeasurementProtocolSecret with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateMeasurementProtocolSecretRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createMeasurementProtocolSecret(request), expectedError); - }); - }); - - describe('deleteMeasurementProtocolSecret', () => { - it('invokes deleteMeasurementProtocolSecret without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteMeasurementProtocolSecretRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteMeasurementProtocolSecret = stubSimpleCall(expectedResponse); - const [response] = await client.deleteMeasurementProtocolSecret(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteMeasurementProtocolSecret without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteMeasurementProtocolSecretRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteMeasurementProtocolSecret = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteMeasurementProtocolSecret( - 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.deleteMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteMeasurementProtocolSecret with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteMeasurementProtocolSecretRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteMeasurementProtocolSecret = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteMeasurementProtocolSecret(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteMeasurementProtocolSecret with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteMeasurementProtocolSecretRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteMeasurementProtocolSecret(request), expectedError); - }); - }); - - describe('updateMeasurementProtocolSecret', () => { - it('invokes updateMeasurementProtocolSecret without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateMeasurementProtocolSecretRequest() - ); - request.measurementProtocolSecret ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateMeasurementProtocolSecretRequest', ['measurementProtocolSecret', 'name']); - request.measurementProtocolSecret.name = defaultValue1; - const expectedHeaderRequestParams = `measurement_protocol_secret.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret() - ); - client.innerApiCalls.updateMeasurementProtocolSecret = stubSimpleCall(expectedResponse); - const [response] = await client.updateMeasurementProtocolSecret(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateMeasurementProtocolSecret without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateMeasurementProtocolSecretRequest() - ); - request.measurementProtocolSecret ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateMeasurementProtocolSecretRequest', ['measurementProtocolSecret', 'name']); - request.measurementProtocolSecret.name = defaultValue1; - const expectedHeaderRequestParams = `measurement_protocol_secret.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret() - ); - client.innerApiCalls.updateMeasurementProtocolSecret = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateMeasurementProtocolSecret( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateMeasurementProtocolSecret with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateMeasurementProtocolSecretRequest() - ); - request.measurementProtocolSecret ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateMeasurementProtocolSecretRequest', ['measurementProtocolSecret', 'name']); - request.measurementProtocolSecret.name = defaultValue1; - const expectedHeaderRequestParams = `measurement_protocol_secret.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateMeasurementProtocolSecret = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateMeasurementProtocolSecret(request), expectedError); - const actualRequest = (client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateMeasurementProtocolSecret with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateMeasurementProtocolSecretRequest() - ); - request.measurementProtocolSecret ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateMeasurementProtocolSecretRequest', ['measurementProtocolSecret', 'name']); - request.measurementProtocolSecret.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateMeasurementProtocolSecret(request), expectedError); - }); - }); - - describe('acknowledgeUserDataCollection', () => { - it('invokes acknowledgeUserDataCollection without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.AcknowledgeUserDataCollectionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.AcknowledgeUserDataCollectionRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.AcknowledgeUserDataCollectionResponse() - ); - client.innerApiCalls.acknowledgeUserDataCollection = stubSimpleCall(expectedResponse); - const [response] = await client.acknowledgeUserDataCollection(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.acknowledgeUserDataCollection as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.acknowledgeUserDataCollection as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes acknowledgeUserDataCollection without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.AcknowledgeUserDataCollectionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.AcknowledgeUserDataCollectionRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.AcknowledgeUserDataCollectionResponse() - ); - client.innerApiCalls.acknowledgeUserDataCollection = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.acknowledgeUserDataCollection( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.acknowledgeUserDataCollection as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.acknowledgeUserDataCollection as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes acknowledgeUserDataCollection with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.AcknowledgeUserDataCollectionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.AcknowledgeUserDataCollectionRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.acknowledgeUserDataCollection = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.acknowledgeUserDataCollection(request), expectedError); - const actualRequest = (client.innerApiCalls.acknowledgeUserDataCollection as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.acknowledgeUserDataCollection as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes acknowledgeUserDataCollection with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.AcknowledgeUserDataCollectionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.AcknowledgeUserDataCollectionRequest', ['property']); - request.property = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.acknowledgeUserDataCollection(request), expectedError); - }); - }); - - describe('getSKAdNetworkConversionValueSchema', () => { - it('invokes getSKAdNetworkConversionValueSchema without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetSKAdNetworkConversionValueSchemaRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetSKAdNetworkConversionValueSchemaRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema() - ); - client.innerApiCalls.getSkAdNetworkConversionValueSchema = stubSimpleCall(expectedResponse); - const [response] = await client.getSKAdNetworkConversionValueSchema(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getSKAdNetworkConversionValueSchema without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetSKAdNetworkConversionValueSchemaRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetSKAdNetworkConversionValueSchemaRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema() - ); - client.innerApiCalls.getSkAdNetworkConversionValueSchema = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getSKAdNetworkConversionValueSchema( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getSKAdNetworkConversionValueSchema with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetSKAdNetworkConversionValueSchemaRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetSKAdNetworkConversionValueSchemaRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getSkAdNetworkConversionValueSchema = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getSKAdNetworkConversionValueSchema(request), expectedError); - const actualRequest = (client.innerApiCalls.getSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getSKAdNetworkConversionValueSchema with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetSKAdNetworkConversionValueSchemaRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetSKAdNetworkConversionValueSchemaRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getSKAdNetworkConversionValueSchema(request), expectedError); - }); - }); - - describe('createSKAdNetworkConversionValueSchema', () => { - it('invokes createSKAdNetworkConversionValueSchema without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema() - ); - client.innerApiCalls.createSkAdNetworkConversionValueSchema = stubSimpleCall(expectedResponse); - const [response] = await client.createSKAdNetworkConversionValueSchema(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createSKAdNetworkConversionValueSchema without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema() - ); - client.innerApiCalls.createSkAdNetworkConversionValueSchema = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createSKAdNetworkConversionValueSchema( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createSKAdNetworkConversionValueSchema with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createSkAdNetworkConversionValueSchema = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createSKAdNetworkConversionValueSchema(request), expectedError); - const actualRequest = (client.innerApiCalls.createSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createSKAdNetworkConversionValueSchema with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createSKAdNetworkConversionValueSchema(request), expectedError); - }); - }); - - describe('deleteSKAdNetworkConversionValueSchema', () => { - it('invokes deleteSKAdNetworkConversionValueSchema without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteSKAdNetworkConversionValueSchemaRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteSKAdNetworkConversionValueSchemaRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteSkAdNetworkConversionValueSchema = stubSimpleCall(expectedResponse); - const [response] = await client.deleteSKAdNetworkConversionValueSchema(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteSKAdNetworkConversionValueSchema without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteSKAdNetworkConversionValueSchemaRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteSKAdNetworkConversionValueSchemaRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteSkAdNetworkConversionValueSchema = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteSKAdNetworkConversionValueSchema( - 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.deleteSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteSKAdNetworkConversionValueSchema with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteSKAdNetworkConversionValueSchemaRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteSKAdNetworkConversionValueSchemaRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteSkAdNetworkConversionValueSchema = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteSKAdNetworkConversionValueSchema(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteSKAdNetworkConversionValueSchema with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteSKAdNetworkConversionValueSchemaRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteSKAdNetworkConversionValueSchemaRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteSKAdNetworkConversionValueSchema(request), expectedError); - }); - }); - - describe('updateSKAdNetworkConversionValueSchema', () => { - it('invokes updateSKAdNetworkConversionValueSchema without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateSKAdNetworkConversionValueSchemaRequest() - ); - request.skadnetworkConversionValueSchema ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateSKAdNetworkConversionValueSchemaRequest', ['skadnetworkConversionValueSchema', 'name']); - request.skadnetworkConversionValueSchema.name = defaultValue1; - const expectedHeaderRequestParams = `skadnetwork_conversion_value_schema.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema() - ); - client.innerApiCalls.updateSkAdNetworkConversionValueSchema = stubSimpleCall(expectedResponse); - const [response] = await client.updateSKAdNetworkConversionValueSchema(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateSKAdNetworkConversionValueSchema without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateSKAdNetworkConversionValueSchemaRequest() - ); - request.skadnetworkConversionValueSchema ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateSKAdNetworkConversionValueSchemaRequest', ['skadnetworkConversionValueSchema', 'name']); - request.skadnetworkConversionValueSchema.name = defaultValue1; - const expectedHeaderRequestParams = `skadnetwork_conversion_value_schema.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema() - ); - client.innerApiCalls.updateSkAdNetworkConversionValueSchema = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateSKAdNetworkConversionValueSchema( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateSKAdNetworkConversionValueSchema with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateSKAdNetworkConversionValueSchemaRequest() - ); - request.skadnetworkConversionValueSchema ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateSKAdNetworkConversionValueSchemaRequest', ['skadnetworkConversionValueSchema', 'name']); - request.skadnetworkConversionValueSchema.name = defaultValue1; - const expectedHeaderRequestParams = `skadnetwork_conversion_value_schema.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateSkAdNetworkConversionValueSchema = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateSKAdNetworkConversionValueSchema(request), expectedError); - const actualRequest = (client.innerApiCalls.updateSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSkAdNetworkConversionValueSchema as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateSKAdNetworkConversionValueSchema with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateSKAdNetworkConversionValueSchemaRequest() - ); - request.skadnetworkConversionValueSchema ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateSKAdNetworkConversionValueSchemaRequest', ['skadnetworkConversionValueSchema', 'name']); - request.skadnetworkConversionValueSchema.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateSKAdNetworkConversionValueSchema(request), expectedError); - }); - }); - - describe('getGoogleSignalsSettings', () => { - it('invokes getGoogleSignalsSettings without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetGoogleSignalsSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetGoogleSignalsSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GoogleSignalsSettings() - ); - client.innerApiCalls.getGoogleSignalsSettings = stubSimpleCall(expectedResponse); - const [response] = await client.getGoogleSignalsSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getGoogleSignalsSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGoogleSignalsSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getGoogleSignalsSettings without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetGoogleSignalsSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetGoogleSignalsSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GoogleSignalsSettings() - ); - client.innerApiCalls.getGoogleSignalsSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getGoogleSignalsSettings( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getGoogleSignalsSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGoogleSignalsSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getGoogleSignalsSettings with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetGoogleSignalsSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetGoogleSignalsSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getGoogleSignalsSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getGoogleSignalsSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.getGoogleSignalsSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getGoogleSignalsSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getGoogleSignalsSettings with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetGoogleSignalsSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetGoogleSignalsSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getGoogleSignalsSettings(request), expectedError); - }); - }); - - describe('updateGoogleSignalsSettings', () => { - it('invokes updateGoogleSignalsSettings without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateGoogleSignalsSettingsRequest() - ); - request.googleSignalsSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateGoogleSignalsSettingsRequest', ['googleSignalsSettings', 'name']); - request.googleSignalsSettings.name = defaultValue1; - const expectedHeaderRequestParams = `google_signals_settings.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GoogleSignalsSettings() - ); - client.innerApiCalls.updateGoogleSignalsSettings = stubSimpleCall(expectedResponse); - const [response] = await client.updateGoogleSignalsSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateGoogleSignalsSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGoogleSignalsSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateGoogleSignalsSettings without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateGoogleSignalsSettingsRequest() - ); - request.googleSignalsSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateGoogleSignalsSettingsRequest', ['googleSignalsSettings', 'name']); - request.googleSignalsSettings.name = defaultValue1; - const expectedHeaderRequestParams = `google_signals_settings.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GoogleSignalsSettings() - ); - client.innerApiCalls.updateGoogleSignalsSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateGoogleSignalsSettings( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateGoogleSignalsSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGoogleSignalsSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateGoogleSignalsSettings with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateGoogleSignalsSettingsRequest() - ); - request.googleSignalsSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateGoogleSignalsSettingsRequest', ['googleSignalsSettings', 'name']); - request.googleSignalsSettings.name = defaultValue1; - const expectedHeaderRequestParams = `google_signals_settings.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateGoogleSignalsSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateGoogleSignalsSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.updateGoogleSignalsSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGoogleSignalsSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateGoogleSignalsSettings with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateGoogleSignalsSettingsRequest() - ); - request.googleSignalsSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateGoogleSignalsSettingsRequest', ['googleSignalsSettings', 'name']); - request.googleSignalsSettings.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateGoogleSignalsSettings(request), expectedError); - }); - }); - - describe('createConversionEvent', () => { - it('invokes createConversionEvent without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateConversionEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ConversionEvent() - ); - client.innerApiCalls.createConversionEvent = stubSimpleCall(expectedResponse); - const [response] = await client.createConversionEvent(request); - assert(stub.calledOnce); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createConversionEvent without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateConversionEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ConversionEvent() - ); - client.innerApiCalls.createConversionEvent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createConversionEvent( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IConversionEvent|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert(stub.calledOnce); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createConversionEvent with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateConversionEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createConversionEvent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createConversionEvent(request), expectedError); - assert(stub.calledOnce); - const actualRequest = (client.innerApiCalls.createConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createConversionEvent with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateConversionEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createConversionEvent(request), expectedError); - assert(stub.calledOnce); - }); - }); - - describe('updateConversionEvent', () => { - it('invokes updateConversionEvent without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateConversionEventRequest() - ); - request.conversionEvent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateConversionEventRequest', ['conversionEvent', 'name']); - request.conversionEvent.name = defaultValue1; - const expectedHeaderRequestParams = `conversion_event.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ConversionEvent() - ); - client.innerApiCalls.updateConversionEvent = stubSimpleCall(expectedResponse); - const [response] = await client.updateConversionEvent(request); - assert(stub.calledOnce); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateConversionEvent without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateConversionEventRequest() - ); - request.conversionEvent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateConversionEventRequest', ['conversionEvent', 'name']); - request.conversionEvent.name = defaultValue1; - const expectedHeaderRequestParams = `conversion_event.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ConversionEvent() - ); - client.innerApiCalls.updateConversionEvent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateConversionEvent( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IConversionEvent|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert(stub.calledOnce); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateConversionEvent with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateConversionEventRequest() - ); - request.conversionEvent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateConversionEventRequest', ['conversionEvent', 'name']); - request.conversionEvent.name = defaultValue1; - const expectedHeaderRequestParams = `conversion_event.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateConversionEvent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateConversionEvent(request), expectedError); - assert(stub.calledOnce); - const actualRequest = (client.innerApiCalls.updateConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateConversionEvent with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateConversionEventRequest() - ); - request.conversionEvent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateConversionEventRequest', ['conversionEvent', 'name']); - request.conversionEvent.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateConversionEvent(request), expectedError); - assert(stub.calledOnce); - }); - }); - - describe('getConversionEvent', () => { - it('invokes getConversionEvent without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetConversionEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ConversionEvent() - ); - client.innerApiCalls.getConversionEvent = stubSimpleCall(expectedResponse); - const [response] = await client.getConversionEvent(request); - assert(stub.calledOnce); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getConversionEvent without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetConversionEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ConversionEvent() - ); - client.innerApiCalls.getConversionEvent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getConversionEvent( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IConversionEvent|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert(stub.calledOnce); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getConversionEvent with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetConversionEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getConversionEvent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getConversionEvent(request), expectedError); - assert(stub.calledOnce); - const actualRequest = (client.innerApiCalls.getConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getConversionEvent with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetConversionEventRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getConversionEvent(request), expectedError); - assert(stub.calledOnce); - }); - }); - - describe('deleteConversionEvent', () => { - it('invokes deleteConversionEvent without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteConversionEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteConversionEvent = stubSimpleCall(expectedResponse); - const [response] = await client.deleteConversionEvent(request); - assert(stub.calledOnce); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteConversionEvent without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteConversionEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteConversionEvent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteConversionEvent( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert(stub.calledOnce); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteConversionEvent with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteConversionEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteConversionEvent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteConversionEvent(request), expectedError); - assert(stub.calledOnce); - const actualRequest = (client.innerApiCalls.deleteConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteConversionEvent with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteConversionEventRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteConversionEvent(request), expectedError); - assert(stub.calledOnce); - }); - }); - - describe('createKeyEvent', () => { - it('invokes createKeyEvent without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateKeyEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.KeyEvent() - ); - client.innerApiCalls.createKeyEvent = stubSimpleCall(expectedResponse); - const [response] = await client.createKeyEvent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createKeyEvent without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateKeyEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.KeyEvent() - ); - client.innerApiCalls.createKeyEvent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createKeyEvent( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IKeyEvent|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createKeyEvent with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateKeyEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createKeyEvent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createKeyEvent(request), expectedError); - const actualRequest = (client.innerApiCalls.createKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createKeyEvent with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateKeyEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createKeyEvent(request), expectedError); - }); - }); - - describe('updateKeyEvent', () => { - it('invokes updateKeyEvent without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateKeyEventRequest() - ); - request.keyEvent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateKeyEventRequest', ['keyEvent', 'name']); - request.keyEvent.name = defaultValue1; - const expectedHeaderRequestParams = `key_event.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.KeyEvent() - ); - client.innerApiCalls.updateKeyEvent = stubSimpleCall(expectedResponse); - const [response] = await client.updateKeyEvent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateKeyEvent without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateKeyEventRequest() - ); - request.keyEvent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateKeyEventRequest', ['keyEvent', 'name']); - request.keyEvent.name = defaultValue1; - const expectedHeaderRequestParams = `key_event.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.KeyEvent() - ); - client.innerApiCalls.updateKeyEvent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateKeyEvent( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IKeyEvent|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateKeyEvent with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateKeyEventRequest() - ); - request.keyEvent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateKeyEventRequest', ['keyEvent', 'name']); - request.keyEvent.name = defaultValue1; - const expectedHeaderRequestParams = `key_event.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateKeyEvent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateKeyEvent(request), expectedError); - const actualRequest = (client.innerApiCalls.updateKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateKeyEvent with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateKeyEventRequest() - ); - request.keyEvent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateKeyEventRequest', ['keyEvent', 'name']); - request.keyEvent.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateKeyEvent(request), expectedError); - }); - }); - - describe('getKeyEvent', () => { - it('invokes getKeyEvent without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetKeyEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.KeyEvent() - ); - client.innerApiCalls.getKeyEvent = stubSimpleCall(expectedResponse); - const [response] = await client.getKeyEvent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getKeyEvent without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetKeyEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.KeyEvent() - ); - client.innerApiCalls.getKeyEvent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getKeyEvent( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IKeyEvent|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getKeyEvent with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetKeyEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getKeyEvent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getKeyEvent(request), expectedError); - const actualRequest = (client.innerApiCalls.getKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getKeyEvent with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetKeyEventRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getKeyEvent(request), expectedError); - }); - }); - - describe('deleteKeyEvent', () => { - it('invokes deleteKeyEvent without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteKeyEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteKeyEvent = stubSimpleCall(expectedResponse); - const [response] = await client.deleteKeyEvent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteKeyEvent without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteKeyEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteKeyEvent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteKeyEvent( - 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.deleteKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteKeyEvent with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteKeyEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteKeyEvent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteKeyEvent(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteKeyEvent with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteKeyEventRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteKeyEvent(request), expectedError); - }); - }); - - describe('getDisplayVideo360AdvertiserLink', () => { - it('invokes getDisplayVideo360AdvertiserLink without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink() - ); - client.innerApiCalls.getDisplayVideo360AdvertiserLink = stubSimpleCall(expectedResponse); - const [response] = await client.getDisplayVideo360AdvertiserLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDisplayVideo360AdvertiserLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink() - ); - client.innerApiCalls.getDisplayVideo360AdvertiserLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getDisplayVideo360AdvertiserLink( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDisplayVideo360AdvertiserLink with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getDisplayVideo360AdvertiserLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getDisplayVideo360AdvertiserLink(request), expectedError); - const actualRequest = (client.innerApiCalls.getDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDisplayVideo360AdvertiserLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getDisplayVideo360AdvertiserLink(request), expectedError); - }); - }); - - describe('createDisplayVideo360AdvertiserLink', () => { - it('invokes createDisplayVideo360AdvertiserLink without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink() - ); - client.innerApiCalls.createDisplayVideo360AdvertiserLink = stubSimpleCall(expectedResponse); - const [response] = await client.createDisplayVideo360AdvertiserLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createDisplayVideo360AdvertiserLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink() - ); - client.innerApiCalls.createDisplayVideo360AdvertiserLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createDisplayVideo360AdvertiserLink( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createDisplayVideo360AdvertiserLink with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createDisplayVideo360AdvertiserLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createDisplayVideo360AdvertiserLink(request), expectedError); - const actualRequest = (client.innerApiCalls.createDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createDisplayVideo360AdvertiserLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createDisplayVideo360AdvertiserLink(request), expectedError); - }); - }); - - describe('deleteDisplayVideo360AdvertiserLink', () => { - it('invokes deleteDisplayVideo360AdvertiserLink without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDisplayVideo360AdvertiserLink = stubSimpleCall(expectedResponse); - const [response] = await client.deleteDisplayVideo360AdvertiserLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteDisplayVideo360AdvertiserLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDisplayVideo360AdvertiserLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteDisplayVideo360AdvertiserLink( - 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.deleteDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteDisplayVideo360AdvertiserLink with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteDisplayVideo360AdvertiserLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteDisplayVideo360AdvertiserLink(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteDisplayVideo360AdvertiserLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteDisplayVideo360AdvertiserLink(request), expectedError); - }); - }); - - describe('updateDisplayVideo360AdvertiserLink', () => { - it('invokes updateDisplayVideo360AdvertiserLink without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateDisplayVideo360AdvertiserLinkRequest() - ); - request.displayVideo_360AdvertiserLink ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateDisplayVideo360AdvertiserLinkRequest', ['displayVideo_360AdvertiserLink', 'name']); - request.displayVideo_360AdvertiserLink.name = defaultValue1; - const expectedHeaderRequestParams = `display_video_360_advertiser_link.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink() - ); - client.innerApiCalls.updateDisplayVideo360AdvertiserLink = stubSimpleCall(expectedResponse); - const [response] = await client.updateDisplayVideo360AdvertiserLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateDisplayVideo360AdvertiserLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateDisplayVideo360AdvertiserLinkRequest() - ); - request.displayVideo_360AdvertiserLink ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateDisplayVideo360AdvertiserLinkRequest', ['displayVideo_360AdvertiserLink', 'name']); - request.displayVideo_360AdvertiserLink.name = defaultValue1; - const expectedHeaderRequestParams = `display_video_360_advertiser_link.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink() - ); - client.innerApiCalls.updateDisplayVideo360AdvertiserLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateDisplayVideo360AdvertiserLink( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateDisplayVideo360AdvertiserLink with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateDisplayVideo360AdvertiserLinkRequest() - ); - request.displayVideo_360AdvertiserLink ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateDisplayVideo360AdvertiserLinkRequest', ['displayVideo_360AdvertiserLink', 'name']); - request.displayVideo_360AdvertiserLink.name = defaultValue1; - const expectedHeaderRequestParams = `display_video_360_advertiser_link.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateDisplayVideo360AdvertiserLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateDisplayVideo360AdvertiserLink(request), expectedError); - const actualRequest = (client.innerApiCalls.updateDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDisplayVideo360AdvertiserLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateDisplayVideo360AdvertiserLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateDisplayVideo360AdvertiserLinkRequest() - ); - request.displayVideo_360AdvertiserLink ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateDisplayVideo360AdvertiserLinkRequest', ['displayVideo_360AdvertiserLink', 'name']); - request.displayVideo_360AdvertiserLink.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateDisplayVideo360AdvertiserLink(request), expectedError); - }); - }); - - describe('getDisplayVideo360AdvertiserLinkProposal', () => { - it('invokes getDisplayVideo360AdvertiserLinkProposal without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkProposalRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkProposalRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal() - ); - client.innerApiCalls.getDisplayVideo360AdvertiserLinkProposal = stubSimpleCall(expectedResponse); - const [response] = await client.getDisplayVideo360AdvertiserLinkProposal(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDisplayVideo360AdvertiserLinkProposal without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkProposalRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkProposalRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal() - ); - client.innerApiCalls.getDisplayVideo360AdvertiserLinkProposal = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getDisplayVideo360AdvertiserLinkProposal( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDisplayVideo360AdvertiserLinkProposal with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkProposalRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkProposalRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getDisplayVideo360AdvertiserLinkProposal = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getDisplayVideo360AdvertiserLinkProposal(request), expectedError); - const actualRequest = (client.innerApiCalls.getDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDisplayVideo360AdvertiserLinkProposal with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkProposalRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkProposalRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getDisplayVideo360AdvertiserLinkProposal(request), expectedError); - }); - }); - - describe('createDisplayVideo360AdvertiserLinkProposal', () => { - it('invokes createDisplayVideo360AdvertiserLinkProposal without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkProposalRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkProposalRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal() - ); - client.innerApiCalls.createDisplayVideo360AdvertiserLinkProposal = stubSimpleCall(expectedResponse); - const [response] = await client.createDisplayVideo360AdvertiserLinkProposal(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createDisplayVideo360AdvertiserLinkProposal without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkProposalRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkProposalRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal() - ); - client.innerApiCalls.createDisplayVideo360AdvertiserLinkProposal = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createDisplayVideo360AdvertiserLinkProposal( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createDisplayVideo360AdvertiserLinkProposal with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkProposalRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkProposalRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createDisplayVideo360AdvertiserLinkProposal = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createDisplayVideo360AdvertiserLinkProposal(request), expectedError); - const actualRequest = (client.innerApiCalls.createDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createDisplayVideo360AdvertiserLinkProposal with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkProposalRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkProposalRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createDisplayVideo360AdvertiserLinkProposal(request), expectedError); - }); - }); - - describe('deleteDisplayVideo360AdvertiserLinkProposal', () => { - it('invokes deleteDisplayVideo360AdvertiserLinkProposal without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkProposalRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkProposalRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDisplayVideo360AdvertiserLinkProposal = stubSimpleCall(expectedResponse); - const [response] = await client.deleteDisplayVideo360AdvertiserLinkProposal(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteDisplayVideo360AdvertiserLinkProposal without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkProposalRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkProposalRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDisplayVideo360AdvertiserLinkProposal = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteDisplayVideo360AdvertiserLinkProposal( - 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.deleteDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteDisplayVideo360AdvertiserLinkProposal with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkProposalRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkProposalRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteDisplayVideo360AdvertiserLinkProposal = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteDisplayVideo360AdvertiserLinkProposal(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteDisplayVideo360AdvertiserLinkProposal with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkProposalRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkProposalRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteDisplayVideo360AdvertiserLinkProposal(request), expectedError); - }); - }); - - describe('approveDisplayVideo360AdvertiserLinkProposal', () => { - it('invokes approveDisplayVideo360AdvertiserLinkProposal without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalResponse() - ); - client.innerApiCalls.approveDisplayVideo360AdvertiserLinkProposal = stubSimpleCall(expectedResponse); - const [response] = await client.approveDisplayVideo360AdvertiserLinkProposal(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.approveDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.approveDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes approveDisplayVideo360AdvertiserLinkProposal without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalResponse() - ); - client.innerApiCalls.approveDisplayVideo360AdvertiserLinkProposal = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.approveDisplayVideo360AdvertiserLinkProposal( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.approveDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.approveDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes approveDisplayVideo360AdvertiserLinkProposal with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.approveDisplayVideo360AdvertiserLinkProposal = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.approveDisplayVideo360AdvertiserLinkProposal(request), expectedError); - const actualRequest = (client.innerApiCalls.approveDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.approveDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes approveDisplayVideo360AdvertiserLinkProposal with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.approveDisplayVideo360AdvertiserLinkProposal(request), expectedError); - }); - }); - - describe('cancelDisplayVideo360AdvertiserLinkProposal', () => { - it('invokes cancelDisplayVideo360AdvertiserLinkProposal without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CancelDisplayVideo360AdvertiserLinkProposalRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CancelDisplayVideo360AdvertiserLinkProposalRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal() - ); - client.innerApiCalls.cancelDisplayVideo360AdvertiserLinkProposal = stubSimpleCall(expectedResponse); - const [response] = await client.cancelDisplayVideo360AdvertiserLinkProposal(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.cancelDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.cancelDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes cancelDisplayVideo360AdvertiserLinkProposal without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CancelDisplayVideo360AdvertiserLinkProposalRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CancelDisplayVideo360AdvertiserLinkProposalRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal() - ); - client.innerApiCalls.cancelDisplayVideo360AdvertiserLinkProposal = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.cancelDisplayVideo360AdvertiserLinkProposal( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.cancelDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.cancelDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes cancelDisplayVideo360AdvertiserLinkProposal with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CancelDisplayVideo360AdvertiserLinkProposalRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CancelDisplayVideo360AdvertiserLinkProposalRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.cancelDisplayVideo360AdvertiserLinkProposal = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.cancelDisplayVideo360AdvertiserLinkProposal(request), expectedError); - const actualRequest = (client.innerApiCalls.cancelDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.cancelDisplayVideo360AdvertiserLinkProposal as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes cancelDisplayVideo360AdvertiserLinkProposal with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CancelDisplayVideo360AdvertiserLinkProposalRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CancelDisplayVideo360AdvertiserLinkProposalRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.cancelDisplayVideo360AdvertiserLinkProposal(request), expectedError); - }); - }); - - describe('createCustomDimension', () => { - it('invokes createCustomDimension without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateCustomDimensionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CustomDimension() - ); - client.innerApiCalls.createCustomDimension = stubSimpleCall(expectedResponse); - const [response] = await client.createCustomDimension(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCustomDimension without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateCustomDimensionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CustomDimension() - ); - client.innerApiCalls.createCustomDimension = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createCustomDimension( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ICustomDimension|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCustomDimension with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateCustomDimensionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createCustomDimension = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createCustomDimension(request), expectedError); - const actualRequest = (client.innerApiCalls.createCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCustomDimension with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateCustomDimensionRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createCustomDimension(request), expectedError); - }); - }); - - describe('updateCustomDimension', () => { - it('invokes updateCustomDimension without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateCustomDimensionRequest() - ); - request.customDimension ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateCustomDimensionRequest', ['customDimension', 'name']); - request.customDimension.name = defaultValue1; - const expectedHeaderRequestParams = `custom_dimension.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CustomDimension() - ); - client.innerApiCalls.updateCustomDimension = stubSimpleCall(expectedResponse); - const [response] = await client.updateCustomDimension(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCustomDimension without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateCustomDimensionRequest() - ); - request.customDimension ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateCustomDimensionRequest', ['customDimension', 'name']); - request.customDimension.name = defaultValue1; - const expectedHeaderRequestParams = `custom_dimension.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CustomDimension() - ); - client.innerApiCalls.updateCustomDimension = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateCustomDimension( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ICustomDimension|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCustomDimension with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateCustomDimensionRequest() - ); - request.customDimension ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateCustomDimensionRequest', ['customDimension', 'name']); - request.customDimension.name = defaultValue1; - const expectedHeaderRequestParams = `custom_dimension.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateCustomDimension = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateCustomDimension(request), expectedError); - const actualRequest = (client.innerApiCalls.updateCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCustomDimension with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateCustomDimensionRequest() - ); - request.customDimension ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateCustomDimensionRequest', ['customDimension', 'name']); - request.customDimension.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateCustomDimension(request), expectedError); - }); - }); - - describe('archiveCustomDimension', () => { - it('invokes archiveCustomDimension without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ArchiveCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ArchiveCustomDimensionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.archiveCustomDimension = stubSimpleCall(expectedResponse); - const [response] = await client.archiveCustomDimension(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.archiveCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.archiveCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes archiveCustomDimension without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ArchiveCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ArchiveCustomDimensionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.archiveCustomDimension = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.archiveCustomDimension( - 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.archiveCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.archiveCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes archiveCustomDimension with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ArchiveCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ArchiveCustomDimensionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.archiveCustomDimension = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.archiveCustomDimension(request), expectedError); - const actualRequest = (client.innerApiCalls.archiveCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.archiveCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes archiveCustomDimension with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ArchiveCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ArchiveCustomDimensionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.archiveCustomDimension(request), expectedError); - }); - }); - - describe('getCustomDimension', () => { - it('invokes getCustomDimension without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetCustomDimensionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CustomDimension() - ); - client.innerApiCalls.getCustomDimension = stubSimpleCall(expectedResponse); - const [response] = await client.getCustomDimension(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCustomDimension without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetCustomDimensionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CustomDimension() - ); - client.innerApiCalls.getCustomDimension = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getCustomDimension( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ICustomDimension|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCustomDimension with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetCustomDimensionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getCustomDimension = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getCustomDimension(request), expectedError); - const actualRequest = (client.innerApiCalls.getCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCustomDimension with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetCustomDimensionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getCustomDimension(request), expectedError); - }); - }); - - describe('createCustomMetric', () => { - it('invokes createCustomMetric without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateCustomMetricRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CustomMetric() - ); - client.innerApiCalls.createCustomMetric = stubSimpleCall(expectedResponse); - const [response] = await client.createCustomMetric(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCustomMetric without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateCustomMetricRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CustomMetric() - ); - client.innerApiCalls.createCustomMetric = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createCustomMetric( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ICustomMetric|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCustomMetric with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateCustomMetricRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createCustomMetric = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createCustomMetric(request), expectedError); - const actualRequest = (client.innerApiCalls.createCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCustomMetric with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateCustomMetricRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createCustomMetric(request), expectedError); - }); - }); - - describe('updateCustomMetric', () => { - it('invokes updateCustomMetric without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateCustomMetricRequest() - ); - request.customMetric ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateCustomMetricRequest', ['customMetric', 'name']); - request.customMetric.name = defaultValue1; - const expectedHeaderRequestParams = `custom_metric.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CustomMetric() - ); - client.innerApiCalls.updateCustomMetric = stubSimpleCall(expectedResponse); - const [response] = await client.updateCustomMetric(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCustomMetric without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateCustomMetricRequest() - ); - request.customMetric ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateCustomMetricRequest', ['customMetric', 'name']); - request.customMetric.name = defaultValue1; - const expectedHeaderRequestParams = `custom_metric.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CustomMetric() - ); - client.innerApiCalls.updateCustomMetric = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateCustomMetric( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ICustomMetric|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCustomMetric with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateCustomMetricRequest() - ); - request.customMetric ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateCustomMetricRequest', ['customMetric', 'name']); - request.customMetric.name = defaultValue1; - const expectedHeaderRequestParams = `custom_metric.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateCustomMetric = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateCustomMetric(request), expectedError); - const actualRequest = (client.innerApiCalls.updateCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCustomMetric with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateCustomMetricRequest() - ); - request.customMetric ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateCustomMetricRequest', ['customMetric', 'name']); - request.customMetric.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateCustomMetric(request), expectedError); - }); - }); - - describe('archiveCustomMetric', () => { - it('invokes archiveCustomMetric without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ArchiveCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ArchiveCustomMetricRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.archiveCustomMetric = stubSimpleCall(expectedResponse); - const [response] = await client.archiveCustomMetric(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.archiveCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.archiveCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes archiveCustomMetric without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ArchiveCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ArchiveCustomMetricRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.archiveCustomMetric = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.archiveCustomMetric( - 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.archiveCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.archiveCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes archiveCustomMetric with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ArchiveCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ArchiveCustomMetricRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.archiveCustomMetric = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.archiveCustomMetric(request), expectedError); - const actualRequest = (client.innerApiCalls.archiveCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.archiveCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes archiveCustomMetric with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ArchiveCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ArchiveCustomMetricRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.archiveCustomMetric(request), expectedError); - }); - }); - - describe('getCustomMetric', () => { - it('invokes getCustomMetric without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetCustomMetricRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CustomMetric() - ); - client.innerApiCalls.getCustomMetric = stubSimpleCall(expectedResponse); - const [response] = await client.getCustomMetric(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCustomMetric without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetCustomMetricRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CustomMetric() - ); - client.innerApiCalls.getCustomMetric = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getCustomMetric( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ICustomMetric|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCustomMetric with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetCustomMetricRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getCustomMetric = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getCustomMetric(request), expectedError); - const actualRequest = (client.innerApiCalls.getCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCustomMetric with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetCustomMetricRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getCustomMetric(request), expectedError); - }); - }); - - describe('getDataRetentionSettings', () => { - it('invokes getDataRetentionSettings without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDataRetentionSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDataRetentionSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DataRetentionSettings() - ); - client.innerApiCalls.getDataRetentionSettings = stubSimpleCall(expectedResponse); - const [response] = await client.getDataRetentionSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDataRetentionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataRetentionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDataRetentionSettings without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDataRetentionSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDataRetentionSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DataRetentionSettings() - ); - client.innerApiCalls.getDataRetentionSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getDataRetentionSettings( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IDataRetentionSettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDataRetentionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataRetentionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDataRetentionSettings with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDataRetentionSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDataRetentionSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getDataRetentionSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getDataRetentionSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.getDataRetentionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataRetentionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDataRetentionSettings with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDataRetentionSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDataRetentionSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getDataRetentionSettings(request), expectedError); - }); - }); - - describe('updateDataRetentionSettings', () => { - it('invokes updateDataRetentionSettings without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateDataRetentionSettingsRequest() - ); - request.dataRetentionSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateDataRetentionSettingsRequest', ['dataRetentionSettings', 'name']); - request.dataRetentionSettings.name = defaultValue1; - const expectedHeaderRequestParams = `data_retention_settings.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DataRetentionSettings() - ); - client.innerApiCalls.updateDataRetentionSettings = stubSimpleCall(expectedResponse); - const [response] = await client.updateDataRetentionSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDataRetentionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDataRetentionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateDataRetentionSettings without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateDataRetentionSettingsRequest() - ); - request.dataRetentionSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateDataRetentionSettingsRequest', ['dataRetentionSettings', 'name']); - request.dataRetentionSettings.name = defaultValue1; - const expectedHeaderRequestParams = `data_retention_settings.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DataRetentionSettings() - ); - client.innerApiCalls.updateDataRetentionSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateDataRetentionSettings( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IDataRetentionSettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDataRetentionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDataRetentionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateDataRetentionSettings with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateDataRetentionSettingsRequest() - ); - request.dataRetentionSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateDataRetentionSettingsRequest', ['dataRetentionSettings', 'name']); - request.dataRetentionSettings.name = defaultValue1; - const expectedHeaderRequestParams = `data_retention_settings.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateDataRetentionSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateDataRetentionSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.updateDataRetentionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDataRetentionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateDataRetentionSettings with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateDataRetentionSettingsRequest() - ); - request.dataRetentionSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateDataRetentionSettingsRequest', ['dataRetentionSettings', 'name']); - request.dataRetentionSettings.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateDataRetentionSettings(request), expectedError); - }); - }); - - describe('createDataStream', () => { - it('invokes createDataStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateDataStreamRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DataStream() - ); - client.innerApiCalls.createDataStream = stubSimpleCall(expectedResponse); - const [response] = await client.createDataStream(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createDataStream without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateDataStreamRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DataStream() - ); - client.innerApiCalls.createDataStream = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createDataStream( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IDataStream|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createDataStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateDataStreamRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createDataStream = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createDataStream(request), expectedError); - const actualRequest = (client.innerApiCalls.createDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createDataStream with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateDataStreamRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createDataStream(request), expectedError); - }); - }); - - describe('deleteDataStream', () => { - it('invokes deleteDataStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteDataStreamRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDataStream = stubSimpleCall(expectedResponse); - const [response] = await client.deleteDataStream(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteDataStream without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteDataStreamRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDataStream = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteDataStream( - 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.deleteDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteDataStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteDataStreamRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteDataStream = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteDataStream(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteDataStream with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteDataStreamRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteDataStream(request), expectedError); - }); - }); - - describe('updateDataStream', () => { - it('invokes updateDataStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateDataStreamRequest() - ); - request.dataStream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateDataStreamRequest', ['dataStream', 'name']); - request.dataStream.name = defaultValue1; - const expectedHeaderRequestParams = `data_stream.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DataStream() - ); - client.innerApiCalls.updateDataStream = stubSimpleCall(expectedResponse); - const [response] = await client.updateDataStream(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateDataStream without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateDataStreamRequest() - ); - request.dataStream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateDataStreamRequest', ['dataStream', 'name']); - request.dataStream.name = defaultValue1; - const expectedHeaderRequestParams = `data_stream.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DataStream() - ); - client.innerApiCalls.updateDataStream = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateDataStream( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IDataStream|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateDataStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateDataStreamRequest() - ); - request.dataStream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateDataStreamRequest', ['dataStream', 'name']); - request.dataStream.name = defaultValue1; - const expectedHeaderRequestParams = `data_stream.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateDataStream = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateDataStream(request), expectedError); - const actualRequest = (client.innerApiCalls.updateDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateDataStream with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateDataStreamRequest() - ); - request.dataStream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateDataStreamRequest', ['dataStream', 'name']); - request.dataStream.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateDataStream(request), expectedError); - }); - }); - - describe('getDataStream', () => { - it('invokes getDataStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDataStreamRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DataStream() - ); - client.innerApiCalls.getDataStream = stubSimpleCall(expectedResponse); - const [response] = await client.getDataStream(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDataStream without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDataStreamRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DataStream() - ); - client.innerApiCalls.getDataStream = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getDataStream( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IDataStream|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDataStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDataStreamRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getDataStream = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getDataStream(request), expectedError); - const actualRequest = (client.innerApiCalls.getDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDataStream with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDataStreamRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getDataStream(request), expectedError); - }); - }); - - describe('getAudience', () => { - it('invokes getAudience without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetAudienceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetAudienceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.Audience() - ); - client.innerApiCalls.getAudience = stubSimpleCall(expectedResponse); - const [response] = await client.getAudience(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAudience as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAudience as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAudience without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetAudienceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetAudienceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.Audience() - ); - client.innerApiCalls.getAudience = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getAudience( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IAudience|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAudience as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAudience as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAudience with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetAudienceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetAudienceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getAudience = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getAudience(request), expectedError); - const actualRequest = (client.innerApiCalls.getAudience as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAudience as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAudience with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetAudienceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetAudienceRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getAudience(request), expectedError); - }); - }); - - describe('createAudience', () => { - it('invokes createAudience without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateAudienceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateAudienceRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.Audience() - ); - client.innerApiCalls.createAudience = stubSimpleCall(expectedResponse); - const [response] = await client.createAudience(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createAudience as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createAudience as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createAudience without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateAudienceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateAudienceRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.Audience() - ); - client.innerApiCalls.createAudience = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createAudience( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IAudience|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createAudience as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createAudience as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createAudience with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateAudienceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateAudienceRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createAudience = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createAudience(request), expectedError); - const actualRequest = (client.innerApiCalls.createAudience as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createAudience as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createAudience with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateAudienceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateAudienceRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createAudience(request), expectedError); - }); - }); - - describe('updateAudience', () => { - it('invokes updateAudience without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateAudienceRequest() - ); - request.audience ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateAudienceRequest', ['audience', 'name']); - request.audience.name = defaultValue1; - const expectedHeaderRequestParams = `audience.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.Audience() - ); - client.innerApiCalls.updateAudience = stubSimpleCall(expectedResponse); - const [response] = await client.updateAudience(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateAudience as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAudience as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateAudience without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateAudienceRequest() - ); - request.audience ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateAudienceRequest', ['audience', 'name']); - request.audience.name = defaultValue1; - const expectedHeaderRequestParams = `audience.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.Audience() - ); - client.innerApiCalls.updateAudience = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateAudience( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IAudience|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateAudience as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAudience as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateAudience with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateAudienceRequest() - ); - request.audience ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateAudienceRequest', ['audience', 'name']); - request.audience.name = defaultValue1; - const expectedHeaderRequestParams = `audience.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateAudience = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateAudience(request), expectedError); - const actualRequest = (client.innerApiCalls.updateAudience as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAudience as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateAudience with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateAudienceRequest() - ); - request.audience ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateAudienceRequest', ['audience', 'name']); - request.audience.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateAudience(request), expectedError); - }); - }); - - describe('archiveAudience', () => { - it('invokes archiveAudience without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ArchiveAudienceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ArchiveAudienceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.archiveAudience = stubSimpleCall(expectedResponse); - const [response] = await client.archiveAudience(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.archiveAudience as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.archiveAudience as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes archiveAudience without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ArchiveAudienceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ArchiveAudienceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.archiveAudience = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.archiveAudience( - 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.archiveAudience as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.archiveAudience as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes archiveAudience with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ArchiveAudienceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ArchiveAudienceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.archiveAudience = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.archiveAudience(request), expectedError); - const actualRequest = (client.innerApiCalls.archiveAudience as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.archiveAudience as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes archiveAudience with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ArchiveAudienceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ArchiveAudienceRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.archiveAudience(request), expectedError); - }); - }); - - describe('getSearchAds360Link', () => { - it('invokes getSearchAds360Link without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetSearchAds360LinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetSearchAds360LinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SearchAds360Link() - ); - client.innerApiCalls.getSearchAds360Link = stubSimpleCall(expectedResponse); - const [response] = await client.getSearchAds360Link(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSearchAds360Link as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSearchAds360Link as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getSearchAds360Link without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetSearchAds360LinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetSearchAds360LinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SearchAds360Link() - ); - client.innerApiCalls.getSearchAds360Link = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getSearchAds360Link( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ISearchAds360Link|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSearchAds360Link as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSearchAds360Link as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getSearchAds360Link with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetSearchAds360LinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetSearchAds360LinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getSearchAds360Link = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getSearchAds360Link(request), expectedError); - const actualRequest = (client.innerApiCalls.getSearchAds360Link as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSearchAds360Link as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getSearchAds360Link with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetSearchAds360LinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetSearchAds360LinkRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getSearchAds360Link(request), expectedError); - }); - }); - - describe('createSearchAds360Link', () => { - it('invokes createSearchAds360Link without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateSearchAds360LinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateSearchAds360LinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SearchAds360Link() - ); - client.innerApiCalls.createSearchAds360Link = stubSimpleCall(expectedResponse); - const [response] = await client.createSearchAds360Link(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createSearchAds360Link as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createSearchAds360Link as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createSearchAds360Link without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateSearchAds360LinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateSearchAds360LinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SearchAds360Link() - ); - client.innerApiCalls.createSearchAds360Link = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createSearchAds360Link( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ISearchAds360Link|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createSearchAds360Link as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createSearchAds360Link as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createSearchAds360Link with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateSearchAds360LinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateSearchAds360LinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createSearchAds360Link = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createSearchAds360Link(request), expectedError); - const actualRequest = (client.innerApiCalls.createSearchAds360Link as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createSearchAds360Link as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createSearchAds360Link with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateSearchAds360LinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateSearchAds360LinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createSearchAds360Link(request), expectedError); - }); - }); - - describe('deleteSearchAds360Link', () => { - it('invokes deleteSearchAds360Link without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteSearchAds360LinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteSearchAds360LinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteSearchAds360Link = stubSimpleCall(expectedResponse); - const [response] = await client.deleteSearchAds360Link(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteSearchAds360Link as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSearchAds360Link as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteSearchAds360Link without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteSearchAds360LinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteSearchAds360LinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteSearchAds360Link = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteSearchAds360Link( - 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.deleteSearchAds360Link as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSearchAds360Link as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteSearchAds360Link with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteSearchAds360LinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteSearchAds360LinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteSearchAds360Link = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteSearchAds360Link(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteSearchAds360Link as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSearchAds360Link as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteSearchAds360Link with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteSearchAds360LinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteSearchAds360LinkRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteSearchAds360Link(request), expectedError); - }); - }); - - describe('updateSearchAds360Link', () => { - it('invokes updateSearchAds360Link without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateSearchAds360LinkRequest() - ); - request.searchAds_360Link ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateSearchAds360LinkRequest', ['searchAds_360Link', 'name']); - request.searchAds_360Link.name = defaultValue1; - const expectedHeaderRequestParams = `search_ads_360_link.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SearchAds360Link() - ); - client.innerApiCalls.updateSearchAds360Link = stubSimpleCall(expectedResponse); - const [response] = await client.updateSearchAds360Link(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateSearchAds360Link as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSearchAds360Link as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateSearchAds360Link without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateSearchAds360LinkRequest() - ); - request.searchAds_360Link ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateSearchAds360LinkRequest', ['searchAds_360Link', 'name']); - request.searchAds_360Link.name = defaultValue1; - const expectedHeaderRequestParams = `search_ads_360_link.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SearchAds360Link() - ); - client.innerApiCalls.updateSearchAds360Link = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateSearchAds360Link( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ISearchAds360Link|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateSearchAds360Link as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSearchAds360Link as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateSearchAds360Link with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateSearchAds360LinkRequest() - ); - request.searchAds_360Link ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateSearchAds360LinkRequest', ['searchAds_360Link', 'name']); - request.searchAds_360Link.name = defaultValue1; - const expectedHeaderRequestParams = `search_ads_360_link.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateSearchAds360Link = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateSearchAds360Link(request), expectedError); - const actualRequest = (client.innerApiCalls.updateSearchAds360Link as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSearchAds360Link as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateSearchAds360Link with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateSearchAds360LinkRequest() - ); - request.searchAds_360Link ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateSearchAds360LinkRequest', ['searchAds_360Link', 'name']); - request.searchAds_360Link.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateSearchAds360Link(request), expectedError); - }); - }); - - describe('getAttributionSettings', () => { - it('invokes getAttributionSettings without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetAttributionSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetAttributionSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.AttributionSettings() - ); - client.innerApiCalls.getAttributionSettings = stubSimpleCall(expectedResponse); - const [response] = await client.getAttributionSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAttributionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAttributionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAttributionSettings without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetAttributionSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetAttributionSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.AttributionSettings() - ); - client.innerApiCalls.getAttributionSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getAttributionSettings( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IAttributionSettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAttributionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAttributionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAttributionSettings with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetAttributionSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetAttributionSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getAttributionSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getAttributionSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.getAttributionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAttributionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAttributionSettings with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetAttributionSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetAttributionSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getAttributionSettings(request), expectedError); - }); - }); - - describe('updateAttributionSettings', () => { - it('invokes updateAttributionSettings without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateAttributionSettingsRequest() - ); - request.attributionSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateAttributionSettingsRequest', ['attributionSettings', 'name']); - request.attributionSettings.name = defaultValue1; - const expectedHeaderRequestParams = `attribution_settings.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.AttributionSettings() - ); - client.innerApiCalls.updateAttributionSettings = stubSimpleCall(expectedResponse); - const [response] = await client.updateAttributionSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateAttributionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAttributionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateAttributionSettings without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateAttributionSettingsRequest() - ); - request.attributionSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateAttributionSettingsRequest', ['attributionSettings', 'name']); - request.attributionSettings.name = defaultValue1; - const expectedHeaderRequestParams = `attribution_settings.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.AttributionSettings() - ); - client.innerApiCalls.updateAttributionSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateAttributionSettings( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IAttributionSettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateAttributionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAttributionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateAttributionSettings with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateAttributionSettingsRequest() - ); - request.attributionSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateAttributionSettingsRequest', ['attributionSettings', 'name']); - request.attributionSettings.name = defaultValue1; - const expectedHeaderRequestParams = `attribution_settings.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateAttributionSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateAttributionSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.updateAttributionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAttributionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateAttributionSettings with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateAttributionSettingsRequest() - ); - request.attributionSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateAttributionSettingsRequest', ['attributionSettings', 'name']); - request.attributionSettings.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateAttributionSettings(request), expectedError); - }); - }); - - describe('runAccessReport', () => { - it('invokes runAccessReport without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.RunAccessReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.RunAccessReportRequest', ['entity']); - request.entity = defaultValue1; - const expectedHeaderRequestParams = `entity=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.RunAccessReportResponse() - ); - client.innerApiCalls.runAccessReport = stubSimpleCall(expectedResponse); - const [response] = await client.runAccessReport(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.runAccessReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runAccessReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes runAccessReport without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.RunAccessReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.RunAccessReportRequest', ['entity']); - request.entity = defaultValue1; - const expectedHeaderRequestParams = `entity=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.RunAccessReportResponse() - ); - client.innerApiCalls.runAccessReport = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.runAccessReport( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IRunAccessReportResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.runAccessReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runAccessReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes runAccessReport with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.RunAccessReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.RunAccessReportRequest', ['entity']); - request.entity = defaultValue1; - const expectedHeaderRequestParams = `entity=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.runAccessReport = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.runAccessReport(request), expectedError); - const actualRequest = (client.innerApiCalls.runAccessReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runAccessReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes runAccessReport with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.RunAccessReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.RunAccessReportRequest', ['entity']); - request.entity = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.runAccessReport(request), expectedError); - }); - }); - - describe('createAccessBinding', () => { - it('invokes createAccessBinding without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateAccessBindingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateAccessBindingRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.AccessBinding() - ); - client.innerApiCalls.createAccessBinding = stubSimpleCall(expectedResponse); - const [response] = await client.createAccessBinding(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createAccessBinding as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createAccessBinding as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createAccessBinding without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateAccessBindingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateAccessBindingRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.AccessBinding() - ); - client.innerApiCalls.createAccessBinding = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createAccessBinding( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IAccessBinding|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createAccessBinding as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createAccessBinding as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createAccessBinding with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateAccessBindingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateAccessBindingRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createAccessBinding = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createAccessBinding(request), expectedError); - const actualRequest = (client.innerApiCalls.createAccessBinding as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createAccessBinding as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createAccessBinding with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateAccessBindingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateAccessBindingRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createAccessBinding(request), expectedError); - }); - }); - - describe('getAccessBinding', () => { - it('invokes getAccessBinding without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetAccessBindingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetAccessBindingRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.AccessBinding() - ); - client.innerApiCalls.getAccessBinding = stubSimpleCall(expectedResponse); - const [response] = await client.getAccessBinding(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAccessBinding as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAccessBinding as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAccessBinding without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetAccessBindingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetAccessBindingRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.AccessBinding() - ); - client.innerApiCalls.getAccessBinding = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getAccessBinding( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IAccessBinding|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAccessBinding as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAccessBinding as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAccessBinding with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetAccessBindingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetAccessBindingRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getAccessBinding = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getAccessBinding(request), expectedError); - const actualRequest = (client.innerApiCalls.getAccessBinding as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAccessBinding as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAccessBinding with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetAccessBindingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetAccessBindingRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getAccessBinding(request), expectedError); - }); - }); - - describe('updateAccessBinding', () => { - it('invokes updateAccessBinding without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateAccessBindingRequest() - ); - request.accessBinding ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateAccessBindingRequest', ['accessBinding', 'name']); - request.accessBinding.name = defaultValue1; - const expectedHeaderRequestParams = `access_binding.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.AccessBinding() - ); - client.innerApiCalls.updateAccessBinding = stubSimpleCall(expectedResponse); - const [response] = await client.updateAccessBinding(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateAccessBinding as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAccessBinding as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateAccessBinding without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateAccessBindingRequest() - ); - request.accessBinding ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateAccessBindingRequest', ['accessBinding', 'name']); - request.accessBinding.name = defaultValue1; - const expectedHeaderRequestParams = `access_binding.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.AccessBinding() - ); - client.innerApiCalls.updateAccessBinding = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateAccessBinding( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IAccessBinding|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateAccessBinding as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAccessBinding as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateAccessBinding with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateAccessBindingRequest() - ); - request.accessBinding ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateAccessBindingRequest', ['accessBinding', 'name']); - request.accessBinding.name = defaultValue1; - const expectedHeaderRequestParams = `access_binding.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateAccessBinding = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateAccessBinding(request), expectedError); - const actualRequest = (client.innerApiCalls.updateAccessBinding as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAccessBinding as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateAccessBinding with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateAccessBindingRequest() - ); - request.accessBinding ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateAccessBindingRequest', ['accessBinding', 'name']); - request.accessBinding.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateAccessBinding(request), expectedError); - }); - }); - - describe('deleteAccessBinding', () => { - it('invokes deleteAccessBinding without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteAccessBindingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteAccessBindingRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteAccessBinding = stubSimpleCall(expectedResponse); - const [response] = await client.deleteAccessBinding(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteAccessBinding as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteAccessBinding as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteAccessBinding without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteAccessBindingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteAccessBindingRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteAccessBinding = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteAccessBinding( - 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.deleteAccessBinding as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteAccessBinding as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteAccessBinding with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteAccessBindingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteAccessBindingRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteAccessBinding = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteAccessBinding(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteAccessBinding as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteAccessBinding as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteAccessBinding with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteAccessBindingRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteAccessBindingRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteAccessBinding(request), expectedError); - }); - }); - - describe('batchCreateAccessBindings', () => { - it('invokes batchCreateAccessBindings without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BatchCreateAccessBindingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.BatchCreateAccessBindingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BatchCreateAccessBindingsResponse() - ); - client.innerApiCalls.batchCreateAccessBindings = stubSimpleCall(expectedResponse); - const [response] = await client.batchCreateAccessBindings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchCreateAccessBindings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchCreateAccessBindings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes batchCreateAccessBindings without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BatchCreateAccessBindingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.BatchCreateAccessBindingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BatchCreateAccessBindingsResponse() - ); - client.innerApiCalls.batchCreateAccessBindings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchCreateAccessBindings( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchCreateAccessBindings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchCreateAccessBindings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes batchCreateAccessBindings with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BatchCreateAccessBindingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.BatchCreateAccessBindingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchCreateAccessBindings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchCreateAccessBindings(request), expectedError); - const actualRequest = (client.innerApiCalls.batchCreateAccessBindings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchCreateAccessBindings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes batchCreateAccessBindings with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BatchCreateAccessBindingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.BatchCreateAccessBindingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchCreateAccessBindings(request), expectedError); - }); - }); - - describe('batchGetAccessBindings', () => { - it('invokes batchGetAccessBindings without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BatchGetAccessBindingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.BatchGetAccessBindingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BatchGetAccessBindingsResponse() - ); - client.innerApiCalls.batchGetAccessBindings = stubSimpleCall(expectedResponse); - const [response] = await client.batchGetAccessBindings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchGetAccessBindings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchGetAccessBindings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes batchGetAccessBindings without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BatchGetAccessBindingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.BatchGetAccessBindingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BatchGetAccessBindingsResponse() - ); - client.innerApiCalls.batchGetAccessBindings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchGetAccessBindings( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchGetAccessBindings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchGetAccessBindings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes batchGetAccessBindings with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BatchGetAccessBindingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.BatchGetAccessBindingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchGetAccessBindings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchGetAccessBindings(request), expectedError); - const actualRequest = (client.innerApiCalls.batchGetAccessBindings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchGetAccessBindings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes batchGetAccessBindings with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BatchGetAccessBindingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.BatchGetAccessBindingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchGetAccessBindings(request), expectedError); - }); - }); - - describe('batchUpdateAccessBindings', () => { - it('invokes batchUpdateAccessBindings without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BatchUpdateAccessBindingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.BatchUpdateAccessBindingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BatchUpdateAccessBindingsResponse() - ); - client.innerApiCalls.batchUpdateAccessBindings = stubSimpleCall(expectedResponse); - const [response] = await client.batchUpdateAccessBindings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchUpdateAccessBindings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchUpdateAccessBindings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes batchUpdateAccessBindings without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BatchUpdateAccessBindingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.BatchUpdateAccessBindingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BatchUpdateAccessBindingsResponse() - ); - client.innerApiCalls.batchUpdateAccessBindings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchUpdateAccessBindings( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchUpdateAccessBindings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchUpdateAccessBindings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes batchUpdateAccessBindings with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BatchUpdateAccessBindingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.BatchUpdateAccessBindingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchUpdateAccessBindings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchUpdateAccessBindings(request), expectedError); - const actualRequest = (client.innerApiCalls.batchUpdateAccessBindings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchUpdateAccessBindings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes batchUpdateAccessBindings with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BatchUpdateAccessBindingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.BatchUpdateAccessBindingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchUpdateAccessBindings(request), expectedError); - }); - }); - - describe('batchDeleteAccessBindings', () => { - it('invokes batchDeleteAccessBindings without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BatchDeleteAccessBindingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.BatchDeleteAccessBindingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.batchDeleteAccessBindings = stubSimpleCall(expectedResponse); - const [response] = await client.batchDeleteAccessBindings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchDeleteAccessBindings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchDeleteAccessBindings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes batchDeleteAccessBindings without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BatchDeleteAccessBindingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.BatchDeleteAccessBindingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.batchDeleteAccessBindings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchDeleteAccessBindings( - 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.batchDeleteAccessBindings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchDeleteAccessBindings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes batchDeleteAccessBindings with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BatchDeleteAccessBindingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.BatchDeleteAccessBindingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchDeleteAccessBindings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchDeleteAccessBindings(request), expectedError); - const actualRequest = (client.innerApiCalls.batchDeleteAccessBindings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchDeleteAccessBindings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes batchDeleteAccessBindings with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BatchDeleteAccessBindingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.BatchDeleteAccessBindingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchDeleteAccessBindings(request), expectedError); - }); - }); - - describe('getExpandedDataSet', () => { - it('invokes getExpandedDataSet without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetExpandedDataSetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetExpandedDataSetRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ExpandedDataSet() - ); - client.innerApiCalls.getExpandedDataSet = stubSimpleCall(expectedResponse); - const [response] = await client.getExpandedDataSet(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getExpandedDataSet as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getExpandedDataSet as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getExpandedDataSet without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetExpandedDataSetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetExpandedDataSetRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ExpandedDataSet() - ); - client.innerApiCalls.getExpandedDataSet = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getExpandedDataSet( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IExpandedDataSet|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getExpandedDataSet as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getExpandedDataSet as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getExpandedDataSet with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetExpandedDataSetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetExpandedDataSetRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getExpandedDataSet = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getExpandedDataSet(request), expectedError); - const actualRequest = (client.innerApiCalls.getExpandedDataSet as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getExpandedDataSet as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getExpandedDataSet with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetExpandedDataSetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetExpandedDataSetRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getExpandedDataSet(request), expectedError); - }); - }); - - describe('createExpandedDataSet', () => { - it('invokes createExpandedDataSet without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateExpandedDataSetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateExpandedDataSetRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ExpandedDataSet() - ); - client.innerApiCalls.createExpandedDataSet = stubSimpleCall(expectedResponse); - const [response] = await client.createExpandedDataSet(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createExpandedDataSet as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createExpandedDataSet as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createExpandedDataSet without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateExpandedDataSetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateExpandedDataSetRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ExpandedDataSet() - ); - client.innerApiCalls.createExpandedDataSet = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createExpandedDataSet( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IExpandedDataSet|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createExpandedDataSet as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createExpandedDataSet as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createExpandedDataSet with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateExpandedDataSetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateExpandedDataSetRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createExpandedDataSet = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createExpandedDataSet(request), expectedError); - const actualRequest = (client.innerApiCalls.createExpandedDataSet as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createExpandedDataSet as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createExpandedDataSet with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateExpandedDataSetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateExpandedDataSetRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createExpandedDataSet(request), expectedError); - }); - }); - - describe('updateExpandedDataSet', () => { - it('invokes updateExpandedDataSet without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateExpandedDataSetRequest() - ); - request.expandedDataSet ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateExpandedDataSetRequest', ['expandedDataSet', 'name']); - request.expandedDataSet.name = defaultValue1; - const expectedHeaderRequestParams = `expanded_data_set.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ExpandedDataSet() - ); - client.innerApiCalls.updateExpandedDataSet = stubSimpleCall(expectedResponse); - const [response] = await client.updateExpandedDataSet(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateExpandedDataSet as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateExpandedDataSet as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateExpandedDataSet without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateExpandedDataSetRequest() - ); - request.expandedDataSet ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateExpandedDataSetRequest', ['expandedDataSet', 'name']); - request.expandedDataSet.name = defaultValue1; - const expectedHeaderRequestParams = `expanded_data_set.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ExpandedDataSet() - ); - client.innerApiCalls.updateExpandedDataSet = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateExpandedDataSet( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IExpandedDataSet|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateExpandedDataSet as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateExpandedDataSet as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateExpandedDataSet with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateExpandedDataSetRequest() - ); - request.expandedDataSet ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateExpandedDataSetRequest', ['expandedDataSet', 'name']); - request.expandedDataSet.name = defaultValue1; - const expectedHeaderRequestParams = `expanded_data_set.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateExpandedDataSet = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateExpandedDataSet(request), expectedError); - const actualRequest = (client.innerApiCalls.updateExpandedDataSet as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateExpandedDataSet as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateExpandedDataSet with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateExpandedDataSetRequest() - ); - request.expandedDataSet ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateExpandedDataSetRequest', ['expandedDataSet', 'name']); - request.expandedDataSet.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateExpandedDataSet(request), expectedError); - }); - }); - - describe('deleteExpandedDataSet', () => { - it('invokes deleteExpandedDataSet without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteExpandedDataSetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteExpandedDataSetRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteExpandedDataSet = stubSimpleCall(expectedResponse); - const [response] = await client.deleteExpandedDataSet(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteExpandedDataSet as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteExpandedDataSet as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteExpandedDataSet without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteExpandedDataSetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteExpandedDataSetRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteExpandedDataSet = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteExpandedDataSet( - 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.deleteExpandedDataSet as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteExpandedDataSet as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteExpandedDataSet with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteExpandedDataSetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteExpandedDataSetRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteExpandedDataSet = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteExpandedDataSet(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteExpandedDataSet as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteExpandedDataSet as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteExpandedDataSet with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteExpandedDataSetRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteExpandedDataSetRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteExpandedDataSet(request), expectedError); - }); - }); - - describe('getChannelGroup', () => { - it('invokes getChannelGroup without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetChannelGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetChannelGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ChannelGroup() - ); - client.innerApiCalls.getChannelGroup = stubSimpleCall(expectedResponse); - const [response] = await client.getChannelGroup(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getChannelGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getChannelGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getChannelGroup without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetChannelGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetChannelGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ChannelGroup() - ); - client.innerApiCalls.getChannelGroup = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getChannelGroup( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IChannelGroup|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getChannelGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getChannelGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getChannelGroup with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetChannelGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetChannelGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getChannelGroup = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getChannelGroup(request), expectedError); - const actualRequest = (client.innerApiCalls.getChannelGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getChannelGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getChannelGroup with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetChannelGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetChannelGroupRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getChannelGroup(request), expectedError); - }); - }); - - describe('createChannelGroup', () => { - it('invokes createChannelGroup without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateChannelGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateChannelGroupRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ChannelGroup() - ); - client.innerApiCalls.createChannelGroup = stubSimpleCall(expectedResponse); - const [response] = await client.createChannelGroup(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createChannelGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createChannelGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createChannelGroup without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateChannelGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateChannelGroupRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ChannelGroup() - ); - client.innerApiCalls.createChannelGroup = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createChannelGroup( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IChannelGroup|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createChannelGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createChannelGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createChannelGroup with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateChannelGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateChannelGroupRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createChannelGroup = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createChannelGroup(request), expectedError); - const actualRequest = (client.innerApiCalls.createChannelGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createChannelGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createChannelGroup with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateChannelGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateChannelGroupRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createChannelGroup(request), expectedError); - }); - }); - - describe('updateChannelGroup', () => { - it('invokes updateChannelGroup without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateChannelGroupRequest() - ); - request.channelGroup ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateChannelGroupRequest', ['channelGroup', 'name']); - request.channelGroup.name = defaultValue1; - const expectedHeaderRequestParams = `channel_group.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ChannelGroup() - ); - client.innerApiCalls.updateChannelGroup = stubSimpleCall(expectedResponse); - const [response] = await client.updateChannelGroup(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateChannelGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateChannelGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateChannelGroup without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateChannelGroupRequest() - ); - request.channelGroup ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateChannelGroupRequest', ['channelGroup', 'name']); - request.channelGroup.name = defaultValue1; - const expectedHeaderRequestParams = `channel_group.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ChannelGroup() - ); - client.innerApiCalls.updateChannelGroup = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateChannelGroup( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IChannelGroup|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateChannelGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateChannelGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateChannelGroup with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateChannelGroupRequest() - ); - request.channelGroup ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateChannelGroupRequest', ['channelGroup', 'name']); - request.channelGroup.name = defaultValue1; - const expectedHeaderRequestParams = `channel_group.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateChannelGroup = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateChannelGroup(request), expectedError); - const actualRequest = (client.innerApiCalls.updateChannelGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateChannelGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateChannelGroup with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateChannelGroupRequest() - ); - request.channelGroup ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateChannelGroupRequest', ['channelGroup', 'name']); - request.channelGroup.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateChannelGroup(request), expectedError); - }); - }); - - describe('deleteChannelGroup', () => { - it('invokes deleteChannelGroup without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteChannelGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteChannelGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteChannelGroup = stubSimpleCall(expectedResponse); - const [response] = await client.deleteChannelGroup(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteChannelGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteChannelGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteChannelGroup without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteChannelGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteChannelGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteChannelGroup = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteChannelGroup( - 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.deleteChannelGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteChannelGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteChannelGroup with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteChannelGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteChannelGroupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteChannelGroup = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteChannelGroup(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteChannelGroup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteChannelGroup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteChannelGroup with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteChannelGroupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteChannelGroupRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteChannelGroup(request), expectedError); - }); - }); - - describe('createBigQueryLink', () => { - it('invokes createBigQueryLink without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateBigQueryLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateBigQueryLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BigQueryLink() - ); - client.innerApiCalls.createBigQueryLink = stubSimpleCall(expectedResponse); - const [response] = await client.createBigQueryLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createBigQueryLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBigQueryLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createBigQueryLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateBigQueryLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateBigQueryLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BigQueryLink() - ); - client.innerApiCalls.createBigQueryLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createBigQueryLink( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IBigQueryLink|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createBigQueryLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBigQueryLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createBigQueryLink with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateBigQueryLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateBigQueryLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createBigQueryLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createBigQueryLink(request), expectedError); - const actualRequest = (client.innerApiCalls.createBigQueryLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBigQueryLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createBigQueryLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateBigQueryLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateBigQueryLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createBigQueryLink(request), expectedError); - }); - }); - - describe('getBigQueryLink', () => { - it('invokes getBigQueryLink without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetBigQueryLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetBigQueryLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BigQueryLink() - ); - client.innerApiCalls.getBigQueryLink = stubSimpleCall(expectedResponse); - const [response] = await client.getBigQueryLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getBigQueryLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBigQueryLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getBigQueryLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetBigQueryLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetBigQueryLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BigQueryLink() - ); - client.innerApiCalls.getBigQueryLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getBigQueryLink( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IBigQueryLink|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getBigQueryLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBigQueryLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getBigQueryLink with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetBigQueryLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetBigQueryLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getBigQueryLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getBigQueryLink(request), expectedError); - const actualRequest = (client.innerApiCalls.getBigQueryLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBigQueryLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getBigQueryLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetBigQueryLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetBigQueryLinkRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getBigQueryLink(request), expectedError); - }); - }); - - describe('deleteBigQueryLink', () => { - it('invokes deleteBigQueryLink without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteBigQueryLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteBigQueryLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteBigQueryLink = stubSimpleCall(expectedResponse); - const [response] = await client.deleteBigQueryLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteBigQueryLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBigQueryLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteBigQueryLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteBigQueryLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteBigQueryLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteBigQueryLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteBigQueryLink( - 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.deleteBigQueryLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBigQueryLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteBigQueryLink with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteBigQueryLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteBigQueryLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteBigQueryLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteBigQueryLink(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteBigQueryLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBigQueryLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteBigQueryLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteBigQueryLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteBigQueryLinkRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteBigQueryLink(request), expectedError); - }); - }); - - describe('updateBigQueryLink', () => { - it('invokes updateBigQueryLink without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateBigQueryLinkRequest() - ); - request.bigqueryLink ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateBigQueryLinkRequest', ['bigqueryLink', 'name']); - request.bigqueryLink.name = defaultValue1; - const expectedHeaderRequestParams = `bigquery_link.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BigQueryLink() - ); - client.innerApiCalls.updateBigQueryLink = stubSimpleCall(expectedResponse); - const [response] = await client.updateBigQueryLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateBigQueryLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBigQueryLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateBigQueryLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateBigQueryLinkRequest() - ); - request.bigqueryLink ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateBigQueryLinkRequest', ['bigqueryLink', 'name']); - request.bigqueryLink.name = defaultValue1; - const expectedHeaderRequestParams = `bigquery_link.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.BigQueryLink() - ); - client.innerApiCalls.updateBigQueryLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateBigQueryLink( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IBigQueryLink|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateBigQueryLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBigQueryLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateBigQueryLink with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateBigQueryLinkRequest() - ); - request.bigqueryLink ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateBigQueryLinkRequest', ['bigqueryLink', 'name']); - request.bigqueryLink.name = defaultValue1; - const expectedHeaderRequestParams = `bigquery_link.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateBigQueryLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateBigQueryLink(request), expectedError); - const actualRequest = (client.innerApiCalls.updateBigQueryLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBigQueryLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateBigQueryLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateBigQueryLinkRequest() - ); - request.bigqueryLink ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateBigQueryLinkRequest', ['bigqueryLink', 'name']); - request.bigqueryLink.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateBigQueryLink(request), expectedError); - }); - }); - - describe('getEnhancedMeasurementSettings', () => { - it('invokes getEnhancedMeasurementSettings without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetEnhancedMeasurementSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetEnhancedMeasurementSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.EnhancedMeasurementSettings() - ); - client.innerApiCalls.getEnhancedMeasurementSettings = stubSimpleCall(expectedResponse); - const [response] = await client.getEnhancedMeasurementSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getEnhancedMeasurementSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getEnhancedMeasurementSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getEnhancedMeasurementSettings without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetEnhancedMeasurementSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetEnhancedMeasurementSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.EnhancedMeasurementSettings() - ); - client.innerApiCalls.getEnhancedMeasurementSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getEnhancedMeasurementSettings( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getEnhancedMeasurementSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getEnhancedMeasurementSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getEnhancedMeasurementSettings with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetEnhancedMeasurementSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetEnhancedMeasurementSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getEnhancedMeasurementSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getEnhancedMeasurementSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.getEnhancedMeasurementSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getEnhancedMeasurementSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getEnhancedMeasurementSettings with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetEnhancedMeasurementSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetEnhancedMeasurementSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getEnhancedMeasurementSettings(request), expectedError); - }); - }); - - describe('updateEnhancedMeasurementSettings', () => { - it('invokes updateEnhancedMeasurementSettings without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateEnhancedMeasurementSettingsRequest() - ); - request.enhancedMeasurementSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateEnhancedMeasurementSettingsRequest', ['enhancedMeasurementSettings', 'name']); - request.enhancedMeasurementSettings.name = defaultValue1; - const expectedHeaderRequestParams = `enhanced_measurement_settings.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.EnhancedMeasurementSettings() - ); - client.innerApiCalls.updateEnhancedMeasurementSettings = stubSimpleCall(expectedResponse); - const [response] = await client.updateEnhancedMeasurementSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateEnhancedMeasurementSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateEnhancedMeasurementSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateEnhancedMeasurementSettings without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateEnhancedMeasurementSettingsRequest() - ); - request.enhancedMeasurementSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateEnhancedMeasurementSettingsRequest', ['enhancedMeasurementSettings', 'name']); - request.enhancedMeasurementSettings.name = defaultValue1; - const expectedHeaderRequestParams = `enhanced_measurement_settings.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.EnhancedMeasurementSettings() - ); - client.innerApiCalls.updateEnhancedMeasurementSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateEnhancedMeasurementSettings( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateEnhancedMeasurementSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateEnhancedMeasurementSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateEnhancedMeasurementSettings with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateEnhancedMeasurementSettingsRequest() - ); - request.enhancedMeasurementSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateEnhancedMeasurementSettingsRequest', ['enhancedMeasurementSettings', 'name']); - request.enhancedMeasurementSettings.name = defaultValue1; - const expectedHeaderRequestParams = `enhanced_measurement_settings.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateEnhancedMeasurementSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateEnhancedMeasurementSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.updateEnhancedMeasurementSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateEnhancedMeasurementSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateEnhancedMeasurementSettings with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateEnhancedMeasurementSettingsRequest() - ); - request.enhancedMeasurementSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateEnhancedMeasurementSettingsRequest', ['enhancedMeasurementSettings', 'name']); - request.enhancedMeasurementSettings.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateEnhancedMeasurementSettings(request), expectedError); - }); - }); - - describe('getAdSenseLink', () => { - it('invokes getAdSenseLink without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetAdSenseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetAdSenseLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.AdSenseLink() - ); - client.innerApiCalls.getAdSenseLink = stubSimpleCall(expectedResponse); - const [response] = await client.getAdSenseLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAdSenseLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAdSenseLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAdSenseLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetAdSenseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetAdSenseLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.AdSenseLink() - ); - client.innerApiCalls.getAdSenseLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getAdSenseLink( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IAdSenseLink|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAdSenseLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAdSenseLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAdSenseLink with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetAdSenseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetAdSenseLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getAdSenseLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getAdSenseLink(request), expectedError); - const actualRequest = (client.innerApiCalls.getAdSenseLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAdSenseLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAdSenseLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetAdSenseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetAdSenseLinkRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getAdSenseLink(request), expectedError); - }); - }); - - describe('createAdSenseLink', () => { - it('invokes createAdSenseLink without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateAdSenseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateAdSenseLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.AdSenseLink() - ); - client.innerApiCalls.createAdSenseLink = stubSimpleCall(expectedResponse); - const [response] = await client.createAdSenseLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createAdSenseLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createAdSenseLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createAdSenseLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateAdSenseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateAdSenseLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.AdSenseLink() - ); - client.innerApiCalls.createAdSenseLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createAdSenseLink( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IAdSenseLink|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createAdSenseLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createAdSenseLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createAdSenseLink with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateAdSenseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateAdSenseLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createAdSenseLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createAdSenseLink(request), expectedError); - const actualRequest = (client.innerApiCalls.createAdSenseLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createAdSenseLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createAdSenseLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateAdSenseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateAdSenseLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createAdSenseLink(request), expectedError); - }); - }); - - describe('deleteAdSenseLink', () => { - it('invokes deleteAdSenseLink without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteAdSenseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteAdSenseLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteAdSenseLink = stubSimpleCall(expectedResponse); - const [response] = await client.deleteAdSenseLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteAdSenseLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteAdSenseLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteAdSenseLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteAdSenseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteAdSenseLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteAdSenseLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteAdSenseLink( - 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.deleteAdSenseLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteAdSenseLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteAdSenseLink with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteAdSenseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteAdSenseLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteAdSenseLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteAdSenseLink(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteAdSenseLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteAdSenseLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteAdSenseLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteAdSenseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteAdSenseLinkRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteAdSenseLink(request), expectedError); - }); - }); - - describe('getEventCreateRule', () => { - it('invokes getEventCreateRule without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetEventCreateRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetEventCreateRuleRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.EventCreateRule() - ); - client.innerApiCalls.getEventCreateRule = stubSimpleCall(expectedResponse); - const [response] = await client.getEventCreateRule(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getEventCreateRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getEventCreateRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getEventCreateRule without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetEventCreateRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetEventCreateRuleRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.EventCreateRule() - ); - client.innerApiCalls.getEventCreateRule = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getEventCreateRule( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IEventCreateRule|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getEventCreateRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getEventCreateRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getEventCreateRule with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetEventCreateRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetEventCreateRuleRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getEventCreateRule = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getEventCreateRule(request), expectedError); - const actualRequest = (client.innerApiCalls.getEventCreateRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getEventCreateRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getEventCreateRule with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetEventCreateRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetEventCreateRuleRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getEventCreateRule(request), expectedError); - }); - }); - - describe('createEventCreateRule', () => { - it('invokes createEventCreateRule without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateEventCreateRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateEventCreateRuleRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.EventCreateRule() - ); - client.innerApiCalls.createEventCreateRule = stubSimpleCall(expectedResponse); - const [response] = await client.createEventCreateRule(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createEventCreateRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createEventCreateRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createEventCreateRule without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateEventCreateRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateEventCreateRuleRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.EventCreateRule() - ); - client.innerApiCalls.createEventCreateRule = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createEventCreateRule( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IEventCreateRule|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createEventCreateRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createEventCreateRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createEventCreateRule with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateEventCreateRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateEventCreateRuleRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createEventCreateRule = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createEventCreateRule(request), expectedError); - const actualRequest = (client.innerApiCalls.createEventCreateRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createEventCreateRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createEventCreateRule with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateEventCreateRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateEventCreateRuleRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createEventCreateRule(request), expectedError); - }); - }); - - describe('updateEventCreateRule', () => { - it('invokes updateEventCreateRule without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateEventCreateRuleRequest() - ); - request.eventCreateRule ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateEventCreateRuleRequest', ['eventCreateRule', 'name']); - request.eventCreateRule.name = defaultValue1; - const expectedHeaderRequestParams = `event_create_rule.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.EventCreateRule() - ); - client.innerApiCalls.updateEventCreateRule = stubSimpleCall(expectedResponse); - const [response] = await client.updateEventCreateRule(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateEventCreateRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateEventCreateRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateEventCreateRule without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateEventCreateRuleRequest() - ); - request.eventCreateRule ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateEventCreateRuleRequest', ['eventCreateRule', 'name']); - request.eventCreateRule.name = defaultValue1; - const expectedHeaderRequestParams = `event_create_rule.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.EventCreateRule() - ); - client.innerApiCalls.updateEventCreateRule = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateEventCreateRule( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IEventCreateRule|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateEventCreateRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateEventCreateRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateEventCreateRule with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateEventCreateRuleRequest() - ); - request.eventCreateRule ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateEventCreateRuleRequest', ['eventCreateRule', 'name']); - request.eventCreateRule.name = defaultValue1; - const expectedHeaderRequestParams = `event_create_rule.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateEventCreateRule = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateEventCreateRule(request), expectedError); - const actualRequest = (client.innerApiCalls.updateEventCreateRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateEventCreateRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateEventCreateRule with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateEventCreateRuleRequest() - ); - request.eventCreateRule ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateEventCreateRuleRequest', ['eventCreateRule', 'name']); - request.eventCreateRule.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateEventCreateRule(request), expectedError); - }); - }); - - describe('deleteEventCreateRule', () => { - it('invokes deleteEventCreateRule without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteEventCreateRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteEventCreateRuleRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteEventCreateRule = stubSimpleCall(expectedResponse); - const [response] = await client.deleteEventCreateRule(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteEventCreateRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteEventCreateRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteEventCreateRule without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteEventCreateRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteEventCreateRuleRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteEventCreateRule = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteEventCreateRule( - 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.deleteEventCreateRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteEventCreateRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteEventCreateRule with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteEventCreateRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteEventCreateRuleRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteEventCreateRule = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteEventCreateRule(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteEventCreateRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteEventCreateRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteEventCreateRule with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteEventCreateRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteEventCreateRuleRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteEventCreateRule(request), expectedError); - }); - }); - - describe('getEventEditRule', () => { - it('invokes getEventEditRule without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetEventEditRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetEventEditRuleRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.EventEditRule() - ); - client.innerApiCalls.getEventEditRule = stubSimpleCall(expectedResponse); - const [response] = await client.getEventEditRule(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getEventEditRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getEventEditRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getEventEditRule without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetEventEditRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetEventEditRuleRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.EventEditRule() - ); - client.innerApiCalls.getEventEditRule = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getEventEditRule( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IEventEditRule|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getEventEditRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getEventEditRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getEventEditRule with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetEventEditRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetEventEditRuleRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getEventEditRule = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getEventEditRule(request), expectedError); - const actualRequest = (client.innerApiCalls.getEventEditRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getEventEditRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getEventEditRule with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetEventEditRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetEventEditRuleRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getEventEditRule(request), expectedError); - }); - }); - - describe('createEventEditRule', () => { - it('invokes createEventEditRule without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateEventEditRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateEventEditRuleRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.EventEditRule() - ); - client.innerApiCalls.createEventEditRule = stubSimpleCall(expectedResponse); - const [response] = await client.createEventEditRule(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createEventEditRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createEventEditRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createEventEditRule without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateEventEditRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateEventEditRuleRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.EventEditRule() - ); - client.innerApiCalls.createEventEditRule = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createEventEditRule( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IEventEditRule|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createEventEditRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createEventEditRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createEventEditRule with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateEventEditRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateEventEditRuleRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createEventEditRule = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createEventEditRule(request), expectedError); - const actualRequest = (client.innerApiCalls.createEventEditRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createEventEditRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createEventEditRule with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateEventEditRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateEventEditRuleRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createEventEditRule(request), expectedError); - }); - }); - - describe('updateEventEditRule', () => { - it('invokes updateEventEditRule without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateEventEditRuleRequest() - ); - request.eventEditRule ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateEventEditRuleRequest', ['eventEditRule', 'name']); - request.eventEditRule.name = defaultValue1; - const expectedHeaderRequestParams = `event_edit_rule.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.EventEditRule() - ); - client.innerApiCalls.updateEventEditRule = stubSimpleCall(expectedResponse); - const [response] = await client.updateEventEditRule(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateEventEditRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateEventEditRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateEventEditRule without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateEventEditRuleRequest() - ); - request.eventEditRule ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateEventEditRuleRequest', ['eventEditRule', 'name']); - request.eventEditRule.name = defaultValue1; - const expectedHeaderRequestParams = `event_edit_rule.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.EventEditRule() - ); - client.innerApiCalls.updateEventEditRule = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateEventEditRule( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IEventEditRule|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateEventEditRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateEventEditRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateEventEditRule with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateEventEditRuleRequest() - ); - request.eventEditRule ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateEventEditRuleRequest', ['eventEditRule', 'name']); - request.eventEditRule.name = defaultValue1; - const expectedHeaderRequestParams = `event_edit_rule.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateEventEditRule = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateEventEditRule(request), expectedError); - const actualRequest = (client.innerApiCalls.updateEventEditRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateEventEditRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateEventEditRule with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateEventEditRuleRequest() - ); - request.eventEditRule ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateEventEditRuleRequest', ['eventEditRule', 'name']); - request.eventEditRule.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateEventEditRule(request), expectedError); - }); - }); - - describe('deleteEventEditRule', () => { - it('invokes deleteEventEditRule without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteEventEditRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteEventEditRuleRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteEventEditRule = stubSimpleCall(expectedResponse); - const [response] = await client.deleteEventEditRule(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteEventEditRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteEventEditRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteEventEditRule without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteEventEditRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteEventEditRuleRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteEventEditRule = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteEventEditRule( - 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.deleteEventEditRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteEventEditRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteEventEditRule with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteEventEditRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteEventEditRuleRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteEventEditRule = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteEventEditRule(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteEventEditRule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteEventEditRule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteEventEditRule with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteEventEditRuleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteEventEditRuleRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteEventEditRule(request), expectedError); - }); - }); - - describe('reorderEventEditRules', () => { - it('invokes reorderEventEditRules without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ReorderEventEditRulesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ReorderEventEditRulesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.reorderEventEditRules = stubSimpleCall(expectedResponse); - const [response] = await client.reorderEventEditRules(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.reorderEventEditRules as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.reorderEventEditRules as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes reorderEventEditRules without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ReorderEventEditRulesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ReorderEventEditRulesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.reorderEventEditRules = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.reorderEventEditRules( - 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.reorderEventEditRules as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.reorderEventEditRules as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes reorderEventEditRules with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ReorderEventEditRulesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ReorderEventEditRulesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.reorderEventEditRules = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.reorderEventEditRules(request), expectedError); - const actualRequest = (client.innerApiCalls.reorderEventEditRules as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.reorderEventEditRules as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes reorderEventEditRules with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ReorderEventEditRulesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ReorderEventEditRulesRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.reorderEventEditRules(request), expectedError); - }); - }); - - describe('updateDataRedactionSettings', () => { - it('invokes updateDataRedactionSettings without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateDataRedactionSettingsRequest() - ); - request.dataRedactionSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateDataRedactionSettingsRequest', ['dataRedactionSettings', 'name']); - request.dataRedactionSettings.name = defaultValue1; - const expectedHeaderRequestParams = `data_redaction_settings.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DataRedactionSettings() - ); - client.innerApiCalls.updateDataRedactionSettings = stubSimpleCall(expectedResponse); - const [response] = await client.updateDataRedactionSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDataRedactionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDataRedactionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateDataRedactionSettings without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateDataRedactionSettingsRequest() - ); - request.dataRedactionSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateDataRedactionSettingsRequest', ['dataRedactionSettings', 'name']); - request.dataRedactionSettings.name = defaultValue1; - const expectedHeaderRequestParams = `data_redaction_settings.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DataRedactionSettings() - ); - client.innerApiCalls.updateDataRedactionSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateDataRedactionSettings( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IDataRedactionSettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDataRedactionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDataRedactionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateDataRedactionSettings with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateDataRedactionSettingsRequest() - ); - request.dataRedactionSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateDataRedactionSettingsRequest', ['dataRedactionSettings', 'name']); - request.dataRedactionSettings.name = defaultValue1; - const expectedHeaderRequestParams = `data_redaction_settings.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateDataRedactionSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateDataRedactionSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.updateDataRedactionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDataRedactionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateDataRedactionSettings with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateDataRedactionSettingsRequest() - ); - request.dataRedactionSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateDataRedactionSettingsRequest', ['dataRedactionSettings', 'name']); - request.dataRedactionSettings.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateDataRedactionSettings(request), expectedError); - }); - }); - - describe('getDataRedactionSettings', () => { - it('invokes getDataRedactionSettings without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDataRedactionSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDataRedactionSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DataRedactionSettings() - ); - client.innerApiCalls.getDataRedactionSettings = stubSimpleCall(expectedResponse); - const [response] = await client.getDataRedactionSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDataRedactionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataRedactionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDataRedactionSettings without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDataRedactionSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDataRedactionSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DataRedactionSettings() - ); - client.innerApiCalls.getDataRedactionSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getDataRedactionSettings( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IDataRedactionSettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDataRedactionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataRedactionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDataRedactionSettings with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDataRedactionSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDataRedactionSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getDataRedactionSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getDataRedactionSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.getDataRedactionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataRedactionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDataRedactionSettings with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetDataRedactionSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetDataRedactionSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getDataRedactionSettings(request), expectedError); - }); - }); - - describe('getCalculatedMetric', () => { - it('invokes getCalculatedMetric without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetCalculatedMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetCalculatedMetricRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CalculatedMetric() - ); - client.innerApiCalls.getCalculatedMetric = stubSimpleCall(expectedResponse); - const [response] = await client.getCalculatedMetric(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCalculatedMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCalculatedMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCalculatedMetric without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetCalculatedMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetCalculatedMetricRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CalculatedMetric() - ); - client.innerApiCalls.getCalculatedMetric = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getCalculatedMetric( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ICalculatedMetric|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCalculatedMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCalculatedMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCalculatedMetric with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetCalculatedMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetCalculatedMetricRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getCalculatedMetric = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getCalculatedMetric(request), expectedError); - const actualRequest = (client.innerApiCalls.getCalculatedMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCalculatedMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCalculatedMetric with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetCalculatedMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetCalculatedMetricRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getCalculatedMetric(request), expectedError); - }); - }); - - describe('createCalculatedMetric', () => { - it('invokes createCalculatedMetric without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateCalculatedMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateCalculatedMetricRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CalculatedMetric() - ); - client.innerApiCalls.createCalculatedMetric = stubSimpleCall(expectedResponse); - const [response] = await client.createCalculatedMetric(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createCalculatedMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCalculatedMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCalculatedMetric without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateCalculatedMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateCalculatedMetricRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CalculatedMetric() - ); - client.innerApiCalls.createCalculatedMetric = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createCalculatedMetric( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ICalculatedMetric|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createCalculatedMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCalculatedMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCalculatedMetric with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateCalculatedMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateCalculatedMetricRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createCalculatedMetric = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createCalculatedMetric(request), expectedError); - const actualRequest = (client.innerApiCalls.createCalculatedMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCalculatedMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCalculatedMetric with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateCalculatedMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateCalculatedMetricRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createCalculatedMetric(request), expectedError); - }); - }); - - describe('updateCalculatedMetric', () => { - it('invokes updateCalculatedMetric without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateCalculatedMetricRequest() - ); - request.calculatedMetric ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateCalculatedMetricRequest', ['calculatedMetric', 'name']); - request.calculatedMetric.name = defaultValue1; - const expectedHeaderRequestParams = `calculated_metric.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CalculatedMetric() - ); - client.innerApiCalls.updateCalculatedMetric = stubSimpleCall(expectedResponse); - const [response] = await client.updateCalculatedMetric(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCalculatedMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCalculatedMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCalculatedMetric without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateCalculatedMetricRequest() - ); - request.calculatedMetric ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateCalculatedMetricRequest', ['calculatedMetric', 'name']); - request.calculatedMetric.name = defaultValue1; - const expectedHeaderRequestParams = `calculated_metric.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CalculatedMetric() - ); - client.innerApiCalls.updateCalculatedMetric = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateCalculatedMetric( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ICalculatedMetric|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCalculatedMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCalculatedMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCalculatedMetric with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateCalculatedMetricRequest() - ); - request.calculatedMetric ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateCalculatedMetricRequest', ['calculatedMetric', 'name']); - request.calculatedMetric.name = defaultValue1; - const expectedHeaderRequestParams = `calculated_metric.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateCalculatedMetric = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateCalculatedMetric(request), expectedError); - const actualRequest = (client.innerApiCalls.updateCalculatedMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCalculatedMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCalculatedMetric with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateCalculatedMetricRequest() - ); - request.calculatedMetric ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateCalculatedMetricRequest', ['calculatedMetric', 'name']); - request.calculatedMetric.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateCalculatedMetric(request), expectedError); - }); - }); - - describe('deleteCalculatedMetric', () => { - it('invokes deleteCalculatedMetric without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteCalculatedMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteCalculatedMetricRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteCalculatedMetric = stubSimpleCall(expectedResponse); - const [response] = await client.deleteCalculatedMetric(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteCalculatedMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteCalculatedMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteCalculatedMetric without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteCalculatedMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteCalculatedMetricRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteCalculatedMetric = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteCalculatedMetric( - 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.deleteCalculatedMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteCalculatedMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteCalculatedMetric with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteCalculatedMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteCalculatedMetricRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteCalculatedMetric = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteCalculatedMetric(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteCalculatedMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteCalculatedMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteCalculatedMetric with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteCalculatedMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteCalculatedMetricRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteCalculatedMetric(request), expectedError); - }); - }); - - describe('createRollupProperty', () => { - it('invokes createRollupProperty without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateRollupPropertyRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateRollupPropertyResponse() - ); - client.innerApiCalls.createRollupProperty = stubSimpleCall(expectedResponse); - const [response] = await client.createRollupProperty(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes createRollupProperty without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateRollupPropertyRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateRollupPropertyResponse() - ); - client.innerApiCalls.createRollupProperty = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createRollupProperty( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ICreateRollupPropertyResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes createRollupProperty with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateRollupPropertyRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createRollupProperty = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createRollupProperty(request), expectedError); - }); - - it('invokes createRollupProperty with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateRollupPropertyRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createRollupProperty(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 analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'analyticsadmin.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 analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient( + { universeDomain: 'configured.example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'analyticsadmin.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 analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', + }); + }); + }); + + it('has port', () => { + const port = + analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); + + it('should create a client with no option', () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + fallback: true, + }); + assert(client); + }); + + it('has initialize method and supports deferred initialization', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.analyticsAdminServiceStub, undefined); + await client.initialize(); + assert(client.analyticsAdminServiceStub); + }); + + it('has close method for the initialized client', (done) => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.analyticsAdminServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; + }); + }); + + it('has close method for the non-initialized client', (done) => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.analyticsAdminServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('getRollupPropertySourceLink', () => { - it('invokes getRollupPropertySourceLink without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetRollupPropertySourceLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetRollupPropertySourceLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink() - ); - client.innerApiCalls.getRollupPropertySourceLink = stubSimpleCall(expectedResponse); - const [response] = await client.getRollupPropertySourceLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getRollupPropertySourceLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRollupPropertySourceLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getRollupPropertySourceLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetRollupPropertySourceLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetRollupPropertySourceLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink() - ); - client.innerApiCalls.getRollupPropertySourceLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getRollupPropertySourceLink( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getRollupPropertySourceLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRollupPropertySourceLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getRollupPropertySourceLink with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetRollupPropertySourceLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetRollupPropertySourceLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getRollupPropertySourceLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getRollupPropertySourceLink(request), expectedError); - const actualRequest = (client.innerApiCalls.getRollupPropertySourceLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRollupPropertySourceLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getRollupPropertySourceLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetRollupPropertySourceLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetRollupPropertySourceLinkRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getRollupPropertySourceLink(request), expectedError); - }); - }); - - describe('createRollupPropertySourceLink', () => { - it('invokes createRollupPropertySourceLink without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateRollupPropertySourceLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateRollupPropertySourceLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink() - ); - client.innerApiCalls.createRollupPropertySourceLink = stubSimpleCall(expectedResponse); - const [response] = await client.createRollupPropertySourceLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createRollupPropertySourceLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createRollupPropertySourceLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createRollupPropertySourceLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateRollupPropertySourceLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateRollupPropertySourceLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink() - ); - client.innerApiCalls.createRollupPropertySourceLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createRollupPropertySourceLink( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createRollupPropertySourceLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createRollupPropertySourceLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createRollupPropertySourceLink with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateRollupPropertySourceLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateRollupPropertySourceLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createRollupPropertySourceLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createRollupPropertySourceLink(request), expectedError); - const actualRequest = (client.innerApiCalls.createRollupPropertySourceLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createRollupPropertySourceLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createRollupPropertySourceLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateRollupPropertySourceLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateRollupPropertySourceLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createRollupPropertySourceLink(request), expectedError); - }); - }); - - describe('deleteRollupPropertySourceLink', () => { - it('invokes deleteRollupPropertySourceLink without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteRollupPropertySourceLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteRollupPropertySourceLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteRollupPropertySourceLink = stubSimpleCall(expectedResponse); - const [response] = await client.deleteRollupPropertySourceLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteRollupPropertySourceLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteRollupPropertySourceLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteRollupPropertySourceLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteRollupPropertySourceLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteRollupPropertySourceLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteRollupPropertySourceLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteRollupPropertySourceLink( - 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.deleteRollupPropertySourceLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteRollupPropertySourceLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteRollupPropertySourceLink with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteRollupPropertySourceLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteRollupPropertySourceLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteRollupPropertySourceLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteRollupPropertySourceLink(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteRollupPropertySourceLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteRollupPropertySourceLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteRollupPropertySourceLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteRollupPropertySourceLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteRollupPropertySourceLinkRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteRollupPropertySourceLink(request), expectedError); - }); - }); - - describe('provisionSubproperty', () => { - it('invokes provisionSubproperty without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ProvisionSubpropertyRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ProvisionSubpropertyResponse() - ); - client.innerApiCalls.provisionSubproperty = stubSimpleCall(expectedResponse); - const [response] = await client.provisionSubproperty(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes provisionSubproperty without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ProvisionSubpropertyRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ProvisionSubpropertyResponse() - ); - client.innerApiCalls.provisionSubproperty = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.provisionSubproperty( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IProvisionSubpropertyResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes provisionSubproperty with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ProvisionSubpropertyRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.provisionSubproperty = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.provisionSubproperty(request), expectedError); - }); - - it('invokes provisionSubproperty with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ProvisionSubpropertyRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.provisionSubproperty(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + 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 analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + 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('getAccount', () => { + it('invokes getAccount without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetAccountRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Account(), + ); + client.innerApiCalls.getAccount = stubSimpleCall(expectedResponse); + const [response] = await client.getAccount(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getAccount without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetAccountRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Account(), + ); + client.innerApiCalls.getAccount = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getAccount( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IAccount | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getAccount with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetAccountRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getAccount = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getAccount(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getAccount with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetAccountRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getAccount(request), expectedError); + }); + }); + + describe('deleteAccount', () => { + it('invokes deleteAccount without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteAccountRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteAccount = stubSimpleCall(expectedResponse); + const [response] = await client.deleteAccount(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteAccount without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteAccountRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteAccount = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteAccount( + 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.deleteAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteAccount with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteAccountRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteAccount = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteAccount(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteAccount with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteAccountRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteAccount(request), expectedError); + }); + }); + + describe('updateAccount', () => { + it('invokes updateAccount without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateAccountRequest(), + ); + request.account ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateAccountRequest', + ['account', 'name'], + ); + request.account.name = defaultValue1; + const expectedHeaderRequestParams = `account.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Account(), + ); + client.innerApiCalls.updateAccount = stubSimpleCall(expectedResponse); + const [response] = await client.updateAccount(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateAccount without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateAccountRequest(), + ); + request.account ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateAccountRequest', + ['account', 'name'], + ); + request.account.name = defaultValue1; + const expectedHeaderRequestParams = `account.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Account(), + ); + client.innerApiCalls.updateAccount = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateAccount( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IAccount | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateAccount with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateAccountRequest(), + ); + request.account ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateAccountRequest', + ['account', 'name'], + ); + request.account.name = defaultValue1; + const expectedHeaderRequestParams = `account.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateAccount = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateAccount(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateAccount with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateAccountRequest(), + ); + request.account ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateAccountRequest', + ['account', 'name'], + ); + request.account.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateAccount(request), expectedError); + }); + }); + + describe('provisionAccountTicket', () => { + it('invokes provisionAccountTicket without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ProvisionAccountTicketRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ProvisionAccountTicketResponse(), + ); + client.innerApiCalls.provisionAccountTicket = + stubSimpleCall(expectedResponse); + const [response] = await client.provisionAccountTicket(request); + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes provisionAccountTicket without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ProvisionAccountTicketRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ProvisionAccountTicketResponse(), + ); + client.innerApiCalls.provisionAccountTicket = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.provisionAccountTicket( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IProvisionAccountTicketResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes provisionAccountTicket with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ProvisionAccountTicketRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.provisionAccountTicket = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.provisionAccountTicket(request), + expectedError, + ); + }); + + it('invokes provisionAccountTicket with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ProvisionAccountTicketRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.provisionAccountTicket(request), + expectedError, + ); + }); + }); + + describe('getProperty', () => { + it('invokes getProperty without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetPropertyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetPropertyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Property(), + ); + client.innerApiCalls.getProperty = stubSimpleCall(expectedResponse); + const [response] = await client.getProperty(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getProperty as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getProperty as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getProperty without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetPropertyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetPropertyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Property(), + ); + client.innerApiCalls.getProperty = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getProperty( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IProperty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getProperty as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getProperty as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getProperty with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetPropertyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetPropertyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getProperty = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getProperty(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getProperty as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getProperty as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getProperty with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetPropertyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetPropertyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getProperty(request), expectedError); + }); + }); + + describe('createProperty', () => { + it('invokes createProperty without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreatePropertyRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Property(), + ); + client.innerApiCalls.createProperty = stubSimpleCall(expectedResponse); + const [response] = await client.createProperty(request); + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes createProperty without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreatePropertyRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Property(), + ); + client.innerApiCalls.createProperty = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createProperty( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IProperty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes createProperty with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreatePropertyRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createProperty = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createProperty(request), expectedError); + }); + + it('invokes createProperty with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreatePropertyRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createProperty(request), expectedError); + }); + }); + + describe('deleteProperty', () => { + it('invokes deleteProperty without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeletePropertyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeletePropertyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Property(), + ); + client.innerApiCalls.deleteProperty = stubSimpleCall(expectedResponse); + const [response] = await client.deleteProperty(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteProperty as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteProperty as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteProperty without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeletePropertyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeletePropertyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Property(), + ); + client.innerApiCalls.deleteProperty = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteProperty( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IProperty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteProperty as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteProperty as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteProperty with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeletePropertyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeletePropertyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteProperty = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteProperty(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteProperty as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteProperty as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteProperty with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeletePropertyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeletePropertyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteProperty(request), expectedError); + }); + }); + + describe('updateProperty', () => { + it('invokes updateProperty without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdatePropertyRequest(), + ); + request.property ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdatePropertyRequest', + ['property', 'name'], + ); + request.property.name = defaultValue1; + const expectedHeaderRequestParams = `property.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Property(), + ); + client.innerApiCalls.updateProperty = stubSimpleCall(expectedResponse); + const [response] = await client.updateProperty(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateProperty as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateProperty as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateProperty without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdatePropertyRequest(), + ); + request.property ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdatePropertyRequest', + ['property', 'name'], + ); + request.property.name = defaultValue1; + const expectedHeaderRequestParams = `property.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Property(), + ); + client.innerApiCalls.updateProperty = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateProperty( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IProperty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateProperty as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateProperty as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateProperty with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdatePropertyRequest(), + ); + request.property ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdatePropertyRequest', + ['property', 'name'], + ); + request.property.name = defaultValue1; + const expectedHeaderRequestParams = `property.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateProperty = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateProperty(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateProperty as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateProperty as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateProperty with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdatePropertyRequest(), + ); + request.property ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdatePropertyRequest', + ['property', 'name'], + ); + request.property.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateProperty(request), expectedError); + }); + }); + + describe('createFirebaseLink', () => { + it('invokes createFirebaseLink without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateFirebaseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateFirebaseLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.FirebaseLink(), + ); + client.innerApiCalls.createFirebaseLink = + stubSimpleCall(expectedResponse); + const [response] = await client.createFirebaseLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createFirebaseLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createFirebaseLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createFirebaseLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateFirebaseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateFirebaseLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.FirebaseLink(), + ); + client.innerApiCalls.createFirebaseLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createFirebaseLink( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IFirebaseLink | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createFirebaseLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createFirebaseLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createFirebaseLink with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateFirebaseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateFirebaseLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createFirebaseLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createFirebaseLink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createFirebaseLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createFirebaseLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createFirebaseLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateFirebaseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateFirebaseLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createFirebaseLink(request), expectedError); + }); + }); + + describe('deleteFirebaseLink', () => { + it('invokes deleteFirebaseLink without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteFirebaseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteFirebaseLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteFirebaseLink = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteFirebaseLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteFirebaseLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteFirebaseLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteFirebaseLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteFirebaseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteFirebaseLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteFirebaseLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteFirebaseLink( + 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.deleteFirebaseLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteFirebaseLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteFirebaseLink with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteFirebaseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteFirebaseLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteFirebaseLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteFirebaseLink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteFirebaseLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteFirebaseLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteFirebaseLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteFirebaseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteFirebaseLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteFirebaseLink(request), expectedError); + }); + }); + + describe('getGlobalSiteTag', () => { + it('invokes getGlobalSiteTag without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetGlobalSiteTagRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetGlobalSiteTagRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GlobalSiteTag(), + ); + client.innerApiCalls.getGlobalSiteTag = stubSimpleCall(expectedResponse); + const [response] = await client.getGlobalSiteTag(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getGlobalSiteTag as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGlobalSiteTag as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getGlobalSiteTag without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetGlobalSiteTagRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetGlobalSiteTagRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GlobalSiteTag(), + ); + client.innerApiCalls.getGlobalSiteTag = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getGlobalSiteTag( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IGlobalSiteTag | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getGlobalSiteTag as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGlobalSiteTag as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getGlobalSiteTag with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetGlobalSiteTagRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetGlobalSiteTagRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getGlobalSiteTag = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getGlobalSiteTag(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getGlobalSiteTag as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGlobalSiteTag as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getGlobalSiteTag with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetGlobalSiteTagRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetGlobalSiteTagRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getGlobalSiteTag(request), expectedError); + }); + }); + + describe('createGoogleAdsLink', () => { + it('invokes createGoogleAdsLink without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateGoogleAdsLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateGoogleAdsLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GoogleAdsLink(), + ); + client.innerApiCalls.createGoogleAdsLink = + stubSimpleCall(expectedResponse); + const [response] = await client.createGoogleAdsLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createGoogleAdsLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createGoogleAdsLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createGoogleAdsLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateGoogleAdsLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateGoogleAdsLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GoogleAdsLink(), + ); + client.innerApiCalls.createGoogleAdsLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createGoogleAdsLink( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IGoogleAdsLink | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createGoogleAdsLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createGoogleAdsLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createGoogleAdsLink with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateGoogleAdsLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateGoogleAdsLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createGoogleAdsLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createGoogleAdsLink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createGoogleAdsLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createGoogleAdsLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createGoogleAdsLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateGoogleAdsLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateGoogleAdsLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createGoogleAdsLink(request), expectedError); + }); + }); + + describe('updateGoogleAdsLink', () => { + it('invokes updateGoogleAdsLink without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest(), + ); + request.googleAdsLink ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest', + ['googleAdsLink', 'name'], + ); + request.googleAdsLink.name = defaultValue1; + const expectedHeaderRequestParams = `google_ads_link.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GoogleAdsLink(), + ); + client.innerApiCalls.updateGoogleAdsLink = + stubSimpleCall(expectedResponse); + const [response] = await client.updateGoogleAdsLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateGoogleAdsLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGoogleAdsLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateGoogleAdsLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest(), + ); + request.googleAdsLink ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest', + ['googleAdsLink', 'name'], + ); + request.googleAdsLink.name = defaultValue1; + const expectedHeaderRequestParams = `google_ads_link.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GoogleAdsLink(), + ); + client.innerApiCalls.updateGoogleAdsLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateGoogleAdsLink( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IGoogleAdsLink | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateGoogleAdsLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGoogleAdsLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateGoogleAdsLink with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest(), + ); + request.googleAdsLink ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest', + ['googleAdsLink', 'name'], + ); + request.googleAdsLink.name = defaultValue1; + const expectedHeaderRequestParams = `google_ads_link.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateGoogleAdsLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateGoogleAdsLink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateGoogleAdsLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGoogleAdsLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateGoogleAdsLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest(), + ); + request.googleAdsLink ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateGoogleAdsLinkRequest', + ['googleAdsLink', 'name'], + ); + request.googleAdsLink.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateGoogleAdsLink(request), expectedError); + }); + }); + + describe('deleteGoogleAdsLink', () => { + it('invokes deleteGoogleAdsLink without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteGoogleAdsLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteGoogleAdsLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteGoogleAdsLink = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteGoogleAdsLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteGoogleAdsLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteGoogleAdsLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteGoogleAdsLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteGoogleAdsLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteGoogleAdsLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteGoogleAdsLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteGoogleAdsLink( + 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.deleteGoogleAdsLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteGoogleAdsLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteGoogleAdsLink with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteGoogleAdsLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteGoogleAdsLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteGoogleAdsLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteGoogleAdsLink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteGoogleAdsLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteGoogleAdsLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteGoogleAdsLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteGoogleAdsLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteGoogleAdsLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteGoogleAdsLink(request), expectedError); + }); + }); + + describe('getDataSharingSettings', () => { + it('invokes getDataSharingSettings without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDataSharingSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDataSharingSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataSharingSettings(), + ); + client.innerApiCalls.getDataSharingSettings = + stubSimpleCall(expectedResponse); + const [response] = await client.getDataSharingSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDataSharingSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataSharingSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDataSharingSettings without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDataSharingSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDataSharingSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataSharingSettings(), + ); + client.innerApiCalls.getDataSharingSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDataSharingSettings( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IDataSharingSettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDataSharingSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataSharingSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDataSharingSettings with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDataSharingSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDataSharingSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDataSharingSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getDataSharingSettings(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getDataSharingSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataSharingSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDataSharingSettings with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDataSharingSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDataSharingSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getDataSharingSettings(request), + expectedError, + ); + }); + }); + + describe('getMeasurementProtocolSecret', () => { + it('invokes getMeasurementProtocolSecret without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret(), + ); + client.innerApiCalls.getMeasurementProtocolSecret = + stubSimpleCall(expectedResponse); + const [response] = await client.getMeasurementProtocolSecret(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getMeasurementProtocolSecret without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret(), + ); + client.innerApiCalls.getMeasurementProtocolSecret = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getMeasurementProtocolSecret( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getMeasurementProtocolSecret with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getMeasurementProtocolSecret = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getMeasurementProtocolSecret(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getMeasurementProtocolSecret with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getMeasurementProtocolSecret(request), + expectedError, + ); + }); + }); + + describe('createMeasurementProtocolSecret', () => { + it('invokes createMeasurementProtocolSecret without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateMeasurementProtocolSecretRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret(), + ); + client.innerApiCalls.createMeasurementProtocolSecret = + stubSimpleCall(expectedResponse); + const [response] = await client.createMeasurementProtocolSecret(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createMeasurementProtocolSecret without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateMeasurementProtocolSecretRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret(), + ); + client.innerApiCalls.createMeasurementProtocolSecret = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createMeasurementProtocolSecret( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createMeasurementProtocolSecret with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateMeasurementProtocolSecretRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createMeasurementProtocolSecret = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createMeasurementProtocolSecret(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createMeasurementProtocolSecret with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateMeasurementProtocolSecretRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createMeasurementProtocolSecret(request), + expectedError, + ); + }); + }); + + describe('deleteMeasurementProtocolSecret', () => { + it('invokes deleteMeasurementProtocolSecret without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteMeasurementProtocolSecretRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteMeasurementProtocolSecret = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteMeasurementProtocolSecret(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteMeasurementProtocolSecret without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteMeasurementProtocolSecretRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteMeasurementProtocolSecret = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteMeasurementProtocolSecret( + 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.deleteMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteMeasurementProtocolSecret with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteMeasurementProtocolSecretRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteMeasurementProtocolSecret = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteMeasurementProtocolSecret(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteMeasurementProtocolSecret with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteMeasurementProtocolSecretRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteMeasurementProtocolSecret(request), + expectedError, + ); + }); + }); + + describe('updateMeasurementProtocolSecret', () => { + it('invokes updateMeasurementProtocolSecret without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateMeasurementProtocolSecretRequest(), + ); + request.measurementProtocolSecret ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateMeasurementProtocolSecretRequest', + ['measurementProtocolSecret', 'name'], + ); + request.measurementProtocolSecret.name = defaultValue1; + const expectedHeaderRequestParams = `measurement_protocol_secret.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret(), + ); + client.innerApiCalls.updateMeasurementProtocolSecret = + stubSimpleCall(expectedResponse); + const [response] = await client.updateMeasurementProtocolSecret(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateMeasurementProtocolSecret without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateMeasurementProtocolSecretRequest(), + ); + request.measurementProtocolSecret ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateMeasurementProtocolSecretRequest', + ['measurementProtocolSecret', 'name'], + ); + request.measurementProtocolSecret.name = defaultValue1; + const expectedHeaderRequestParams = `measurement_protocol_secret.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret(), + ); + client.innerApiCalls.updateMeasurementProtocolSecret = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateMeasurementProtocolSecret( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateMeasurementProtocolSecret with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateMeasurementProtocolSecretRequest(), + ); + request.measurementProtocolSecret ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateMeasurementProtocolSecretRequest', + ['measurementProtocolSecret', 'name'], + ); + request.measurementProtocolSecret.name = defaultValue1; + const expectedHeaderRequestParams = `measurement_protocol_secret.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateMeasurementProtocolSecret = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateMeasurementProtocolSecret(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateMeasurementProtocolSecret with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateMeasurementProtocolSecretRequest(), + ); + request.measurementProtocolSecret ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateMeasurementProtocolSecretRequest', + ['measurementProtocolSecret', 'name'], + ); + request.measurementProtocolSecret.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateMeasurementProtocolSecret(request), + expectedError, + ); + }); + }); + + describe('acknowledgeUserDataCollection', () => { + it('invokes acknowledgeUserDataCollection without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AcknowledgeUserDataCollectionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.AcknowledgeUserDataCollectionRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AcknowledgeUserDataCollectionResponse(), + ); + client.innerApiCalls.acknowledgeUserDataCollection = + stubSimpleCall(expectedResponse); + const [response] = await client.acknowledgeUserDataCollection(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.acknowledgeUserDataCollection as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.acknowledgeUserDataCollection as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes acknowledgeUserDataCollection without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AcknowledgeUserDataCollectionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.AcknowledgeUserDataCollectionRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AcknowledgeUserDataCollectionResponse(), + ); + client.innerApiCalls.acknowledgeUserDataCollection = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.acknowledgeUserDataCollection( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IAcknowledgeUserDataCollectionResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.acknowledgeUserDataCollection as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.acknowledgeUserDataCollection as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes acknowledgeUserDataCollection with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AcknowledgeUserDataCollectionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.AcknowledgeUserDataCollectionRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.acknowledgeUserDataCollection = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.acknowledgeUserDataCollection(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.acknowledgeUserDataCollection as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.acknowledgeUserDataCollection as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes acknowledgeUserDataCollection with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AcknowledgeUserDataCollectionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.AcknowledgeUserDataCollectionRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.acknowledgeUserDataCollection(request), + expectedError, + ); + }); + }); + + describe('getSKAdNetworkConversionValueSchema', () => { + it('invokes getSKAdNetworkConversionValueSchema without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetSKAdNetworkConversionValueSchemaRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetSKAdNetworkConversionValueSchemaRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema(), + ); + client.innerApiCalls.getSkAdNetworkConversionValueSchema = + stubSimpleCall(expectedResponse); + const [response] = + await client.getSKAdNetworkConversionValueSchema(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getSKAdNetworkConversionValueSchema without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetSKAdNetworkConversionValueSchemaRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetSKAdNetworkConversionValueSchemaRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema(), + ); + client.innerApiCalls.getSkAdNetworkConversionValueSchema = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getSKAdNetworkConversionValueSchema( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getSKAdNetworkConversionValueSchema with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetSKAdNetworkConversionValueSchemaRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetSKAdNetworkConversionValueSchemaRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getSkAdNetworkConversionValueSchema = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getSKAdNetworkConversionValueSchema(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getSKAdNetworkConversionValueSchema with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetSKAdNetworkConversionValueSchemaRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetSKAdNetworkConversionValueSchemaRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getSKAdNetworkConversionValueSchema(request), + expectedError, + ); + }); + }); + + describe('createSKAdNetworkConversionValueSchema', () => { + it('invokes createSKAdNetworkConversionValueSchema without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema(), + ); + client.innerApiCalls.createSkAdNetworkConversionValueSchema = + stubSimpleCall(expectedResponse); + const [response] = + await client.createSKAdNetworkConversionValueSchema(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createSKAdNetworkConversionValueSchema without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema(), + ); + client.innerApiCalls.createSkAdNetworkConversionValueSchema = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createSKAdNetworkConversionValueSchema( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createSKAdNetworkConversionValueSchema with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createSkAdNetworkConversionValueSchema = + stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.createSKAdNetworkConversionValueSchema(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createSKAdNetworkConversionValueSchema with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateSKAdNetworkConversionValueSchemaRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createSKAdNetworkConversionValueSchema(request), + expectedError, + ); + }); + }); + + describe('deleteSKAdNetworkConversionValueSchema', () => { + it('invokes deleteSKAdNetworkConversionValueSchema without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteSKAdNetworkConversionValueSchemaRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteSKAdNetworkConversionValueSchemaRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteSkAdNetworkConversionValueSchema = + stubSimpleCall(expectedResponse); + const [response] = + await client.deleteSKAdNetworkConversionValueSchema(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteSKAdNetworkConversionValueSchema without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteSKAdNetworkConversionValueSchemaRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteSKAdNetworkConversionValueSchemaRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteSkAdNetworkConversionValueSchema = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteSKAdNetworkConversionValueSchema( + 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.deleteSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteSKAdNetworkConversionValueSchema with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteSKAdNetworkConversionValueSchemaRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteSKAdNetworkConversionValueSchemaRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteSkAdNetworkConversionValueSchema = + stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.deleteSKAdNetworkConversionValueSchema(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteSKAdNetworkConversionValueSchema with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteSKAdNetworkConversionValueSchemaRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteSKAdNetworkConversionValueSchemaRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteSKAdNetworkConversionValueSchema(request), + expectedError, + ); + }); + }); + + describe('updateSKAdNetworkConversionValueSchema', () => { + it('invokes updateSKAdNetworkConversionValueSchema without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateSKAdNetworkConversionValueSchemaRequest(), + ); + request.skadnetworkConversionValueSchema ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateSKAdNetworkConversionValueSchemaRequest', + ['skadnetworkConversionValueSchema', 'name'], + ); + request.skadnetworkConversionValueSchema.name = defaultValue1; + const expectedHeaderRequestParams = `skadnetwork_conversion_value_schema.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema(), + ); + client.innerApiCalls.updateSkAdNetworkConversionValueSchema = + stubSimpleCall(expectedResponse); + const [response] = + await client.updateSKAdNetworkConversionValueSchema(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateSKAdNetworkConversionValueSchema without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateSKAdNetworkConversionValueSchemaRequest(), + ); + request.skadnetworkConversionValueSchema ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateSKAdNetworkConversionValueSchemaRequest', + ['skadnetworkConversionValueSchema', 'name'], + ); + request.skadnetworkConversionValueSchema.name = defaultValue1; + const expectedHeaderRequestParams = `skadnetwork_conversion_value_schema.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema(), + ); + client.innerApiCalls.updateSkAdNetworkConversionValueSchema = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateSKAdNetworkConversionValueSchema( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateSKAdNetworkConversionValueSchema with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateSKAdNetworkConversionValueSchemaRequest(), + ); + request.skadnetworkConversionValueSchema ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateSKAdNetworkConversionValueSchemaRequest', + ['skadnetworkConversionValueSchema', 'name'], + ); + request.skadnetworkConversionValueSchema.name = defaultValue1; + const expectedHeaderRequestParams = `skadnetwork_conversion_value_schema.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateSkAdNetworkConversionValueSchema = + stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.updateSKAdNetworkConversionValueSchema(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSkAdNetworkConversionValueSchema as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateSKAdNetworkConversionValueSchema with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateSKAdNetworkConversionValueSchemaRequest(), + ); + request.skadnetworkConversionValueSchema ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateSKAdNetworkConversionValueSchemaRequest', + ['skadnetworkConversionValueSchema', 'name'], + ); + request.skadnetworkConversionValueSchema.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateSKAdNetworkConversionValueSchema(request), + expectedError, + ); + }); + }); + + describe('getGoogleSignalsSettings', () => { + it('invokes getGoogleSignalsSettings without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetGoogleSignalsSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetGoogleSignalsSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GoogleSignalsSettings(), + ); + client.innerApiCalls.getGoogleSignalsSettings = + stubSimpleCall(expectedResponse); + const [response] = await client.getGoogleSignalsSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getGoogleSignalsSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGoogleSignalsSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getGoogleSignalsSettings without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetGoogleSignalsSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetGoogleSignalsSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GoogleSignalsSettings(), + ); + client.innerApiCalls.getGoogleSignalsSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getGoogleSignalsSettings( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getGoogleSignalsSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGoogleSignalsSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getGoogleSignalsSettings with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetGoogleSignalsSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetGoogleSignalsSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getGoogleSignalsSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getGoogleSignalsSettings(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getGoogleSignalsSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getGoogleSignalsSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getGoogleSignalsSettings with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetGoogleSignalsSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetGoogleSignalsSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getGoogleSignalsSettings(request), + expectedError, + ); + }); + }); + + describe('updateGoogleSignalsSettings', () => { + it('invokes updateGoogleSignalsSettings without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateGoogleSignalsSettingsRequest(), + ); + request.googleSignalsSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateGoogleSignalsSettingsRequest', + ['googleSignalsSettings', 'name'], + ); + request.googleSignalsSettings.name = defaultValue1; + const expectedHeaderRequestParams = `google_signals_settings.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GoogleSignalsSettings(), + ); + client.innerApiCalls.updateGoogleSignalsSettings = + stubSimpleCall(expectedResponse); + const [response] = await client.updateGoogleSignalsSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateGoogleSignalsSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGoogleSignalsSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateGoogleSignalsSettings without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateGoogleSignalsSettingsRequest(), + ); + request.googleSignalsSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateGoogleSignalsSettingsRequest', + ['googleSignalsSettings', 'name'], + ); + request.googleSignalsSettings.name = defaultValue1; + const expectedHeaderRequestParams = `google_signals_settings.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GoogleSignalsSettings(), + ); + client.innerApiCalls.updateGoogleSignalsSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateGoogleSignalsSettings( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IGoogleSignalsSettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateGoogleSignalsSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGoogleSignalsSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateGoogleSignalsSettings with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateGoogleSignalsSettingsRequest(), + ); + request.googleSignalsSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateGoogleSignalsSettingsRequest', + ['googleSignalsSettings', 'name'], + ); + request.googleSignalsSettings.name = defaultValue1; + const expectedHeaderRequestParams = `google_signals_settings.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateGoogleSignalsSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateGoogleSignalsSettings(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateGoogleSignalsSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGoogleSignalsSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateGoogleSignalsSettings with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateGoogleSignalsSettingsRequest(), + ); + request.googleSignalsSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateGoogleSignalsSettingsRequest', + ['googleSignalsSettings', 'name'], + ); + request.googleSignalsSettings.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateGoogleSignalsSettings(request), + expectedError, + ); + }); + }); + + describe('createConversionEvent', () => { + it('invokes createConversionEvent without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateConversionEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ConversionEvent(), + ); + client.innerApiCalls.createConversionEvent = + stubSimpleCall(expectedResponse); + const [response] = await client.createConversionEvent(request); + assert(stub.calledOnce); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createConversionEvent without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateConversionEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ConversionEvent(), + ); + client.innerApiCalls.createConversionEvent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createConversionEvent( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IConversionEvent | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert(stub.calledOnce); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createConversionEvent with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateConversionEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createConversionEvent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createConversionEvent(request), + expectedError, + ); + assert(stub.calledOnce); + const actualRequest = ( + client.innerApiCalls.createConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createConversionEvent with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateConversionEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createConversionEvent(request), + expectedError, + ); + assert(stub.calledOnce); + }); + }); + + describe('updateConversionEvent', () => { + it('invokes updateConversionEvent without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateConversionEventRequest(), + ); + request.conversionEvent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateConversionEventRequest', + ['conversionEvent', 'name'], + ); + request.conversionEvent.name = defaultValue1; + const expectedHeaderRequestParams = `conversion_event.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ConversionEvent(), + ); + client.innerApiCalls.updateConversionEvent = + stubSimpleCall(expectedResponse); + const [response] = await client.updateConversionEvent(request); + assert(stub.calledOnce); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateConversionEvent without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateConversionEventRequest(), + ); + request.conversionEvent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateConversionEventRequest', + ['conversionEvent', 'name'], + ); + request.conversionEvent.name = defaultValue1; + const expectedHeaderRequestParams = `conversion_event.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ConversionEvent(), + ); + client.innerApiCalls.updateConversionEvent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateConversionEvent( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IConversionEvent | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert(stub.calledOnce); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateConversionEvent with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateConversionEventRequest(), + ); + request.conversionEvent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateConversionEventRequest', + ['conversionEvent', 'name'], + ); + request.conversionEvent.name = defaultValue1; + const expectedHeaderRequestParams = `conversion_event.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateConversionEvent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateConversionEvent(request), + expectedError, + ); + assert(stub.calledOnce); + const actualRequest = ( + client.innerApiCalls.updateConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateConversionEvent with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateConversionEventRequest(), + ); + request.conversionEvent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateConversionEventRequest', + ['conversionEvent', 'name'], + ); + request.conversionEvent.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateConversionEvent(request), + expectedError, + ); + assert(stub.calledOnce); + }); + }); + + describe('getConversionEvent', () => { + it('invokes getConversionEvent without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetConversionEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ConversionEvent(), + ); + client.innerApiCalls.getConversionEvent = + stubSimpleCall(expectedResponse); + const [response] = await client.getConversionEvent(request); + assert(stub.calledOnce); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getConversionEvent without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetConversionEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ConversionEvent(), + ); + client.innerApiCalls.getConversionEvent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getConversionEvent( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IConversionEvent | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert(stub.calledOnce); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getConversionEvent with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetConversionEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getConversionEvent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getConversionEvent(request), expectedError); + assert(stub.calledOnce); + const actualRequest = ( + client.innerApiCalls.getConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getConversionEvent with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetConversionEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getConversionEvent(request), expectedError); + assert(stub.calledOnce); + }); + }); + + describe('deleteConversionEvent', () => { + it('invokes deleteConversionEvent without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteConversionEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteConversionEvent = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteConversionEvent(request); + assert(stub.calledOnce); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteConversionEvent without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteConversionEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteConversionEvent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteConversionEvent( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert(stub.calledOnce); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteConversionEvent with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteConversionEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteConversionEvent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteConversionEvent(request), + expectedError, + ); + assert(stub.calledOnce); + const actualRequest = ( + client.innerApiCalls.deleteConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteConversionEvent with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteConversionEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteConversionEvent(request), + expectedError, + ); + assert(stub.calledOnce); + }); + }); + + describe('createKeyEvent', () => { + it('invokes createKeyEvent without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateKeyEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.KeyEvent(), + ); + client.innerApiCalls.createKeyEvent = stubSimpleCall(expectedResponse); + const [response] = await client.createKeyEvent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createKeyEvent without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateKeyEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.KeyEvent(), + ); + client.innerApiCalls.createKeyEvent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createKeyEvent( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IKeyEvent | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createKeyEvent with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateKeyEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createKeyEvent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createKeyEvent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createKeyEvent with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateKeyEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createKeyEvent(request), expectedError); + }); + }); + + describe('updateKeyEvent', () => { + it('invokes updateKeyEvent without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateKeyEventRequest(), + ); + request.keyEvent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateKeyEventRequest', + ['keyEvent', 'name'], + ); + request.keyEvent.name = defaultValue1; + const expectedHeaderRequestParams = `key_event.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.KeyEvent(), + ); + client.innerApiCalls.updateKeyEvent = stubSimpleCall(expectedResponse); + const [response] = await client.updateKeyEvent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateKeyEvent without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateKeyEventRequest(), + ); + request.keyEvent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateKeyEventRequest', + ['keyEvent', 'name'], + ); + request.keyEvent.name = defaultValue1; + const expectedHeaderRequestParams = `key_event.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.KeyEvent(), + ); + client.innerApiCalls.updateKeyEvent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateKeyEvent( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IKeyEvent | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateKeyEvent with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateKeyEventRequest(), + ); + request.keyEvent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateKeyEventRequest', + ['keyEvent', 'name'], + ); + request.keyEvent.name = defaultValue1; + const expectedHeaderRequestParams = `key_event.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateKeyEvent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateKeyEvent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateKeyEvent with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateKeyEventRequest(), + ); + request.keyEvent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateKeyEventRequest', + ['keyEvent', 'name'], + ); + request.keyEvent.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateKeyEvent(request), expectedError); + }); + }); + + describe('getKeyEvent', () => { + it('invokes getKeyEvent without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetKeyEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.KeyEvent(), + ); + client.innerApiCalls.getKeyEvent = stubSimpleCall(expectedResponse); + const [response] = await client.getKeyEvent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getKeyEvent without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetKeyEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.KeyEvent(), + ); + client.innerApiCalls.getKeyEvent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getKeyEvent( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IKeyEvent | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getKeyEvent with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetKeyEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getKeyEvent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getKeyEvent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getKeyEvent with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetKeyEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getKeyEvent(request), expectedError); + }); + }); + + describe('deleteKeyEvent', () => { + it('invokes deleteKeyEvent without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteKeyEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteKeyEvent = stubSimpleCall(expectedResponse); + const [response] = await client.deleteKeyEvent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteKeyEvent without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteKeyEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteKeyEvent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteKeyEvent( + 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.deleteKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteKeyEvent with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteKeyEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteKeyEvent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteKeyEvent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteKeyEvent with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteKeyEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteKeyEvent(request), expectedError); + }); + }); + + describe('getDisplayVideo360AdvertiserLink', () => { + it('invokes getDisplayVideo360AdvertiserLink without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink(), + ); + client.innerApiCalls.getDisplayVideo360AdvertiserLink = + stubSimpleCall(expectedResponse); + const [response] = await client.getDisplayVideo360AdvertiserLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDisplayVideo360AdvertiserLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink(), + ); + client.innerApiCalls.getDisplayVideo360AdvertiserLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDisplayVideo360AdvertiserLink( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDisplayVideo360AdvertiserLink with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDisplayVideo360AdvertiserLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getDisplayVideo360AdvertiserLink(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDisplayVideo360AdvertiserLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getDisplayVideo360AdvertiserLink(request), + expectedError, + ); + }); + }); + + describe('createDisplayVideo360AdvertiserLink', () => { + it('invokes createDisplayVideo360AdvertiserLink without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink(), + ); + client.innerApiCalls.createDisplayVideo360AdvertiserLink = + stubSimpleCall(expectedResponse); + const [response] = + await client.createDisplayVideo360AdvertiserLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDisplayVideo360AdvertiserLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink(), + ); + client.innerApiCalls.createDisplayVideo360AdvertiserLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createDisplayVideo360AdvertiserLink( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDisplayVideo360AdvertiserLink with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createDisplayVideo360AdvertiserLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createDisplayVideo360AdvertiserLink(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDisplayVideo360AdvertiserLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createDisplayVideo360AdvertiserLink(request), + expectedError, + ); + }); + }); + + describe('deleteDisplayVideo360AdvertiserLink', () => { + it('invokes deleteDisplayVideo360AdvertiserLink without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDisplayVideo360AdvertiserLink = + stubSimpleCall(expectedResponse); + const [response] = + await client.deleteDisplayVideo360AdvertiserLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDisplayVideo360AdvertiserLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDisplayVideo360AdvertiserLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteDisplayVideo360AdvertiserLink( + 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.deleteDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDisplayVideo360AdvertiserLink with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteDisplayVideo360AdvertiserLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteDisplayVideo360AdvertiserLink(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDisplayVideo360AdvertiserLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteDisplayVideo360AdvertiserLink(request), + expectedError, + ); + }); + }); + + describe('updateDisplayVideo360AdvertiserLink', () => { + it('invokes updateDisplayVideo360AdvertiserLink without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateDisplayVideo360AdvertiserLinkRequest(), + ); + request.displayVideo_360AdvertiserLink ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateDisplayVideo360AdvertiserLinkRequest', + ['displayVideo_360AdvertiserLink', 'name'], + ); + request.displayVideo_360AdvertiserLink.name = defaultValue1; + const expectedHeaderRequestParams = `display_video_360_advertiser_link.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink(), + ); + client.innerApiCalls.updateDisplayVideo360AdvertiserLink = + stubSimpleCall(expectedResponse); + const [response] = + await client.updateDisplayVideo360AdvertiserLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDisplayVideo360AdvertiserLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateDisplayVideo360AdvertiserLinkRequest(), + ); + request.displayVideo_360AdvertiserLink ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateDisplayVideo360AdvertiserLinkRequest', + ['displayVideo_360AdvertiserLink', 'name'], + ); + request.displayVideo_360AdvertiserLink.name = defaultValue1; + const expectedHeaderRequestParams = `display_video_360_advertiser_link.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink(), + ); + client.innerApiCalls.updateDisplayVideo360AdvertiserLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateDisplayVideo360AdvertiserLink( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDisplayVideo360AdvertiserLink with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateDisplayVideo360AdvertiserLinkRequest(), + ); + request.displayVideo_360AdvertiserLink ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateDisplayVideo360AdvertiserLinkRequest', + ['displayVideo_360AdvertiserLink', 'name'], + ); + request.displayVideo_360AdvertiserLink.name = defaultValue1; + const expectedHeaderRequestParams = `display_video_360_advertiser_link.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDisplayVideo360AdvertiserLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateDisplayVideo360AdvertiserLink(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDisplayVideo360AdvertiserLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDisplayVideo360AdvertiserLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateDisplayVideo360AdvertiserLinkRequest(), + ); + request.displayVideo_360AdvertiserLink ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateDisplayVideo360AdvertiserLinkRequest', + ['displayVideo_360AdvertiserLink', 'name'], + ); + request.displayVideo_360AdvertiserLink.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateDisplayVideo360AdvertiserLink(request), + expectedError, + ); + }); + }); + + describe('getDisplayVideo360AdvertiserLinkProposal', () => { + it('invokes getDisplayVideo360AdvertiserLinkProposal without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkProposalRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkProposalRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal(), + ); + client.innerApiCalls.getDisplayVideo360AdvertiserLinkProposal = + stubSimpleCall(expectedResponse); + const [response] = + await client.getDisplayVideo360AdvertiserLinkProposal(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls + .getDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .getDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDisplayVideo360AdvertiserLinkProposal without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkProposalRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkProposalRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal(), + ); + client.innerApiCalls.getDisplayVideo360AdvertiserLinkProposal = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDisplayVideo360AdvertiserLinkProposal( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls + .getDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .getDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDisplayVideo360AdvertiserLinkProposal with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkProposalRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkProposalRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDisplayVideo360AdvertiserLinkProposal = + stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.getDisplayVideo360AdvertiserLinkProposal(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls + .getDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .getDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDisplayVideo360AdvertiserLinkProposal with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkProposalRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDisplayVideo360AdvertiserLinkProposalRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getDisplayVideo360AdvertiserLinkProposal(request), + expectedError, + ); + }); + }); + + describe('createDisplayVideo360AdvertiserLinkProposal', () => { + it('invokes createDisplayVideo360AdvertiserLinkProposal without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkProposalRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkProposalRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal(), + ); + client.innerApiCalls.createDisplayVideo360AdvertiserLinkProposal = + stubSimpleCall(expectedResponse); + const [response] = + await client.createDisplayVideo360AdvertiserLinkProposal(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls + .createDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .createDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDisplayVideo360AdvertiserLinkProposal without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkProposalRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkProposalRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal(), + ); + client.innerApiCalls.createDisplayVideo360AdvertiserLinkProposal = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createDisplayVideo360AdvertiserLinkProposal( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls + .createDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .createDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDisplayVideo360AdvertiserLinkProposal with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkProposalRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkProposalRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createDisplayVideo360AdvertiserLinkProposal = + stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.createDisplayVideo360AdvertiserLinkProposal(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls + .createDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .createDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDisplayVideo360AdvertiserLinkProposal with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkProposalRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateDisplayVideo360AdvertiserLinkProposalRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createDisplayVideo360AdvertiserLinkProposal(request), + expectedError, + ); + }); + }); + + describe('deleteDisplayVideo360AdvertiserLinkProposal', () => { + it('invokes deleteDisplayVideo360AdvertiserLinkProposal without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkProposalRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkProposalRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDisplayVideo360AdvertiserLinkProposal = + stubSimpleCall(expectedResponse); + const [response] = + await client.deleteDisplayVideo360AdvertiserLinkProposal(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls + .deleteDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .deleteDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDisplayVideo360AdvertiserLinkProposal without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkProposalRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkProposalRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDisplayVideo360AdvertiserLinkProposal = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteDisplayVideo360AdvertiserLinkProposal( + 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 + .deleteDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .deleteDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDisplayVideo360AdvertiserLinkProposal with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkProposalRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkProposalRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteDisplayVideo360AdvertiserLinkProposal = + stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.deleteDisplayVideo360AdvertiserLinkProposal(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls + .deleteDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .deleteDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDisplayVideo360AdvertiserLinkProposal with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkProposalRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteDisplayVideo360AdvertiserLinkProposalRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteDisplayVideo360AdvertiserLinkProposal(request), + expectedError, + ); + }); + }); + + describe('approveDisplayVideo360AdvertiserLinkProposal', () => { + it('invokes approveDisplayVideo360AdvertiserLinkProposal without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalResponse(), + ); + client.innerApiCalls.approveDisplayVideo360AdvertiserLinkProposal = + stubSimpleCall(expectedResponse); + const [response] = + await client.approveDisplayVideo360AdvertiserLinkProposal(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls + .approveDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .approveDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes approveDisplayVideo360AdvertiserLinkProposal without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalResponse(), + ); + client.innerApiCalls.approveDisplayVideo360AdvertiserLinkProposal = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.approveDisplayVideo360AdvertiserLinkProposal( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IApproveDisplayVideo360AdvertiserLinkProposalResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls + .approveDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .approveDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes approveDisplayVideo360AdvertiserLinkProposal with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.approveDisplayVideo360AdvertiserLinkProposal = + stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.approveDisplayVideo360AdvertiserLinkProposal(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls + .approveDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .approveDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes approveDisplayVideo360AdvertiserLinkProposal with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.approveDisplayVideo360AdvertiserLinkProposal(request), + expectedError, + ); + }); + }); + + describe('cancelDisplayVideo360AdvertiserLinkProposal', () => { + it('invokes cancelDisplayVideo360AdvertiserLinkProposal without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CancelDisplayVideo360AdvertiserLinkProposalRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CancelDisplayVideo360AdvertiserLinkProposalRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal(), + ); + client.innerApiCalls.cancelDisplayVideo360AdvertiserLinkProposal = + stubSimpleCall(expectedResponse); + const [response] = + await client.cancelDisplayVideo360AdvertiserLinkProposal(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls + .cancelDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .cancelDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes cancelDisplayVideo360AdvertiserLinkProposal without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CancelDisplayVideo360AdvertiserLinkProposalRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CancelDisplayVideo360AdvertiserLinkProposalRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal(), + ); + client.innerApiCalls.cancelDisplayVideo360AdvertiserLinkProposal = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.cancelDisplayVideo360AdvertiserLinkProposal( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls + .cancelDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .cancelDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes cancelDisplayVideo360AdvertiserLinkProposal with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CancelDisplayVideo360AdvertiserLinkProposalRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CancelDisplayVideo360AdvertiserLinkProposalRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.cancelDisplayVideo360AdvertiserLinkProposal = + stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.cancelDisplayVideo360AdvertiserLinkProposal(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls + .cancelDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .cancelDisplayVideo360AdvertiserLinkProposal as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes cancelDisplayVideo360AdvertiserLinkProposal with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CancelDisplayVideo360AdvertiserLinkProposalRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CancelDisplayVideo360AdvertiserLinkProposalRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.cancelDisplayVideo360AdvertiserLinkProposal(request), + expectedError, + ); + }); + }); + + describe('createCustomDimension', () => { + it('invokes createCustomDimension without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateCustomDimensionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomDimension(), + ); + client.innerApiCalls.createCustomDimension = + stubSimpleCall(expectedResponse); + const [response] = await client.createCustomDimension(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCustomDimension without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateCustomDimensionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomDimension(), + ); + client.innerApiCalls.createCustomDimension = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createCustomDimension( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.ICustomDimension | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCustomDimension with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateCustomDimensionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createCustomDimension = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createCustomDimension(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCustomDimension with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateCustomDimensionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createCustomDimension(request), + expectedError, + ); + }); + }); + + describe('updateCustomDimension', () => { + it('invokes updateCustomDimension without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateCustomDimensionRequest(), + ); + request.customDimension ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateCustomDimensionRequest', + ['customDimension', 'name'], + ); + request.customDimension.name = defaultValue1; + const expectedHeaderRequestParams = `custom_dimension.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomDimension(), + ); + client.innerApiCalls.updateCustomDimension = + stubSimpleCall(expectedResponse); + const [response] = await client.updateCustomDimension(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCustomDimension without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateCustomDimensionRequest(), + ); + request.customDimension ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateCustomDimensionRequest', + ['customDimension', 'name'], + ); + request.customDimension.name = defaultValue1; + const expectedHeaderRequestParams = `custom_dimension.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomDimension(), + ); + client.innerApiCalls.updateCustomDimension = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateCustomDimension( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.ICustomDimension | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCustomDimension with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateCustomDimensionRequest(), + ); + request.customDimension ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateCustomDimensionRequest', + ['customDimension', 'name'], + ); + request.customDimension.name = defaultValue1; + const expectedHeaderRequestParams = `custom_dimension.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateCustomDimension = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateCustomDimension(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCustomDimension with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateCustomDimensionRequest(), + ); + request.customDimension ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateCustomDimensionRequest', + ['customDimension', 'name'], + ); + request.customDimension.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateCustomDimension(request), + expectedError, + ); + }); + }); + + describe('archiveCustomDimension', () => { + it('invokes archiveCustomDimension without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ArchiveCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ArchiveCustomDimensionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.archiveCustomDimension = + stubSimpleCall(expectedResponse); + const [response] = await client.archiveCustomDimension(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.archiveCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.archiveCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes archiveCustomDimension without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ArchiveCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ArchiveCustomDimensionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.archiveCustomDimension = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.archiveCustomDimension( + 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.archiveCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.archiveCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes archiveCustomDimension with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ArchiveCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ArchiveCustomDimensionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.archiveCustomDimension = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.archiveCustomDimension(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.archiveCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.archiveCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes archiveCustomDimension with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ArchiveCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ArchiveCustomDimensionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.archiveCustomDimension(request), + expectedError, + ); + }); + }); + + describe('getCustomDimension', () => { + it('invokes getCustomDimension without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetCustomDimensionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomDimension(), + ); + client.innerApiCalls.getCustomDimension = + stubSimpleCall(expectedResponse); + const [response] = await client.getCustomDimension(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCustomDimension without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetCustomDimensionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomDimension(), + ); + client.innerApiCalls.getCustomDimension = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getCustomDimension( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.ICustomDimension | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCustomDimension with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetCustomDimensionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getCustomDimension = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getCustomDimension(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCustomDimension with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetCustomDimensionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getCustomDimension(request), expectedError); + }); + }); + + describe('createCustomMetric', () => { + it('invokes createCustomMetric without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateCustomMetricRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomMetric(), + ); + client.innerApiCalls.createCustomMetric = + stubSimpleCall(expectedResponse); + const [response] = await client.createCustomMetric(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCustomMetric without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateCustomMetricRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomMetric(), + ); + client.innerApiCalls.createCustomMetric = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createCustomMetric( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.ICustomMetric | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCustomMetric with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateCustomMetricRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createCustomMetric = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createCustomMetric(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCustomMetric with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateCustomMetricRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createCustomMetric(request), expectedError); + }); + }); + + describe('updateCustomMetric', () => { + it('invokes updateCustomMetric without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateCustomMetricRequest(), + ); + request.customMetric ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateCustomMetricRequest', + ['customMetric', 'name'], + ); + request.customMetric.name = defaultValue1; + const expectedHeaderRequestParams = `custom_metric.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomMetric(), + ); + client.innerApiCalls.updateCustomMetric = + stubSimpleCall(expectedResponse); + const [response] = await client.updateCustomMetric(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCustomMetric without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateCustomMetricRequest(), + ); + request.customMetric ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateCustomMetricRequest', + ['customMetric', 'name'], + ); + request.customMetric.name = defaultValue1; + const expectedHeaderRequestParams = `custom_metric.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomMetric(), + ); + client.innerApiCalls.updateCustomMetric = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateCustomMetric( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.ICustomMetric | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCustomMetric with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateCustomMetricRequest(), + ); + request.customMetric ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateCustomMetricRequest', + ['customMetric', 'name'], + ); + request.customMetric.name = defaultValue1; + const expectedHeaderRequestParams = `custom_metric.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateCustomMetric = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateCustomMetric(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCustomMetric with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateCustomMetricRequest(), + ); + request.customMetric ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateCustomMetricRequest', + ['customMetric', 'name'], + ); + request.customMetric.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateCustomMetric(request), expectedError); + }); + }); + + describe('archiveCustomMetric', () => { + it('invokes archiveCustomMetric without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ArchiveCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ArchiveCustomMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.archiveCustomMetric = + stubSimpleCall(expectedResponse); + const [response] = await client.archiveCustomMetric(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.archiveCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.archiveCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes archiveCustomMetric without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ArchiveCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ArchiveCustomMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.archiveCustomMetric = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.archiveCustomMetric( + 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.archiveCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.archiveCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes archiveCustomMetric with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ArchiveCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ArchiveCustomMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.archiveCustomMetric = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.archiveCustomMetric(request), expectedError); + const actualRequest = ( + client.innerApiCalls.archiveCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.archiveCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes archiveCustomMetric with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ArchiveCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ArchiveCustomMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.archiveCustomMetric(request), expectedError); + }); + }); + + describe('getCustomMetric', () => { + it('invokes getCustomMetric without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetCustomMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomMetric(), + ); + client.innerApiCalls.getCustomMetric = stubSimpleCall(expectedResponse); + const [response] = await client.getCustomMetric(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCustomMetric without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetCustomMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomMetric(), + ); + client.innerApiCalls.getCustomMetric = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getCustomMetric( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.ICustomMetric | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCustomMetric with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetCustomMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getCustomMetric = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getCustomMetric(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCustomMetric with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetCustomMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getCustomMetric(request), expectedError); + }); + }); + + describe('getDataRetentionSettings', () => { + it('invokes getDataRetentionSettings without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDataRetentionSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDataRetentionSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataRetentionSettings(), + ); + client.innerApiCalls.getDataRetentionSettings = + stubSimpleCall(expectedResponse); + const [response] = await client.getDataRetentionSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDataRetentionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataRetentionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDataRetentionSettings without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDataRetentionSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDataRetentionSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataRetentionSettings(), + ); + client.innerApiCalls.getDataRetentionSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDataRetentionSettings( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IDataRetentionSettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDataRetentionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataRetentionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDataRetentionSettings with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDataRetentionSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDataRetentionSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDataRetentionSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getDataRetentionSettings(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getDataRetentionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataRetentionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDataRetentionSettings with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDataRetentionSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDataRetentionSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getDataRetentionSettings(request), + expectedError, + ); + }); + }); + + describe('updateDataRetentionSettings', () => { + it('invokes updateDataRetentionSettings without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateDataRetentionSettingsRequest(), + ); + request.dataRetentionSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateDataRetentionSettingsRequest', + ['dataRetentionSettings', 'name'], + ); + request.dataRetentionSettings.name = defaultValue1; + const expectedHeaderRequestParams = `data_retention_settings.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataRetentionSettings(), + ); + client.innerApiCalls.updateDataRetentionSettings = + stubSimpleCall(expectedResponse); + const [response] = await client.updateDataRetentionSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDataRetentionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDataRetentionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDataRetentionSettings without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateDataRetentionSettingsRequest(), + ); + request.dataRetentionSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateDataRetentionSettingsRequest', + ['dataRetentionSettings', 'name'], + ); + request.dataRetentionSettings.name = defaultValue1; + const expectedHeaderRequestParams = `data_retention_settings.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataRetentionSettings(), + ); + client.innerApiCalls.updateDataRetentionSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateDataRetentionSettings( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IDataRetentionSettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDataRetentionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDataRetentionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDataRetentionSettings with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateDataRetentionSettingsRequest(), + ); + request.dataRetentionSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateDataRetentionSettingsRequest', + ['dataRetentionSettings', 'name'], + ); + request.dataRetentionSettings.name = defaultValue1; + const expectedHeaderRequestParams = `data_retention_settings.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDataRetentionSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateDataRetentionSettings(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateDataRetentionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDataRetentionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDataRetentionSettings with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateDataRetentionSettingsRequest(), + ); + request.dataRetentionSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateDataRetentionSettingsRequest', + ['dataRetentionSettings', 'name'], + ); + request.dataRetentionSettings.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateDataRetentionSettings(request), + expectedError, + ); + }); + }); + + describe('createDataStream', () => { + it('invokes createDataStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateDataStreamRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataStream(), + ); + client.innerApiCalls.createDataStream = stubSimpleCall(expectedResponse); + const [response] = await client.createDataStream(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDataStream without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateDataStreamRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataStream(), + ); + client.innerApiCalls.createDataStream = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createDataStream( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IDataStream | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDataStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateDataStreamRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createDataStream = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createDataStream(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDataStream with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateDataStreamRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createDataStream(request), expectedError); + }); + }); + + describe('deleteDataStream', () => { + it('invokes deleteDataStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteDataStreamRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDataStream = stubSimpleCall(expectedResponse); + const [response] = await client.deleteDataStream(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDataStream without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteDataStreamRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDataStream = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteDataStream( + 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.deleteDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDataStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteDataStreamRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteDataStream = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteDataStream(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDataStream with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteDataStreamRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteDataStream(request), expectedError); + }); + }); + + describe('updateDataStream', () => { + it('invokes updateDataStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateDataStreamRequest(), + ); + request.dataStream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateDataStreamRequest', + ['dataStream', 'name'], + ); + request.dataStream.name = defaultValue1; + const expectedHeaderRequestParams = `data_stream.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataStream(), + ); + client.innerApiCalls.updateDataStream = stubSimpleCall(expectedResponse); + const [response] = await client.updateDataStream(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDataStream without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateDataStreamRequest(), + ); + request.dataStream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateDataStreamRequest', + ['dataStream', 'name'], + ); + request.dataStream.name = defaultValue1; + const expectedHeaderRequestParams = `data_stream.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataStream(), + ); + client.innerApiCalls.updateDataStream = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateDataStream( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IDataStream | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDataStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateDataStreamRequest(), + ); + request.dataStream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateDataStreamRequest', + ['dataStream', 'name'], + ); + request.dataStream.name = defaultValue1; + const expectedHeaderRequestParams = `data_stream.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDataStream = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateDataStream(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDataStream with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateDataStreamRequest(), + ); + request.dataStream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateDataStreamRequest', + ['dataStream', 'name'], + ); + request.dataStream.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateDataStream(request), expectedError); + }); + }); + + describe('getDataStream', () => { + it('invokes getDataStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDataStreamRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataStream(), + ); + client.innerApiCalls.getDataStream = stubSimpleCall(expectedResponse); + const [response] = await client.getDataStream(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDataStream without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDataStreamRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataStream(), + ); + client.innerApiCalls.getDataStream = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDataStream( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IDataStream | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDataStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDataStreamRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDataStream = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getDataStream(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDataStream with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDataStreamRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getDataStream(request), expectedError); + }); + }); + + describe('getAudience', () => { + it('invokes getAudience without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetAudienceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetAudienceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Audience(), + ); + client.innerApiCalls.getAudience = stubSimpleCall(expectedResponse); + const [response] = await client.getAudience(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAudience as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAudience as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getAudience without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetAudienceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetAudienceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Audience(), + ); + client.innerApiCalls.getAudience = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getAudience( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IAudience | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAudience as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAudience as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getAudience with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetAudienceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetAudienceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getAudience = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getAudience(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getAudience as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAudience as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getAudience with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetAudienceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetAudienceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getAudience(request), expectedError); + }); + }); + + describe('createAudience', () => { + it('invokes createAudience without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateAudienceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateAudienceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Audience(), + ); + client.innerApiCalls.createAudience = stubSimpleCall(expectedResponse); + const [response] = await client.createAudience(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createAudience as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createAudience as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createAudience without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateAudienceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateAudienceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Audience(), + ); + client.innerApiCalls.createAudience = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createAudience( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IAudience | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createAudience as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createAudience as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createAudience with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateAudienceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateAudienceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createAudience = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createAudience(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createAudience as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createAudience as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createAudience with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateAudienceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateAudienceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createAudience(request), expectedError); + }); + }); + + describe('updateAudience', () => { + it('invokes updateAudience without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateAudienceRequest(), + ); + request.audience ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateAudienceRequest', + ['audience', 'name'], + ); + request.audience.name = defaultValue1; + const expectedHeaderRequestParams = `audience.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Audience(), + ); + client.innerApiCalls.updateAudience = stubSimpleCall(expectedResponse); + const [response] = await client.updateAudience(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateAudience as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAudience as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateAudience without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateAudienceRequest(), + ); + request.audience ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateAudienceRequest', + ['audience', 'name'], + ); + request.audience.name = defaultValue1; + const expectedHeaderRequestParams = `audience.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Audience(), + ); + client.innerApiCalls.updateAudience = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateAudience( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IAudience | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateAudience as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAudience as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateAudience with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateAudienceRequest(), + ); + request.audience ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateAudienceRequest', + ['audience', 'name'], + ); + request.audience.name = defaultValue1; + const expectedHeaderRequestParams = `audience.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateAudience = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateAudience(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateAudience as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAudience as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateAudience with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateAudienceRequest(), + ); + request.audience ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateAudienceRequest', + ['audience', 'name'], + ); + request.audience.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateAudience(request), expectedError); + }); + }); + + describe('archiveAudience', () => { + it('invokes archiveAudience without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ArchiveAudienceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ArchiveAudienceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.archiveAudience = stubSimpleCall(expectedResponse); + const [response] = await client.archiveAudience(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.archiveAudience as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.archiveAudience as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes archiveAudience without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ArchiveAudienceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ArchiveAudienceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.archiveAudience = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.archiveAudience( + 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.archiveAudience as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.archiveAudience as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes archiveAudience with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ArchiveAudienceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ArchiveAudienceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.archiveAudience = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.archiveAudience(request), expectedError); + const actualRequest = ( + client.innerApiCalls.archiveAudience as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.archiveAudience as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes archiveAudience with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ArchiveAudienceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ArchiveAudienceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.archiveAudience(request), expectedError); + }); + }); + + describe('getSearchAds360Link', () => { + it('invokes getSearchAds360Link without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetSearchAds360LinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetSearchAds360LinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchAds360Link(), + ); + client.innerApiCalls.getSearchAds360Link = + stubSimpleCall(expectedResponse); + const [response] = await client.getSearchAds360Link(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSearchAds360Link as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSearchAds360Link as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getSearchAds360Link without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetSearchAds360LinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetSearchAds360LinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchAds360Link(), + ); + client.innerApiCalls.getSearchAds360Link = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getSearchAds360Link( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.ISearchAds360Link | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSearchAds360Link as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSearchAds360Link as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getSearchAds360Link with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetSearchAds360LinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetSearchAds360LinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getSearchAds360Link = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getSearchAds360Link(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getSearchAds360Link as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSearchAds360Link as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getSearchAds360Link with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetSearchAds360LinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetSearchAds360LinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getSearchAds360Link(request), expectedError); + }); + }); + + describe('createSearchAds360Link', () => { + it('invokes createSearchAds360Link without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateSearchAds360LinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateSearchAds360LinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchAds360Link(), + ); + client.innerApiCalls.createSearchAds360Link = + stubSimpleCall(expectedResponse); + const [response] = await client.createSearchAds360Link(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createSearchAds360Link as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createSearchAds360Link as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createSearchAds360Link without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateSearchAds360LinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateSearchAds360LinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchAds360Link(), + ); + client.innerApiCalls.createSearchAds360Link = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createSearchAds360Link( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.ISearchAds360Link | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createSearchAds360Link as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createSearchAds360Link as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createSearchAds360Link with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateSearchAds360LinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateSearchAds360LinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createSearchAds360Link = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createSearchAds360Link(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createSearchAds360Link as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createSearchAds360Link as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createSearchAds360Link with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateSearchAds360LinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateSearchAds360LinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createSearchAds360Link(request), + expectedError, + ); + }); + }); + + describe('deleteSearchAds360Link', () => { + it('invokes deleteSearchAds360Link without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteSearchAds360LinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteSearchAds360LinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteSearchAds360Link = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteSearchAds360Link(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteSearchAds360Link as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSearchAds360Link as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteSearchAds360Link without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteSearchAds360LinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteSearchAds360LinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteSearchAds360Link = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteSearchAds360Link( + 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.deleteSearchAds360Link as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSearchAds360Link as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteSearchAds360Link with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteSearchAds360LinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteSearchAds360LinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteSearchAds360Link = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteSearchAds360Link(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteSearchAds360Link as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSearchAds360Link as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteSearchAds360Link with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteSearchAds360LinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteSearchAds360LinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteSearchAds360Link(request), + expectedError, + ); + }); + }); + + describe('updateSearchAds360Link', () => { + it('invokes updateSearchAds360Link without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateSearchAds360LinkRequest(), + ); + request.searchAds_360Link ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateSearchAds360LinkRequest', + ['searchAds_360Link', 'name'], + ); + request.searchAds_360Link.name = defaultValue1; + const expectedHeaderRequestParams = `search_ads_360_link.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchAds360Link(), + ); + client.innerApiCalls.updateSearchAds360Link = + stubSimpleCall(expectedResponse); + const [response] = await client.updateSearchAds360Link(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateSearchAds360Link as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSearchAds360Link as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateSearchAds360Link without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateSearchAds360LinkRequest(), + ); + request.searchAds_360Link ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateSearchAds360LinkRequest', + ['searchAds_360Link', 'name'], + ); + request.searchAds_360Link.name = defaultValue1; + const expectedHeaderRequestParams = `search_ads_360_link.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchAds360Link(), + ); + client.innerApiCalls.updateSearchAds360Link = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateSearchAds360Link( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.ISearchAds360Link | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateSearchAds360Link as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSearchAds360Link as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateSearchAds360Link with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateSearchAds360LinkRequest(), + ); + request.searchAds_360Link ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateSearchAds360LinkRequest', + ['searchAds_360Link', 'name'], + ); + request.searchAds_360Link.name = defaultValue1; + const expectedHeaderRequestParams = `search_ads_360_link.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateSearchAds360Link = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateSearchAds360Link(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateSearchAds360Link as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSearchAds360Link as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateSearchAds360Link with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateSearchAds360LinkRequest(), + ); + request.searchAds_360Link ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateSearchAds360LinkRequest', + ['searchAds_360Link', 'name'], + ); + request.searchAds_360Link.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateSearchAds360Link(request), + expectedError, + ); + }); + }); + + describe('getAttributionSettings', () => { + it('invokes getAttributionSettings without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetAttributionSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetAttributionSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AttributionSettings(), + ); + client.innerApiCalls.getAttributionSettings = + stubSimpleCall(expectedResponse); + const [response] = await client.getAttributionSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAttributionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAttributionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getAttributionSettings without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetAttributionSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetAttributionSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AttributionSettings(), + ); + client.innerApiCalls.getAttributionSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getAttributionSettings( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IAttributionSettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAttributionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAttributionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getAttributionSettings with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetAttributionSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetAttributionSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getAttributionSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getAttributionSettings(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getAttributionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAttributionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getAttributionSettings with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetAttributionSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetAttributionSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getAttributionSettings(request), + expectedError, + ); + }); + }); + + describe('updateAttributionSettings', () => { + it('invokes updateAttributionSettings without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateAttributionSettingsRequest(), + ); + request.attributionSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateAttributionSettingsRequest', + ['attributionSettings', 'name'], + ); + request.attributionSettings.name = defaultValue1; + const expectedHeaderRequestParams = `attribution_settings.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AttributionSettings(), + ); + client.innerApiCalls.updateAttributionSettings = + stubSimpleCall(expectedResponse); + const [response] = await client.updateAttributionSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateAttributionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAttributionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateAttributionSettings without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateAttributionSettingsRequest(), + ); + request.attributionSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateAttributionSettingsRequest', + ['attributionSettings', 'name'], + ); + request.attributionSettings.name = defaultValue1; + const expectedHeaderRequestParams = `attribution_settings.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AttributionSettings(), + ); + client.innerApiCalls.updateAttributionSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateAttributionSettings( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IAttributionSettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateAttributionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAttributionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateAttributionSettings with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateAttributionSettingsRequest(), + ); + request.attributionSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateAttributionSettingsRequest', + ['attributionSettings', 'name'], + ); + request.attributionSettings.name = defaultValue1; + const expectedHeaderRequestParams = `attribution_settings.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateAttributionSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateAttributionSettings(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateAttributionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAttributionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateAttributionSettings with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateAttributionSettingsRequest(), + ); + request.attributionSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateAttributionSettingsRequest', + ['attributionSettings', 'name'], + ); + request.attributionSettings.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateAttributionSettings(request), + expectedError, + ); + }); + }); + + describe('runAccessReport', () => { + it('invokes runAccessReport without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.RunAccessReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.RunAccessReportRequest', + ['entity'], + ); + request.entity = defaultValue1; + const expectedHeaderRequestParams = `entity=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.RunAccessReportResponse(), + ); + client.innerApiCalls.runAccessReport = stubSimpleCall(expectedResponse); + const [response] = await client.runAccessReport(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runAccessReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runAccessReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes runAccessReport without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.RunAccessReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.RunAccessReportRequest', + ['entity'], + ); + request.entity = defaultValue1; + const expectedHeaderRequestParams = `entity=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.RunAccessReportResponse(), + ); + client.innerApiCalls.runAccessReport = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.runAccessReport( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IRunAccessReportResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runAccessReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runAccessReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes runAccessReport with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.RunAccessReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.RunAccessReportRequest', + ['entity'], + ); + request.entity = defaultValue1; + const expectedHeaderRequestParams = `entity=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.runAccessReport = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.runAccessReport(request), expectedError); + const actualRequest = ( + client.innerApiCalls.runAccessReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runAccessReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes runAccessReport with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.RunAccessReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.RunAccessReportRequest', + ['entity'], + ); + request.entity = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.runAccessReport(request), expectedError); + }); + }); + + describe('createAccessBinding', () => { + it('invokes createAccessBinding without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateAccessBindingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateAccessBindingRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccessBinding(), + ); + client.innerApiCalls.createAccessBinding = + stubSimpleCall(expectedResponse); + const [response] = await client.createAccessBinding(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createAccessBinding as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createAccessBinding as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createAccessBinding without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateAccessBindingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateAccessBindingRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccessBinding(), + ); + client.innerApiCalls.createAccessBinding = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createAccessBinding( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IAccessBinding | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createAccessBinding as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createAccessBinding as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createAccessBinding with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateAccessBindingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateAccessBindingRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createAccessBinding = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createAccessBinding(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createAccessBinding as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createAccessBinding as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createAccessBinding with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateAccessBindingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateAccessBindingRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createAccessBinding(request), expectedError); + }); + }); + + describe('getAccessBinding', () => { + it('invokes getAccessBinding without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetAccessBindingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetAccessBindingRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccessBinding(), + ); + client.innerApiCalls.getAccessBinding = stubSimpleCall(expectedResponse); + const [response] = await client.getAccessBinding(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAccessBinding as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAccessBinding as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getAccessBinding without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetAccessBindingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetAccessBindingRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccessBinding(), + ); + client.innerApiCalls.getAccessBinding = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getAccessBinding( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IAccessBinding | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAccessBinding as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAccessBinding as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getAccessBinding with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetAccessBindingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetAccessBindingRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getAccessBinding = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getAccessBinding(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getAccessBinding as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAccessBinding as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getAccessBinding with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetAccessBindingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetAccessBindingRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getAccessBinding(request), expectedError); + }); + }); + + describe('updateAccessBinding', () => { + it('invokes updateAccessBinding without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateAccessBindingRequest(), + ); + request.accessBinding ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateAccessBindingRequest', + ['accessBinding', 'name'], + ); + request.accessBinding.name = defaultValue1; + const expectedHeaderRequestParams = `access_binding.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccessBinding(), + ); + client.innerApiCalls.updateAccessBinding = + stubSimpleCall(expectedResponse); + const [response] = await client.updateAccessBinding(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateAccessBinding as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAccessBinding as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateAccessBinding without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateAccessBindingRequest(), + ); + request.accessBinding ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateAccessBindingRequest', + ['accessBinding', 'name'], + ); + request.accessBinding.name = defaultValue1; + const expectedHeaderRequestParams = `access_binding.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccessBinding(), + ); + client.innerApiCalls.updateAccessBinding = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateAccessBinding( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IAccessBinding | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateAccessBinding as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAccessBinding as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateAccessBinding with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateAccessBindingRequest(), + ); + request.accessBinding ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateAccessBindingRequest', + ['accessBinding', 'name'], + ); + request.accessBinding.name = defaultValue1; + const expectedHeaderRequestParams = `access_binding.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateAccessBinding = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateAccessBinding(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateAccessBinding as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAccessBinding as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateAccessBinding with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateAccessBindingRequest(), + ); + request.accessBinding ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateAccessBindingRequest', + ['accessBinding', 'name'], + ); + request.accessBinding.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateAccessBinding(request), expectedError); + }); + }); + + describe('deleteAccessBinding', () => { + it('invokes deleteAccessBinding without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteAccessBindingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteAccessBindingRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteAccessBinding = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteAccessBinding(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteAccessBinding as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteAccessBinding as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteAccessBinding without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteAccessBindingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteAccessBindingRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteAccessBinding = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteAccessBinding( + 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.deleteAccessBinding as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteAccessBinding as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteAccessBinding with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteAccessBindingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteAccessBindingRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteAccessBinding = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteAccessBinding(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteAccessBinding as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteAccessBinding as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteAccessBinding with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteAccessBindingRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteAccessBindingRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteAccessBinding(request), expectedError); + }); + }); + + describe('batchCreateAccessBindings', () => { + it('invokes batchCreateAccessBindings without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BatchCreateAccessBindingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.BatchCreateAccessBindingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BatchCreateAccessBindingsResponse(), + ); + client.innerApiCalls.batchCreateAccessBindings = + stubSimpleCall(expectedResponse); + const [response] = await client.batchCreateAccessBindings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchCreateAccessBindings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchCreateAccessBindings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchCreateAccessBindings without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BatchCreateAccessBindingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.BatchCreateAccessBindingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BatchCreateAccessBindingsResponse(), + ); + client.innerApiCalls.batchCreateAccessBindings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchCreateAccessBindings( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IBatchCreateAccessBindingsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchCreateAccessBindings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchCreateAccessBindings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchCreateAccessBindings with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BatchCreateAccessBindingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.BatchCreateAccessBindingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchCreateAccessBindings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.batchCreateAccessBindings(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.batchCreateAccessBindings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchCreateAccessBindings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchCreateAccessBindings with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BatchCreateAccessBindingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.BatchCreateAccessBindingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.batchCreateAccessBindings(request), + expectedError, + ); + }); + }); + + describe('batchGetAccessBindings', () => { + it('invokes batchGetAccessBindings without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BatchGetAccessBindingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.BatchGetAccessBindingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BatchGetAccessBindingsResponse(), + ); + client.innerApiCalls.batchGetAccessBindings = + stubSimpleCall(expectedResponse); + const [response] = await client.batchGetAccessBindings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchGetAccessBindings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchGetAccessBindings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchGetAccessBindings without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BatchGetAccessBindingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.BatchGetAccessBindingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BatchGetAccessBindingsResponse(), + ); + client.innerApiCalls.batchGetAccessBindings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchGetAccessBindings( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IBatchGetAccessBindingsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchGetAccessBindings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchGetAccessBindings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchGetAccessBindings with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BatchGetAccessBindingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.BatchGetAccessBindingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchGetAccessBindings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.batchGetAccessBindings(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.batchGetAccessBindings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchGetAccessBindings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchGetAccessBindings with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BatchGetAccessBindingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.BatchGetAccessBindingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.batchGetAccessBindings(request), + expectedError, + ); + }); + }); + + describe('batchUpdateAccessBindings', () => { + it('invokes batchUpdateAccessBindings without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BatchUpdateAccessBindingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.BatchUpdateAccessBindingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BatchUpdateAccessBindingsResponse(), + ); + client.innerApiCalls.batchUpdateAccessBindings = + stubSimpleCall(expectedResponse); + const [response] = await client.batchUpdateAccessBindings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchUpdateAccessBindings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchUpdateAccessBindings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchUpdateAccessBindings without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BatchUpdateAccessBindingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.BatchUpdateAccessBindingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BatchUpdateAccessBindingsResponse(), + ); + client.innerApiCalls.batchUpdateAccessBindings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchUpdateAccessBindings( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IBatchUpdateAccessBindingsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchUpdateAccessBindings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchUpdateAccessBindings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchUpdateAccessBindings with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BatchUpdateAccessBindingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.BatchUpdateAccessBindingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchUpdateAccessBindings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.batchUpdateAccessBindings(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.batchUpdateAccessBindings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchUpdateAccessBindings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchUpdateAccessBindings with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BatchUpdateAccessBindingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.BatchUpdateAccessBindingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.batchUpdateAccessBindings(request), + expectedError, + ); + }); + }); + + describe('batchDeleteAccessBindings', () => { + it('invokes batchDeleteAccessBindings without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BatchDeleteAccessBindingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.BatchDeleteAccessBindingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.batchDeleteAccessBindings = + stubSimpleCall(expectedResponse); + const [response] = await client.batchDeleteAccessBindings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchDeleteAccessBindings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchDeleteAccessBindings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchDeleteAccessBindings without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BatchDeleteAccessBindingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.BatchDeleteAccessBindingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.batchDeleteAccessBindings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchDeleteAccessBindings( + 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.batchDeleteAccessBindings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchDeleteAccessBindings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchDeleteAccessBindings with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BatchDeleteAccessBindingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.BatchDeleteAccessBindingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchDeleteAccessBindings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.batchDeleteAccessBindings(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.batchDeleteAccessBindings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchDeleteAccessBindings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes batchDeleteAccessBindings with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BatchDeleteAccessBindingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.BatchDeleteAccessBindingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.batchDeleteAccessBindings(request), + expectedError, + ); + }); + }); + + describe('getExpandedDataSet', () => { + it('invokes getExpandedDataSet without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetExpandedDataSetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetExpandedDataSetRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ExpandedDataSet(), + ); + client.innerApiCalls.getExpandedDataSet = + stubSimpleCall(expectedResponse); + const [response] = await client.getExpandedDataSet(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getExpandedDataSet as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getExpandedDataSet as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getExpandedDataSet without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetExpandedDataSetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetExpandedDataSetRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ExpandedDataSet(), + ); + client.innerApiCalls.getExpandedDataSet = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getExpandedDataSet( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IExpandedDataSet | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getExpandedDataSet as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getExpandedDataSet as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getExpandedDataSet with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetExpandedDataSetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetExpandedDataSetRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getExpandedDataSet = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getExpandedDataSet(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getExpandedDataSet as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getExpandedDataSet as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getExpandedDataSet with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetExpandedDataSetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetExpandedDataSetRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getExpandedDataSet(request), expectedError); + }); + }); + + describe('createExpandedDataSet', () => { + it('invokes createExpandedDataSet without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateExpandedDataSetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateExpandedDataSetRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ExpandedDataSet(), + ); + client.innerApiCalls.createExpandedDataSet = + stubSimpleCall(expectedResponse); + const [response] = await client.createExpandedDataSet(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createExpandedDataSet as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createExpandedDataSet as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createExpandedDataSet without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateExpandedDataSetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateExpandedDataSetRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ExpandedDataSet(), + ); + client.innerApiCalls.createExpandedDataSet = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createExpandedDataSet( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IExpandedDataSet | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createExpandedDataSet as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createExpandedDataSet as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createExpandedDataSet with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateExpandedDataSetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateExpandedDataSetRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createExpandedDataSet = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createExpandedDataSet(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createExpandedDataSet as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createExpandedDataSet as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createExpandedDataSet with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateExpandedDataSetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateExpandedDataSetRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createExpandedDataSet(request), + expectedError, + ); + }); + }); + + describe('updateExpandedDataSet', () => { + it('invokes updateExpandedDataSet without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateExpandedDataSetRequest(), + ); + request.expandedDataSet ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateExpandedDataSetRequest', + ['expandedDataSet', 'name'], + ); + request.expandedDataSet.name = defaultValue1; + const expectedHeaderRequestParams = `expanded_data_set.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ExpandedDataSet(), + ); + client.innerApiCalls.updateExpandedDataSet = + stubSimpleCall(expectedResponse); + const [response] = await client.updateExpandedDataSet(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateExpandedDataSet as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateExpandedDataSet as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateExpandedDataSet without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateExpandedDataSetRequest(), + ); + request.expandedDataSet ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateExpandedDataSetRequest', + ['expandedDataSet', 'name'], + ); + request.expandedDataSet.name = defaultValue1; + const expectedHeaderRequestParams = `expanded_data_set.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ExpandedDataSet(), + ); + client.innerApiCalls.updateExpandedDataSet = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateExpandedDataSet( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IExpandedDataSet | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateExpandedDataSet as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateExpandedDataSet as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateExpandedDataSet with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateExpandedDataSetRequest(), + ); + request.expandedDataSet ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateExpandedDataSetRequest', + ['expandedDataSet', 'name'], + ); + request.expandedDataSet.name = defaultValue1; + const expectedHeaderRequestParams = `expanded_data_set.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateExpandedDataSet = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateExpandedDataSet(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateExpandedDataSet as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateExpandedDataSet as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateExpandedDataSet with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateExpandedDataSetRequest(), + ); + request.expandedDataSet ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateExpandedDataSetRequest', + ['expandedDataSet', 'name'], + ); + request.expandedDataSet.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateExpandedDataSet(request), + expectedError, + ); + }); + }); + + describe('deleteExpandedDataSet', () => { + it('invokes deleteExpandedDataSet without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteExpandedDataSetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteExpandedDataSetRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteExpandedDataSet = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteExpandedDataSet(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteExpandedDataSet as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteExpandedDataSet as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteExpandedDataSet without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteExpandedDataSetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteExpandedDataSetRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteExpandedDataSet = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteExpandedDataSet( + 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.deleteExpandedDataSet as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteExpandedDataSet as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteExpandedDataSet with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteExpandedDataSetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteExpandedDataSetRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteExpandedDataSet = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteExpandedDataSet(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteExpandedDataSet as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteExpandedDataSet as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteExpandedDataSet with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteExpandedDataSetRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteExpandedDataSetRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteExpandedDataSet(request), + expectedError, + ); + }); + }); + + describe('getChannelGroup', () => { + it('invokes getChannelGroup without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetChannelGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetChannelGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChannelGroup(), + ); + client.innerApiCalls.getChannelGroup = stubSimpleCall(expectedResponse); + const [response] = await client.getChannelGroup(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getChannelGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getChannelGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getChannelGroup without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetChannelGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetChannelGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChannelGroup(), + ); + client.innerApiCalls.getChannelGroup = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getChannelGroup( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IChannelGroup | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getChannelGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getChannelGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getChannelGroup with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetChannelGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetChannelGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getChannelGroup = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getChannelGroup(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getChannelGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getChannelGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getChannelGroup with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetChannelGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetChannelGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getChannelGroup(request), expectedError); + }); + }); + + describe('createChannelGroup', () => { + it('invokes createChannelGroup without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateChannelGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateChannelGroupRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChannelGroup(), + ); + client.innerApiCalls.createChannelGroup = + stubSimpleCall(expectedResponse); + const [response] = await client.createChannelGroup(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createChannelGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createChannelGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createChannelGroup without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateChannelGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateChannelGroupRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChannelGroup(), + ); + client.innerApiCalls.createChannelGroup = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createChannelGroup( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IChannelGroup | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createChannelGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createChannelGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createChannelGroup with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateChannelGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateChannelGroupRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createChannelGroup = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createChannelGroup(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createChannelGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createChannelGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createChannelGroup with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateChannelGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateChannelGroupRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createChannelGroup(request), expectedError); + }); + }); + + describe('updateChannelGroup', () => { + it('invokes updateChannelGroup without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateChannelGroupRequest(), + ); + request.channelGroup ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateChannelGroupRequest', + ['channelGroup', 'name'], + ); + request.channelGroup.name = defaultValue1; + const expectedHeaderRequestParams = `channel_group.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChannelGroup(), + ); + client.innerApiCalls.updateChannelGroup = + stubSimpleCall(expectedResponse); + const [response] = await client.updateChannelGroup(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateChannelGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateChannelGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateChannelGroup without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateChannelGroupRequest(), + ); + request.channelGroup ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateChannelGroupRequest', + ['channelGroup', 'name'], + ); + request.channelGroup.name = defaultValue1; + const expectedHeaderRequestParams = `channel_group.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChannelGroup(), + ); + client.innerApiCalls.updateChannelGroup = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateChannelGroup( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IChannelGroup | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateChannelGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateChannelGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateChannelGroup with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateChannelGroupRequest(), + ); + request.channelGroup ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateChannelGroupRequest', + ['channelGroup', 'name'], + ); + request.channelGroup.name = defaultValue1; + const expectedHeaderRequestParams = `channel_group.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateChannelGroup = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateChannelGroup(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateChannelGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateChannelGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateChannelGroup with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateChannelGroupRequest(), + ); + request.channelGroup ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateChannelGroupRequest', + ['channelGroup', 'name'], + ); + request.channelGroup.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateChannelGroup(request), expectedError); + }); + }); + + describe('deleteChannelGroup', () => { + it('invokes deleteChannelGroup without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteChannelGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteChannelGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteChannelGroup = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteChannelGroup(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteChannelGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteChannelGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteChannelGroup without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteChannelGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteChannelGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteChannelGroup = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteChannelGroup( + 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.deleteChannelGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteChannelGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteChannelGroup with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteChannelGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteChannelGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteChannelGroup = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteChannelGroup(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteChannelGroup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteChannelGroup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteChannelGroup with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteChannelGroupRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteChannelGroupRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteChannelGroup(request), expectedError); + }); + }); + + describe('createBigQueryLink', () => { + it('invokes createBigQueryLink without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateBigQueryLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateBigQueryLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BigQueryLink(), + ); + client.innerApiCalls.createBigQueryLink = + stubSimpleCall(expectedResponse); + const [response] = await client.createBigQueryLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createBigQueryLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBigQueryLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createBigQueryLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateBigQueryLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateBigQueryLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BigQueryLink(), + ); + client.innerApiCalls.createBigQueryLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createBigQueryLink( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IBigQueryLink | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createBigQueryLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBigQueryLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createBigQueryLink with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateBigQueryLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateBigQueryLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createBigQueryLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createBigQueryLink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createBigQueryLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBigQueryLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createBigQueryLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateBigQueryLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateBigQueryLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createBigQueryLink(request), expectedError); + }); + }); + + describe('getBigQueryLink', () => { + it('invokes getBigQueryLink without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetBigQueryLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetBigQueryLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BigQueryLink(), + ); + client.innerApiCalls.getBigQueryLink = stubSimpleCall(expectedResponse); + const [response] = await client.getBigQueryLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBigQueryLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBigQueryLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getBigQueryLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetBigQueryLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetBigQueryLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BigQueryLink(), + ); + client.innerApiCalls.getBigQueryLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getBigQueryLink( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IBigQueryLink | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBigQueryLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBigQueryLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getBigQueryLink with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetBigQueryLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetBigQueryLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getBigQueryLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getBigQueryLink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getBigQueryLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBigQueryLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getBigQueryLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetBigQueryLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetBigQueryLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getBigQueryLink(request), expectedError); + }); + }); + + describe('deleteBigQueryLink', () => { + it('invokes deleteBigQueryLink without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteBigQueryLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteBigQueryLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteBigQueryLink = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteBigQueryLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBigQueryLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBigQueryLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteBigQueryLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteBigQueryLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteBigQueryLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteBigQueryLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteBigQueryLink( + 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.deleteBigQueryLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBigQueryLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteBigQueryLink with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteBigQueryLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteBigQueryLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteBigQueryLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteBigQueryLink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteBigQueryLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBigQueryLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteBigQueryLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteBigQueryLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteBigQueryLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteBigQueryLink(request), expectedError); + }); + }); + + describe('updateBigQueryLink', () => { + it('invokes updateBigQueryLink without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateBigQueryLinkRequest(), + ); + request.bigqueryLink ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateBigQueryLinkRequest', + ['bigqueryLink', 'name'], + ); + request.bigqueryLink.name = defaultValue1; + const expectedHeaderRequestParams = `bigquery_link.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BigQueryLink(), + ); + client.innerApiCalls.updateBigQueryLink = + stubSimpleCall(expectedResponse); + const [response] = await client.updateBigQueryLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateBigQueryLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBigQueryLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateBigQueryLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateBigQueryLinkRequest(), + ); + request.bigqueryLink ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateBigQueryLinkRequest', + ['bigqueryLink', 'name'], + ); + request.bigqueryLink.name = defaultValue1; + const expectedHeaderRequestParams = `bigquery_link.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BigQueryLink(), + ); + client.innerApiCalls.updateBigQueryLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateBigQueryLink( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IBigQueryLink | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateBigQueryLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBigQueryLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateBigQueryLink with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateBigQueryLinkRequest(), + ); + request.bigqueryLink ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateBigQueryLinkRequest', + ['bigqueryLink', 'name'], + ); + request.bigqueryLink.name = defaultValue1; + const expectedHeaderRequestParams = `bigquery_link.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateBigQueryLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateBigQueryLink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateBigQueryLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBigQueryLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateBigQueryLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateBigQueryLinkRequest(), + ); + request.bigqueryLink ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateBigQueryLinkRequest', + ['bigqueryLink', 'name'], + ); + request.bigqueryLink.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateBigQueryLink(request), expectedError); + }); + }); + + describe('getEnhancedMeasurementSettings', () => { + it('invokes getEnhancedMeasurementSettings without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetEnhancedMeasurementSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetEnhancedMeasurementSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EnhancedMeasurementSettings(), + ); + client.innerApiCalls.getEnhancedMeasurementSettings = + stubSimpleCall(expectedResponse); + const [response] = await client.getEnhancedMeasurementSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getEnhancedMeasurementSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getEnhancedMeasurementSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getEnhancedMeasurementSettings without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetEnhancedMeasurementSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetEnhancedMeasurementSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EnhancedMeasurementSettings(), + ); + client.innerApiCalls.getEnhancedMeasurementSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getEnhancedMeasurementSettings( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getEnhancedMeasurementSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getEnhancedMeasurementSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getEnhancedMeasurementSettings with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetEnhancedMeasurementSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetEnhancedMeasurementSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getEnhancedMeasurementSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getEnhancedMeasurementSettings(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getEnhancedMeasurementSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getEnhancedMeasurementSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getEnhancedMeasurementSettings with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetEnhancedMeasurementSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetEnhancedMeasurementSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getEnhancedMeasurementSettings(request), + expectedError, + ); + }); + }); + + describe('updateEnhancedMeasurementSettings', () => { + it('invokes updateEnhancedMeasurementSettings without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateEnhancedMeasurementSettingsRequest(), + ); + request.enhancedMeasurementSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateEnhancedMeasurementSettingsRequest', + ['enhancedMeasurementSettings', 'name'], + ); + request.enhancedMeasurementSettings.name = defaultValue1; + const expectedHeaderRequestParams = `enhanced_measurement_settings.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EnhancedMeasurementSettings(), + ); + client.innerApiCalls.updateEnhancedMeasurementSettings = + stubSimpleCall(expectedResponse); + const [response] = + await client.updateEnhancedMeasurementSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateEnhancedMeasurementSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateEnhancedMeasurementSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateEnhancedMeasurementSettings without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateEnhancedMeasurementSettingsRequest(), + ); + request.enhancedMeasurementSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateEnhancedMeasurementSettingsRequest', + ['enhancedMeasurementSettings', 'name'], + ); + request.enhancedMeasurementSettings.name = defaultValue1; + const expectedHeaderRequestParams = `enhanced_measurement_settings.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EnhancedMeasurementSettings(), + ); + client.innerApiCalls.updateEnhancedMeasurementSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateEnhancedMeasurementSettings( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IEnhancedMeasurementSettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateEnhancedMeasurementSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateEnhancedMeasurementSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateEnhancedMeasurementSettings with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateEnhancedMeasurementSettingsRequest(), + ); + request.enhancedMeasurementSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateEnhancedMeasurementSettingsRequest', + ['enhancedMeasurementSettings', 'name'], + ); + request.enhancedMeasurementSettings.name = defaultValue1; + const expectedHeaderRequestParams = `enhanced_measurement_settings.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateEnhancedMeasurementSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateEnhancedMeasurementSettings(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateEnhancedMeasurementSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateEnhancedMeasurementSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateEnhancedMeasurementSettings with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateEnhancedMeasurementSettingsRequest(), + ); + request.enhancedMeasurementSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateEnhancedMeasurementSettingsRequest', + ['enhancedMeasurementSettings', 'name'], + ); + request.enhancedMeasurementSettings.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateEnhancedMeasurementSettings(request), + expectedError, + ); + }); + }); + + describe('getAdSenseLink', () => { + it('invokes getAdSenseLink without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetAdSenseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetAdSenseLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AdSenseLink(), + ); + client.innerApiCalls.getAdSenseLink = stubSimpleCall(expectedResponse); + const [response] = await client.getAdSenseLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAdSenseLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAdSenseLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getAdSenseLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetAdSenseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetAdSenseLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AdSenseLink(), + ); + client.innerApiCalls.getAdSenseLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getAdSenseLink( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IAdSenseLink | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAdSenseLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAdSenseLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getAdSenseLink with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetAdSenseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetAdSenseLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getAdSenseLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getAdSenseLink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getAdSenseLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAdSenseLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getAdSenseLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetAdSenseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetAdSenseLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getAdSenseLink(request), expectedError); + }); + }); + + describe('createAdSenseLink', () => { + it('invokes createAdSenseLink without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateAdSenseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateAdSenseLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AdSenseLink(), + ); + client.innerApiCalls.createAdSenseLink = stubSimpleCall(expectedResponse); + const [response] = await client.createAdSenseLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createAdSenseLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createAdSenseLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createAdSenseLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateAdSenseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateAdSenseLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AdSenseLink(), + ); + client.innerApiCalls.createAdSenseLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createAdSenseLink( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IAdSenseLink | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createAdSenseLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createAdSenseLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createAdSenseLink with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateAdSenseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateAdSenseLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createAdSenseLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createAdSenseLink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createAdSenseLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createAdSenseLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createAdSenseLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateAdSenseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateAdSenseLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createAdSenseLink(request), expectedError); + }); + }); + + describe('deleteAdSenseLink', () => { + it('invokes deleteAdSenseLink without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteAdSenseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteAdSenseLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteAdSenseLink = stubSimpleCall(expectedResponse); + const [response] = await client.deleteAdSenseLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteAdSenseLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteAdSenseLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteAdSenseLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteAdSenseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteAdSenseLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteAdSenseLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteAdSenseLink( + 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.deleteAdSenseLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteAdSenseLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteAdSenseLink with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteAdSenseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteAdSenseLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteAdSenseLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteAdSenseLink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteAdSenseLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteAdSenseLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteAdSenseLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteAdSenseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteAdSenseLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteAdSenseLink(request), expectedError); + }); + }); + + describe('getEventCreateRule', () => { + it('invokes getEventCreateRule without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetEventCreateRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetEventCreateRuleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventCreateRule(), + ); + client.innerApiCalls.getEventCreateRule = + stubSimpleCall(expectedResponse); + const [response] = await client.getEventCreateRule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getEventCreateRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getEventCreateRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getEventCreateRule without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetEventCreateRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetEventCreateRuleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventCreateRule(), + ); + client.innerApiCalls.getEventCreateRule = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getEventCreateRule( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IEventCreateRule | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getEventCreateRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getEventCreateRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getEventCreateRule with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetEventCreateRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetEventCreateRuleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getEventCreateRule = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getEventCreateRule(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getEventCreateRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getEventCreateRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getEventCreateRule with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetEventCreateRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetEventCreateRuleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getEventCreateRule(request), expectedError); + }); + }); + + describe('createEventCreateRule', () => { + it('invokes createEventCreateRule without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateEventCreateRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateEventCreateRuleRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventCreateRule(), + ); + client.innerApiCalls.createEventCreateRule = + stubSimpleCall(expectedResponse); + const [response] = await client.createEventCreateRule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createEventCreateRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createEventCreateRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createEventCreateRule without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateEventCreateRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateEventCreateRuleRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventCreateRule(), + ); + client.innerApiCalls.createEventCreateRule = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createEventCreateRule( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IEventCreateRule | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createEventCreateRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createEventCreateRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createEventCreateRule with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateEventCreateRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateEventCreateRuleRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createEventCreateRule = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createEventCreateRule(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createEventCreateRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createEventCreateRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createEventCreateRule with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateEventCreateRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateEventCreateRuleRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createEventCreateRule(request), + expectedError, + ); + }); + }); + + describe('updateEventCreateRule', () => { + it('invokes updateEventCreateRule without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateEventCreateRuleRequest(), + ); + request.eventCreateRule ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateEventCreateRuleRequest', + ['eventCreateRule', 'name'], + ); + request.eventCreateRule.name = defaultValue1; + const expectedHeaderRequestParams = `event_create_rule.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventCreateRule(), + ); + client.innerApiCalls.updateEventCreateRule = + stubSimpleCall(expectedResponse); + const [response] = await client.updateEventCreateRule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateEventCreateRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateEventCreateRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateEventCreateRule without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateEventCreateRuleRequest(), + ); + request.eventCreateRule ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateEventCreateRuleRequest', + ['eventCreateRule', 'name'], + ); + request.eventCreateRule.name = defaultValue1; + const expectedHeaderRequestParams = `event_create_rule.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventCreateRule(), + ); + client.innerApiCalls.updateEventCreateRule = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateEventCreateRule( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IEventCreateRule | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateEventCreateRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateEventCreateRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateEventCreateRule with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateEventCreateRuleRequest(), + ); + request.eventCreateRule ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateEventCreateRuleRequest', + ['eventCreateRule', 'name'], + ); + request.eventCreateRule.name = defaultValue1; + const expectedHeaderRequestParams = `event_create_rule.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateEventCreateRule = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateEventCreateRule(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateEventCreateRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateEventCreateRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateEventCreateRule with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateEventCreateRuleRequest(), + ); + request.eventCreateRule ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateEventCreateRuleRequest', + ['eventCreateRule', 'name'], + ); + request.eventCreateRule.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateEventCreateRule(request), + expectedError, + ); + }); + }); + + describe('deleteEventCreateRule', () => { + it('invokes deleteEventCreateRule without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteEventCreateRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteEventCreateRuleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteEventCreateRule = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteEventCreateRule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteEventCreateRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteEventCreateRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteEventCreateRule without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteEventCreateRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteEventCreateRuleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteEventCreateRule = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteEventCreateRule( + 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.deleteEventCreateRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteEventCreateRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteEventCreateRule with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteEventCreateRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteEventCreateRuleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteEventCreateRule = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteEventCreateRule(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteEventCreateRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteEventCreateRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteEventCreateRule with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteEventCreateRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteEventCreateRuleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteEventCreateRule(request), + expectedError, + ); + }); + }); + + describe('getEventEditRule', () => { + it('invokes getEventEditRule without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetEventEditRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetEventEditRuleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventEditRule(), + ); + client.innerApiCalls.getEventEditRule = stubSimpleCall(expectedResponse); + const [response] = await client.getEventEditRule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getEventEditRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getEventEditRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getEventEditRule without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetEventEditRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetEventEditRuleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventEditRule(), + ); + client.innerApiCalls.getEventEditRule = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getEventEditRule( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IEventEditRule | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getEventEditRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getEventEditRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getEventEditRule with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetEventEditRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetEventEditRuleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getEventEditRule = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getEventEditRule(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getEventEditRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getEventEditRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getEventEditRule with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetEventEditRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetEventEditRuleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getEventEditRule(request), expectedError); + }); + }); + + describe('createEventEditRule', () => { + it('invokes createEventEditRule without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateEventEditRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateEventEditRuleRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventEditRule(), + ); + client.innerApiCalls.createEventEditRule = + stubSimpleCall(expectedResponse); + const [response] = await client.createEventEditRule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createEventEditRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createEventEditRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createEventEditRule without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateEventEditRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateEventEditRuleRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventEditRule(), + ); + client.innerApiCalls.createEventEditRule = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createEventEditRule( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IEventEditRule | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createEventEditRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createEventEditRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createEventEditRule with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateEventEditRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateEventEditRuleRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createEventEditRule = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createEventEditRule(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createEventEditRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createEventEditRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createEventEditRule with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateEventEditRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateEventEditRuleRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createEventEditRule(request), expectedError); + }); + }); + + describe('updateEventEditRule', () => { + it('invokes updateEventEditRule without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateEventEditRuleRequest(), + ); + request.eventEditRule ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateEventEditRuleRequest', + ['eventEditRule', 'name'], + ); + request.eventEditRule.name = defaultValue1; + const expectedHeaderRequestParams = `event_edit_rule.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventEditRule(), + ); + client.innerApiCalls.updateEventEditRule = + stubSimpleCall(expectedResponse); + const [response] = await client.updateEventEditRule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateEventEditRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateEventEditRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateEventEditRule without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateEventEditRuleRequest(), + ); + request.eventEditRule ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateEventEditRuleRequest', + ['eventEditRule', 'name'], + ); + request.eventEditRule.name = defaultValue1; + const expectedHeaderRequestParams = `event_edit_rule.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventEditRule(), + ); + client.innerApiCalls.updateEventEditRule = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateEventEditRule( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IEventEditRule | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateEventEditRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateEventEditRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateEventEditRule with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateEventEditRuleRequest(), + ); + request.eventEditRule ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateEventEditRuleRequest', + ['eventEditRule', 'name'], + ); + request.eventEditRule.name = defaultValue1; + const expectedHeaderRequestParams = `event_edit_rule.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateEventEditRule = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateEventEditRule(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateEventEditRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateEventEditRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateEventEditRule with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateEventEditRuleRequest(), + ); + request.eventEditRule ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateEventEditRuleRequest', + ['eventEditRule', 'name'], + ); + request.eventEditRule.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateEventEditRule(request), expectedError); + }); + }); + + describe('deleteEventEditRule', () => { + it('invokes deleteEventEditRule without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteEventEditRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteEventEditRuleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteEventEditRule = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteEventEditRule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteEventEditRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteEventEditRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteEventEditRule without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteEventEditRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteEventEditRuleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteEventEditRule = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteEventEditRule( + 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.deleteEventEditRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteEventEditRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteEventEditRule with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteEventEditRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteEventEditRuleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteEventEditRule = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteEventEditRule(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteEventEditRule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteEventEditRule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteEventEditRule with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteEventEditRuleRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteEventEditRuleRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteEventEditRule(request), expectedError); + }); + }); + + describe('reorderEventEditRules', () => { + it('invokes reorderEventEditRules without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReorderEventEditRulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ReorderEventEditRulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.reorderEventEditRules = + stubSimpleCall(expectedResponse); + const [response] = await client.reorderEventEditRules(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.reorderEventEditRules as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.reorderEventEditRules as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes reorderEventEditRules without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReorderEventEditRulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ReorderEventEditRulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.reorderEventEditRules = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.reorderEventEditRules( + 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.reorderEventEditRules as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.reorderEventEditRules as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes reorderEventEditRules with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReorderEventEditRulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ReorderEventEditRulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.reorderEventEditRules = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.reorderEventEditRules(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.reorderEventEditRules as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.reorderEventEditRules as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes reorderEventEditRules with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReorderEventEditRulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ReorderEventEditRulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.reorderEventEditRules(request), + expectedError, + ); + }); + }); + + describe('updateDataRedactionSettings', () => { + it('invokes updateDataRedactionSettings without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateDataRedactionSettingsRequest(), + ); + request.dataRedactionSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateDataRedactionSettingsRequest', + ['dataRedactionSettings', 'name'], + ); + request.dataRedactionSettings.name = defaultValue1; + const expectedHeaderRequestParams = `data_redaction_settings.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataRedactionSettings(), + ); + client.innerApiCalls.updateDataRedactionSettings = + stubSimpleCall(expectedResponse); + const [response] = await client.updateDataRedactionSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDataRedactionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDataRedactionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDataRedactionSettings without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateDataRedactionSettingsRequest(), + ); + request.dataRedactionSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateDataRedactionSettingsRequest', + ['dataRedactionSettings', 'name'], + ); + request.dataRedactionSettings.name = defaultValue1; + const expectedHeaderRequestParams = `data_redaction_settings.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataRedactionSettings(), + ); + client.innerApiCalls.updateDataRedactionSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateDataRedactionSettings( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IDataRedactionSettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDataRedactionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDataRedactionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDataRedactionSettings with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateDataRedactionSettingsRequest(), + ); + request.dataRedactionSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateDataRedactionSettingsRequest', + ['dataRedactionSettings', 'name'], + ); + request.dataRedactionSettings.name = defaultValue1; + const expectedHeaderRequestParams = `data_redaction_settings.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDataRedactionSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateDataRedactionSettings(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateDataRedactionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDataRedactionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDataRedactionSettings with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateDataRedactionSettingsRequest(), + ); + request.dataRedactionSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateDataRedactionSettingsRequest', + ['dataRedactionSettings', 'name'], + ); + request.dataRedactionSettings.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateDataRedactionSettings(request), + expectedError, + ); + }); + }); + + describe('getDataRedactionSettings', () => { + it('invokes getDataRedactionSettings without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDataRedactionSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDataRedactionSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataRedactionSettings(), + ); + client.innerApiCalls.getDataRedactionSettings = + stubSimpleCall(expectedResponse); + const [response] = await client.getDataRedactionSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDataRedactionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataRedactionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDataRedactionSettings without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDataRedactionSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDataRedactionSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataRedactionSettings(), + ); + client.innerApiCalls.getDataRedactionSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDataRedactionSettings( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IDataRedactionSettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDataRedactionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataRedactionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDataRedactionSettings with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDataRedactionSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDataRedactionSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDataRedactionSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getDataRedactionSettings(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getDataRedactionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataRedactionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDataRedactionSettings with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetDataRedactionSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetDataRedactionSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getDataRedactionSettings(request), + expectedError, + ); + }); + }); + + describe('getCalculatedMetric', () => { + it('invokes getCalculatedMetric without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetCalculatedMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetCalculatedMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CalculatedMetric(), + ); + client.innerApiCalls.getCalculatedMetric = + stubSimpleCall(expectedResponse); + const [response] = await client.getCalculatedMetric(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCalculatedMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCalculatedMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCalculatedMetric without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetCalculatedMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetCalculatedMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CalculatedMetric(), + ); + client.innerApiCalls.getCalculatedMetric = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getCalculatedMetric( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.ICalculatedMetric | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCalculatedMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCalculatedMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCalculatedMetric with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetCalculatedMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetCalculatedMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getCalculatedMetric = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getCalculatedMetric(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getCalculatedMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCalculatedMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCalculatedMetric with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetCalculatedMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetCalculatedMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getCalculatedMetric(request), expectedError); + }); + }); + + describe('createCalculatedMetric', () => { + it('invokes createCalculatedMetric without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateCalculatedMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateCalculatedMetricRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CalculatedMetric(), + ); + client.innerApiCalls.createCalculatedMetric = + stubSimpleCall(expectedResponse); + const [response] = await client.createCalculatedMetric(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createCalculatedMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCalculatedMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCalculatedMetric without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateCalculatedMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateCalculatedMetricRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CalculatedMetric(), + ); + client.innerApiCalls.createCalculatedMetric = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createCalculatedMetric( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.ICalculatedMetric | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createCalculatedMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCalculatedMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCalculatedMetric with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateCalculatedMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateCalculatedMetricRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createCalculatedMetric = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createCalculatedMetric(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createCalculatedMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCalculatedMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCalculatedMetric with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateCalculatedMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateCalculatedMetricRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createCalculatedMetric(request), + expectedError, + ); + }); + }); + + describe('updateCalculatedMetric', () => { + it('invokes updateCalculatedMetric without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateCalculatedMetricRequest(), + ); + request.calculatedMetric ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateCalculatedMetricRequest', + ['calculatedMetric', 'name'], + ); + request.calculatedMetric.name = defaultValue1; + const expectedHeaderRequestParams = `calculated_metric.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CalculatedMetric(), + ); + client.innerApiCalls.updateCalculatedMetric = + stubSimpleCall(expectedResponse); + const [response] = await client.updateCalculatedMetric(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCalculatedMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCalculatedMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCalculatedMetric without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateCalculatedMetricRequest(), + ); + request.calculatedMetric ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateCalculatedMetricRequest', + ['calculatedMetric', 'name'], + ); + request.calculatedMetric.name = defaultValue1; + const expectedHeaderRequestParams = `calculated_metric.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CalculatedMetric(), + ); + client.innerApiCalls.updateCalculatedMetric = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateCalculatedMetric( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.ICalculatedMetric | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCalculatedMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCalculatedMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCalculatedMetric with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateCalculatedMetricRequest(), + ); + request.calculatedMetric ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateCalculatedMetricRequest', + ['calculatedMetric', 'name'], + ); + request.calculatedMetric.name = defaultValue1; + const expectedHeaderRequestParams = `calculated_metric.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateCalculatedMetric = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateCalculatedMetric(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateCalculatedMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCalculatedMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCalculatedMetric with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateCalculatedMetricRequest(), + ); + request.calculatedMetric ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateCalculatedMetricRequest', + ['calculatedMetric', 'name'], + ); + request.calculatedMetric.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateCalculatedMetric(request), + expectedError, + ); + }); + }); + + describe('deleteCalculatedMetric', () => { + it('invokes deleteCalculatedMetric without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteCalculatedMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteCalculatedMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteCalculatedMetric = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteCalculatedMetric(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteCalculatedMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteCalculatedMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteCalculatedMetric without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteCalculatedMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteCalculatedMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteCalculatedMetric = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteCalculatedMetric( + 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.deleteCalculatedMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteCalculatedMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteCalculatedMetric with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteCalculatedMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteCalculatedMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteCalculatedMetric = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteCalculatedMetric(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteCalculatedMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteCalculatedMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteCalculatedMetric with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteCalculatedMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteCalculatedMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteCalculatedMetric(request), + expectedError, + ); + }); + }); + + describe('createRollupProperty', () => { + it('invokes createRollupProperty without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateRollupPropertyRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateRollupPropertyResponse(), + ); + client.innerApiCalls.createRollupProperty = + stubSimpleCall(expectedResponse); + const [response] = await client.createRollupProperty(request); + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes createRollupProperty without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateRollupPropertyRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateRollupPropertyResponse(), + ); + client.innerApiCalls.createRollupProperty = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createRollupProperty( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.ICreateRollupPropertyResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes createRollupProperty with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateRollupPropertyRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createRollupProperty = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createRollupProperty(request), expectedError); + }); + + it('invokes createRollupProperty with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateRollupPropertyRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createRollupProperty(request), expectedError); + }); + }); + + describe('getRollupPropertySourceLink', () => { + it('invokes getRollupPropertySourceLink without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetRollupPropertySourceLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetRollupPropertySourceLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink(), + ); + client.innerApiCalls.getRollupPropertySourceLink = + stubSimpleCall(expectedResponse); + const [response] = await client.getRollupPropertySourceLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getRollupPropertySourceLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRollupPropertySourceLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getRollupPropertySourceLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetRollupPropertySourceLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetRollupPropertySourceLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink(), + ); + client.innerApiCalls.getRollupPropertySourceLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getRollupPropertySourceLink( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getRollupPropertySourceLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRollupPropertySourceLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getRollupPropertySourceLink with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetRollupPropertySourceLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetRollupPropertySourceLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getRollupPropertySourceLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getRollupPropertySourceLink(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getRollupPropertySourceLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRollupPropertySourceLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getRollupPropertySourceLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetRollupPropertySourceLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetRollupPropertySourceLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getRollupPropertySourceLink(request), + expectedError, + ); + }); + }); + + describe('createRollupPropertySourceLink', () => { + it('invokes createRollupPropertySourceLink without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateRollupPropertySourceLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateRollupPropertySourceLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink(), + ); + client.innerApiCalls.createRollupPropertySourceLink = + stubSimpleCall(expectedResponse); + const [response] = await client.createRollupPropertySourceLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createRollupPropertySourceLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createRollupPropertySourceLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createRollupPropertySourceLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateRollupPropertySourceLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateRollupPropertySourceLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink(), + ); + client.innerApiCalls.createRollupPropertySourceLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createRollupPropertySourceLink( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createRollupPropertySourceLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createRollupPropertySourceLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createRollupPropertySourceLink with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateRollupPropertySourceLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateRollupPropertySourceLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createRollupPropertySourceLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createRollupPropertySourceLink(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createRollupPropertySourceLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createRollupPropertySourceLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createRollupPropertySourceLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateRollupPropertySourceLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateRollupPropertySourceLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createRollupPropertySourceLink(request), + expectedError, + ); + }); + }); + + describe('deleteRollupPropertySourceLink', () => { + it('invokes deleteRollupPropertySourceLink without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteRollupPropertySourceLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteRollupPropertySourceLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteRollupPropertySourceLink = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteRollupPropertySourceLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteRollupPropertySourceLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteRollupPropertySourceLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteRollupPropertySourceLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteRollupPropertySourceLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteRollupPropertySourceLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteRollupPropertySourceLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteRollupPropertySourceLink( + 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.deleteRollupPropertySourceLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteRollupPropertySourceLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteRollupPropertySourceLink with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteRollupPropertySourceLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteRollupPropertySourceLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteRollupPropertySourceLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteRollupPropertySourceLink(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteRollupPropertySourceLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteRollupPropertySourceLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteRollupPropertySourceLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteRollupPropertySourceLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteRollupPropertySourceLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteRollupPropertySourceLink(request), + expectedError, + ); + }); + }); + + describe('provisionSubproperty', () => { + it('invokes provisionSubproperty without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ProvisionSubpropertyRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ProvisionSubpropertyResponse(), + ); + client.innerApiCalls.provisionSubproperty = + stubSimpleCall(expectedResponse); + const [response] = await client.provisionSubproperty(request); + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes provisionSubproperty without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ProvisionSubpropertyRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ProvisionSubpropertyResponse(), + ); + client.innerApiCalls.provisionSubproperty = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.provisionSubproperty( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IProvisionSubpropertyResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes provisionSubproperty with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ProvisionSubpropertyRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.provisionSubproperty = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.provisionSubproperty(request), expectedError); + }); + + it('invokes provisionSubproperty with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ProvisionSubpropertyRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.provisionSubproperty(request), expectedError); + }); + }); + + describe('createSubpropertyEventFilter', () => { + it('invokes createSubpropertyEventFilter without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateSubpropertyEventFilterRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateSubpropertyEventFilterRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter(), + ); + client.innerApiCalls.createSubpropertyEventFilter = + stubSimpleCall(expectedResponse); + const [response] = await client.createSubpropertyEventFilter(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createSubpropertyEventFilter as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createSubpropertyEventFilter as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createSubpropertyEventFilter without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateSubpropertyEventFilterRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateSubpropertyEventFilterRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter(), + ); + client.innerApiCalls.createSubpropertyEventFilter = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createSubpropertyEventFilter( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createSubpropertyEventFilter as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createSubpropertyEventFilter as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createSubpropertyEventFilter with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateSubpropertyEventFilterRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateSubpropertyEventFilterRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createSubpropertyEventFilter = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createSubpropertyEventFilter(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createSubpropertyEventFilter as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createSubpropertyEventFilter as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createSubpropertyEventFilter with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateSubpropertyEventFilterRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateSubpropertyEventFilterRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createSubpropertyEventFilter(request), + expectedError, + ); + }); + }); + + describe('getSubpropertyEventFilter', () => { + it('invokes getSubpropertyEventFilter without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetSubpropertyEventFilterRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetSubpropertyEventFilterRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter(), + ); + client.innerApiCalls.getSubpropertyEventFilter = + stubSimpleCall(expectedResponse); + const [response] = await client.getSubpropertyEventFilter(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSubpropertyEventFilter as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSubpropertyEventFilter as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getSubpropertyEventFilter without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetSubpropertyEventFilterRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetSubpropertyEventFilterRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter(), + ); + client.innerApiCalls.getSubpropertyEventFilter = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getSubpropertyEventFilter( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSubpropertyEventFilter as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSubpropertyEventFilter as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getSubpropertyEventFilter with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetSubpropertyEventFilterRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetSubpropertyEventFilterRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getSubpropertyEventFilter = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getSubpropertyEventFilter(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getSubpropertyEventFilter as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSubpropertyEventFilter as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getSubpropertyEventFilter with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetSubpropertyEventFilterRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetSubpropertyEventFilterRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getSubpropertyEventFilter(request), + expectedError, + ); + }); + }); + + describe('updateSubpropertyEventFilter', () => { + it('invokes updateSubpropertyEventFilter without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateSubpropertyEventFilterRequest(), + ); + request.subpropertyEventFilter ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateSubpropertyEventFilterRequest', + ['subpropertyEventFilter', 'name'], + ); + request.subpropertyEventFilter.name = defaultValue1; + const expectedHeaderRequestParams = `subproperty_event_filter.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter(), + ); + client.innerApiCalls.updateSubpropertyEventFilter = + stubSimpleCall(expectedResponse); + const [response] = await client.updateSubpropertyEventFilter(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateSubpropertyEventFilter as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSubpropertyEventFilter as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateSubpropertyEventFilter without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateSubpropertyEventFilterRequest(), + ); + request.subpropertyEventFilter ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateSubpropertyEventFilterRequest', + ['subpropertyEventFilter', 'name'], + ); + request.subpropertyEventFilter.name = defaultValue1; + const expectedHeaderRequestParams = `subproperty_event_filter.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter(), + ); + client.innerApiCalls.updateSubpropertyEventFilter = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateSubpropertyEventFilter( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateSubpropertyEventFilter as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSubpropertyEventFilter as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateSubpropertyEventFilter with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateSubpropertyEventFilterRequest(), + ); + request.subpropertyEventFilter ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateSubpropertyEventFilterRequest', + ['subpropertyEventFilter', 'name'], + ); + request.subpropertyEventFilter.name = defaultValue1; + const expectedHeaderRequestParams = `subproperty_event_filter.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateSubpropertyEventFilter = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateSubpropertyEventFilter(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateSubpropertyEventFilter as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSubpropertyEventFilter as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateSubpropertyEventFilter with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateSubpropertyEventFilterRequest(), + ); + request.subpropertyEventFilter ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateSubpropertyEventFilterRequest', + ['subpropertyEventFilter', 'name'], + ); + request.subpropertyEventFilter.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateSubpropertyEventFilter(request), + expectedError, + ); + }); + }); + + describe('deleteSubpropertyEventFilter', () => { + it('invokes deleteSubpropertyEventFilter without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteSubpropertyEventFilterRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteSubpropertyEventFilterRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteSubpropertyEventFilter = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteSubpropertyEventFilter(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteSubpropertyEventFilter as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSubpropertyEventFilter as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteSubpropertyEventFilter without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteSubpropertyEventFilterRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteSubpropertyEventFilterRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteSubpropertyEventFilter = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteSubpropertyEventFilter( + 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.deleteSubpropertyEventFilter as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSubpropertyEventFilter as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteSubpropertyEventFilter with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteSubpropertyEventFilterRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteSubpropertyEventFilterRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteSubpropertyEventFilter = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteSubpropertyEventFilter(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteSubpropertyEventFilter as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteSubpropertyEventFilter as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteSubpropertyEventFilter with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteSubpropertyEventFilterRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteSubpropertyEventFilterRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteSubpropertyEventFilter(request), + expectedError, + ); + }); + }); + + describe('createReportingDataAnnotation', () => { + it('invokes createReportingDataAnnotation without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateReportingDataAnnotationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateReportingDataAnnotationRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation(), + ); + client.innerApiCalls.createReportingDataAnnotation = + stubSimpleCall(expectedResponse); + const [response] = await client.createReportingDataAnnotation(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createReportingDataAnnotation as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createReportingDataAnnotation as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createReportingDataAnnotation without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateReportingDataAnnotationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateReportingDataAnnotationRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation(), + ); + client.innerApiCalls.createReportingDataAnnotation = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createReportingDataAnnotation( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IReportingDataAnnotation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createReportingDataAnnotation as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createReportingDataAnnotation as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createReportingDataAnnotation with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateReportingDataAnnotationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateReportingDataAnnotationRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createReportingDataAnnotation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createReportingDataAnnotation(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createReportingDataAnnotation as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createReportingDataAnnotation as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createReportingDataAnnotation with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CreateReportingDataAnnotationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.CreateReportingDataAnnotationRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createReportingDataAnnotation(request), + expectedError, + ); + }); + }); + + describe('getReportingDataAnnotation', () => { + it('invokes getReportingDataAnnotation without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetReportingDataAnnotationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetReportingDataAnnotationRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation(), + ); + client.innerApiCalls.getReportingDataAnnotation = + stubSimpleCall(expectedResponse); + const [response] = await client.getReportingDataAnnotation(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getReportingDataAnnotation as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getReportingDataAnnotation as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getReportingDataAnnotation without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetReportingDataAnnotationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetReportingDataAnnotationRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation(), + ); + client.innerApiCalls.getReportingDataAnnotation = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getReportingDataAnnotation( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IReportingDataAnnotation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getReportingDataAnnotation as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getReportingDataAnnotation as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getReportingDataAnnotation with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetReportingDataAnnotationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetReportingDataAnnotationRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getReportingDataAnnotation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getReportingDataAnnotation(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getReportingDataAnnotation as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getReportingDataAnnotation as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getReportingDataAnnotation with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetReportingDataAnnotationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetReportingDataAnnotationRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getReportingDataAnnotation(request), + expectedError, + ); + }); + }); + + describe('updateReportingDataAnnotation', () => { + it('invokes updateReportingDataAnnotation without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateReportingDataAnnotationRequest(), + ); + request.reportingDataAnnotation ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateReportingDataAnnotationRequest', + ['reportingDataAnnotation', 'name'], + ); + request.reportingDataAnnotation.name = defaultValue1; + const expectedHeaderRequestParams = `reporting_data_annotation.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation(), + ); + client.innerApiCalls.updateReportingDataAnnotation = + stubSimpleCall(expectedResponse); + const [response] = await client.updateReportingDataAnnotation(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateReportingDataAnnotation as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateReportingDataAnnotation as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateReportingDataAnnotation without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateReportingDataAnnotationRequest(), + ); + request.reportingDataAnnotation ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateReportingDataAnnotationRequest', + ['reportingDataAnnotation', 'name'], + ); + request.reportingDataAnnotation.name = defaultValue1; + const expectedHeaderRequestParams = `reporting_data_annotation.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation(), + ); + client.innerApiCalls.updateReportingDataAnnotation = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateReportingDataAnnotation( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IReportingDataAnnotation | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateReportingDataAnnotation as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateReportingDataAnnotation as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateReportingDataAnnotation with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateReportingDataAnnotationRequest(), + ); + request.reportingDataAnnotation ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateReportingDataAnnotationRequest', + ['reportingDataAnnotation', 'name'], + ); + request.reportingDataAnnotation.name = defaultValue1; + const expectedHeaderRequestParams = `reporting_data_annotation.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateReportingDataAnnotation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateReportingDataAnnotation(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateReportingDataAnnotation as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateReportingDataAnnotation as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateReportingDataAnnotation with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateReportingDataAnnotationRequest(), + ); + request.reportingDataAnnotation ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateReportingDataAnnotationRequest', + ['reportingDataAnnotation', 'name'], + ); + request.reportingDataAnnotation.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateReportingDataAnnotation(request), + expectedError, + ); + }); + }); + + describe('deleteReportingDataAnnotation', () => { + it('invokes deleteReportingDataAnnotation without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteReportingDataAnnotationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteReportingDataAnnotationRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteReportingDataAnnotation = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteReportingDataAnnotation(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteReportingDataAnnotation as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteReportingDataAnnotation as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteReportingDataAnnotation without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteReportingDataAnnotationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteReportingDataAnnotationRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteReportingDataAnnotation = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteReportingDataAnnotation( + 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.deleteReportingDataAnnotation as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteReportingDataAnnotation as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteReportingDataAnnotation with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteReportingDataAnnotationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteReportingDataAnnotationRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteReportingDataAnnotation = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteReportingDataAnnotation(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteReportingDataAnnotation as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteReportingDataAnnotation as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteReportingDataAnnotation with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DeleteReportingDataAnnotationRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.DeleteReportingDataAnnotationRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteReportingDataAnnotation(request), + expectedError, + ); + }); + }); + + describe('submitUserDeletion', () => { + it('invokes submitUserDeletion without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubmitUserDeletionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.SubmitUserDeletionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubmitUserDeletionResponse(), + ); + client.innerApiCalls.submitUserDeletion = + stubSimpleCall(expectedResponse); + const [response] = await client.submitUserDeletion(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.submitUserDeletion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.submitUserDeletion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes submitUserDeletion without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubmitUserDeletionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.SubmitUserDeletionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubmitUserDeletionResponse(), + ); + client.innerApiCalls.submitUserDeletion = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.submitUserDeletion( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.ISubmitUserDeletionResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.submitUserDeletion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.submitUserDeletion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes submitUserDeletion with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubmitUserDeletionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.SubmitUserDeletionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.submitUserDeletion = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.submitUserDeletion(request), expectedError); + const actualRequest = ( + client.innerApiCalls.submitUserDeletion as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.submitUserDeletion as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes submitUserDeletion with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubmitUserDeletionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.SubmitUserDeletionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.submitUserDeletion(request), expectedError); + }); + }); + + describe('updateSubpropertySyncConfig', () => { + it('invokes updateSubpropertySyncConfig without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateSubpropertySyncConfigRequest(), + ); + request.subpropertySyncConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateSubpropertySyncConfigRequest', + ['subpropertySyncConfig', 'name'], + ); + request.subpropertySyncConfig.name = defaultValue1; + const expectedHeaderRequestParams = `subproperty_sync_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig(), + ); + client.innerApiCalls.updateSubpropertySyncConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.updateSubpropertySyncConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateSubpropertySyncConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSubpropertySyncConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateSubpropertySyncConfig without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateSubpropertySyncConfigRequest(), + ); + request.subpropertySyncConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateSubpropertySyncConfigRequest', + ['subpropertySyncConfig', 'name'], + ); + request.subpropertySyncConfig.name = defaultValue1; + const expectedHeaderRequestParams = `subproperty_sync_config.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig(), + ); + client.innerApiCalls.updateSubpropertySyncConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateSubpropertySyncConfig( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateSubpropertySyncConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSubpropertySyncConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateSubpropertySyncConfig with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateSubpropertySyncConfigRequest(), + ); + request.subpropertySyncConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateSubpropertySyncConfigRequest', + ['subpropertySyncConfig', 'name'], + ); + request.subpropertySyncConfig.name = defaultValue1; + const expectedHeaderRequestParams = `subproperty_sync_config.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateSubpropertySyncConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateSubpropertySyncConfig(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateSubpropertySyncConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateSubpropertySyncConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateSubpropertySyncConfig with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UpdateSubpropertySyncConfigRequest(), + ); + request.subpropertySyncConfig ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.UpdateSubpropertySyncConfigRequest', + ['subpropertySyncConfig', 'name'], + ); + request.subpropertySyncConfig.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateSubpropertySyncConfig(request), + expectedError, + ); + }); + }); + + describe('getSubpropertySyncConfig', () => { + it('invokes getSubpropertySyncConfig without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetSubpropertySyncConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetSubpropertySyncConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig(), + ); + client.innerApiCalls.getSubpropertySyncConfig = + stubSimpleCall(expectedResponse); + const [response] = await client.getSubpropertySyncConfig(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSubpropertySyncConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSubpropertySyncConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getSubpropertySyncConfig without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetSubpropertySyncConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetSubpropertySyncConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig(), + ); + client.innerApiCalls.getSubpropertySyncConfig = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getSubpropertySyncConfig( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getSubpropertySyncConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSubpropertySyncConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getSubpropertySyncConfig with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetSubpropertySyncConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetSubpropertySyncConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getSubpropertySyncConfig = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getSubpropertySyncConfig(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getSubpropertySyncConfig as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getSubpropertySyncConfig as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getSubpropertySyncConfig with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetSubpropertySyncConfigRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetSubpropertySyncConfigRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getSubpropertySyncConfig(request), + expectedError, + ); + }); + }); + + describe('getReportingIdentitySettings', () => { + it('invokes getReportingIdentitySettings without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetReportingIdentitySettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetReportingIdentitySettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReportingIdentitySettings(), + ); + client.innerApiCalls.getReportingIdentitySettings = + stubSimpleCall(expectedResponse); + const [response] = await client.getReportingIdentitySettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getReportingIdentitySettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getReportingIdentitySettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getReportingIdentitySettings without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetReportingIdentitySettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetReportingIdentitySettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReportingIdentitySettings(), + ); + client.innerApiCalls.getReportingIdentitySettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getReportingIdentitySettings( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IReportingIdentitySettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getReportingIdentitySettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getReportingIdentitySettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getReportingIdentitySettings with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetReportingIdentitySettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetReportingIdentitySettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getReportingIdentitySettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getReportingIdentitySettings(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getReportingIdentitySettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getReportingIdentitySettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getReportingIdentitySettings with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetReportingIdentitySettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetReportingIdentitySettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getReportingIdentitySettings(request), + expectedError, + ); + }); + }); + + describe('getUserProvidedDataSettings', () => { + it('invokes getUserProvidedDataSettings without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetUserProvidedDataSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetUserProvidedDataSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UserProvidedDataSettings(), + ); + client.innerApiCalls.getUserProvidedDataSettings = + stubSimpleCall(expectedResponse); + const [response] = await client.getUserProvidedDataSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getUserProvidedDataSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUserProvidedDataSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getUserProvidedDataSettings without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetUserProvidedDataSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetUserProvidedDataSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.UserProvidedDataSettings(), + ); + client.innerApiCalls.getUserProvidedDataSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getUserProvidedDataSettings( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IUserProvidedDataSettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getUserProvidedDataSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUserProvidedDataSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getUserProvidedDataSettings with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetUserProvidedDataSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetUserProvidedDataSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getUserProvidedDataSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getUserProvidedDataSettings(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getUserProvidedDataSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUserProvidedDataSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getUserProvidedDataSettings with closed client', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GetUserProvidedDataSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.GetUserProvidedDataSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getUserProvidedDataSettings(request), + expectedError, + ); + }); + }); + + describe('listAccounts', () => { + it('invokes listAccounts without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAccountsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Account(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Account(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Account(), + ), + ]; + client.innerApiCalls.listAccounts = stubSimpleCall(expectedResponse); + const [response] = await client.listAccounts(request); + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes listAccounts without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAccountsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Account(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Account(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Account(), + ), + ]; + client.innerApiCalls.listAccounts = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listAccounts( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IAccount[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes listAccounts with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAccountsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listAccounts = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listAccounts(request), expectedError); + }); + + it('invokes listAccountsStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAccountsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Account(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Account(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Account(), + ), + ]; + client.descriptors.page.listAccounts.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listAccountsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.Account[] = []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.Account) => { + 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.listAccounts.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listAccounts, request), + ); + }); + + it('invokes listAccountsStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAccountsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listAccounts.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listAccountsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.Account[] = []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.Account) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listAccounts.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listAccounts, request), + ); + }); + + it('uses async iteration with listAccounts without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAccountsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Account(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Account(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Account(), + ), + ]; + client.descriptors.page.listAccounts.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.IAccount[] = []; + const iterable = client.listAccountsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listAccounts.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + + it('uses async iteration with listAccounts with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAccountsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listAccounts.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listAccountsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.IAccount[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listAccounts.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('listAccountSummaries', () => { + it('invokes listAccountSummaries without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAccountSummariesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccountSummary(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccountSummary(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccountSummary(), + ), + ]; + client.innerApiCalls.listAccountSummaries = + stubSimpleCall(expectedResponse); + const [response] = await client.listAccountSummaries(request); + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes listAccountSummaries without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAccountSummariesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccountSummary(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccountSummary(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccountSummary(), + ), + ]; + client.innerApiCalls.listAccountSummaries = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listAccountSummaries( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.IAccountSummary[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes listAccountSummaries with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAccountSummariesRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listAccountSummaries = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listAccountSummaries(request), expectedError); + }); + + it('invokes listAccountSummariesStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAccountSummariesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccountSummary(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccountSummary(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccountSummary(), + ), + ]; + client.descriptors.page.listAccountSummaries.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listAccountSummariesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.AccountSummary[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.AccountSummary) => { + 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.listAccountSummaries.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listAccountSummaries, request), + ); + }); + + it('invokes listAccountSummariesStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAccountSummariesRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listAccountSummaries.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listAccountSummariesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.AccountSummary[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.AccountSummary) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listAccountSummaries.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listAccountSummaries, request), + ); + }); + + it('uses async iteration with listAccountSummaries without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAccountSummariesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccountSummary(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccountSummary(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccountSummary(), + ), + ]; + client.descriptors.page.listAccountSummaries.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.IAccountSummary[] = + []; + const iterable = client.listAccountSummariesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listAccountSummaries.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + + it('uses async iteration with listAccountSummaries with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAccountSummariesRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listAccountSummaries.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listAccountSummariesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.IAccountSummary[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listAccountSummaries.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('listProperties', () => { + it('invokes listProperties without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListPropertiesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Property(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Property(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Property(), + ), + ]; + client.innerApiCalls.listProperties = stubSimpleCall(expectedResponse); + const [response] = await client.listProperties(request); + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes listProperties without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListPropertiesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Property(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Property(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Property(), + ), + ]; + client.innerApiCalls.listProperties = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listProperties( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IProperty[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes listProperties with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListPropertiesRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listProperties = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listProperties(request), expectedError); + }); + + it('invokes listPropertiesStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListPropertiesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Property(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Property(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Property(), + ), + ]; + client.descriptors.page.listProperties.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listPropertiesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.Property[] = []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.Property) => { + 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.listProperties.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listProperties, request), + ); + }); + + it('invokes listPropertiesStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListPropertiesRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listProperties.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listPropertiesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.Property[] = []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.Property) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listProperties.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listProperties, request), + ); + }); + + it('uses async iteration with listProperties without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListPropertiesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Property(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Property(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Property(), + ), + ]; + client.descriptors.page.listProperties.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.IProperty[] = []; + const iterable = client.listPropertiesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listProperties.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + + it('uses async iteration with listProperties with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListPropertiesRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listProperties.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listPropertiesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.IProperty[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listProperties.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('listFirebaseLinks', () => { + it('invokes listFirebaseLinks without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListFirebaseLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListFirebaseLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.FirebaseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.FirebaseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.FirebaseLink(), + ), + ]; + client.innerApiCalls.listFirebaseLinks = stubSimpleCall(expectedResponse); + const [response] = await client.listFirebaseLinks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listFirebaseLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listFirebaseLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listFirebaseLinks without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListFirebaseLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListFirebaseLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.FirebaseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.FirebaseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.FirebaseLink(), + ), + ]; + client.innerApiCalls.listFirebaseLinks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listFirebaseLinks( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.IFirebaseLink[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listFirebaseLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listFirebaseLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listFirebaseLinks with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListFirebaseLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListFirebaseLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listFirebaseLinks = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listFirebaseLinks(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listFirebaseLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listFirebaseLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listFirebaseLinksStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListFirebaseLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListFirebaseLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.FirebaseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.FirebaseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.FirebaseLink(), + ), + ]; + client.descriptors.page.listFirebaseLinks.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listFirebaseLinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.FirebaseLink[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.FirebaseLink) => { + 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.listFirebaseLinks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listFirebaseLinks, request), + ); + assert( + (client.descriptors.page.listFirebaseLinks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listFirebaseLinksStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListFirebaseLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListFirebaseLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listFirebaseLinks.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listFirebaseLinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.FirebaseLink[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.FirebaseLink) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listFirebaseLinks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listFirebaseLinks, request), + ); + assert( + (client.descriptors.page.listFirebaseLinks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listFirebaseLinks without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListFirebaseLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListFirebaseLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.FirebaseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.FirebaseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.FirebaseLink(), + ), + ]; + client.descriptors.page.listFirebaseLinks.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.IFirebaseLink[] = + []; + const iterable = client.listFirebaseLinksAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listFirebaseLinks.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listFirebaseLinks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listFirebaseLinks with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListFirebaseLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListFirebaseLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listFirebaseLinks.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listFirebaseLinksAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.IFirebaseLink[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listFirebaseLinks.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listFirebaseLinks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listGoogleAdsLinks', () => { + it('invokes listGoogleAdsLinks without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GoogleAdsLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GoogleAdsLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GoogleAdsLink(), + ), + ]; + client.innerApiCalls.listGoogleAdsLinks = + stubSimpleCall(expectedResponse); + const [response] = await client.listGoogleAdsLinks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listGoogleAdsLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGoogleAdsLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listGoogleAdsLinks without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GoogleAdsLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GoogleAdsLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GoogleAdsLink(), + ), + ]; + client.innerApiCalls.listGoogleAdsLinks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listGoogleAdsLinks( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.IGoogleAdsLink[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listGoogleAdsLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGoogleAdsLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listGoogleAdsLinks with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listGoogleAdsLinks = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listGoogleAdsLinks(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listGoogleAdsLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGoogleAdsLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listGoogleAdsLinksStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GoogleAdsLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GoogleAdsLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GoogleAdsLink(), + ), + ]; + client.descriptors.page.listGoogleAdsLinks.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listGoogleAdsLinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.GoogleAdsLink[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.GoogleAdsLink) => { + 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.listGoogleAdsLinks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listGoogleAdsLinks, request), + ); + assert( + (client.descriptors.page.listGoogleAdsLinks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listGoogleAdsLinksStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listGoogleAdsLinks.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listGoogleAdsLinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.GoogleAdsLink[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.GoogleAdsLink) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listGoogleAdsLinks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listGoogleAdsLinks, request), + ); + assert( + (client.descriptors.page.listGoogleAdsLinks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listGoogleAdsLinks without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GoogleAdsLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GoogleAdsLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.GoogleAdsLink(), + ), + ]; + client.descriptors.page.listGoogleAdsLinks.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.IGoogleAdsLink[] = + []; + const iterable = client.listGoogleAdsLinksAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listGoogleAdsLinks.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listGoogleAdsLinks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listGoogleAdsLinks with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listGoogleAdsLinks.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listGoogleAdsLinksAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.IGoogleAdsLink[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listGoogleAdsLinks.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listGoogleAdsLinks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listMeasurementProtocolSecrets', () => { + it('invokes listMeasurementProtocolSecrets without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret(), + ), + ]; + client.innerApiCalls.listMeasurementProtocolSecrets = + stubSimpleCall(expectedResponse); + const [response] = await client.listMeasurementProtocolSecrets(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listMeasurementProtocolSecrets without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret(), + ), + ]; + client.innerApiCalls.listMeasurementProtocolSecrets = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listMeasurementProtocolSecrets( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listMeasurementProtocolSecrets with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listMeasurementProtocolSecrets = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listMeasurementProtocolSecrets(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listMeasurementProtocolSecretsStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret(), + ), + ]; + client.descriptors.page.listMeasurementProtocolSecrets.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listMeasurementProtocolSecretsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret, + ) => { + 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.listMeasurementProtocolSecrets + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listMeasurementProtocolSecrets, + request, + ), + ); + assert( + ( + client.descriptors.page.listMeasurementProtocolSecrets + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('invokes listMeasurementProtocolSecretsStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listMeasurementProtocolSecrets.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listMeasurementProtocolSecretsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listMeasurementProtocolSecrets + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listMeasurementProtocolSecrets, + request, + ), + ); + assert( + ( + client.descriptors.page.listMeasurementProtocolSecrets + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listMeasurementProtocolSecrets without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret(), + ), + ]; + client.descriptors.page.listMeasurementProtocolSecrets.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret[] = + []; + const iterable = client.listMeasurementProtocolSecretsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listMeasurementProtocolSecrets + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listMeasurementProtocolSecrets + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listMeasurementProtocolSecrets with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listMeasurementProtocolSecrets.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listMeasurementProtocolSecretsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listMeasurementProtocolSecrets + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listMeasurementProtocolSecrets + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listSKAdNetworkConversionValueSchemas', () => { + it('invokes listSKAdNetworkConversionValueSchemas without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema(), + ), + ]; + client.innerApiCalls.listSkAdNetworkConversionValueSchemas = + stubSimpleCall(expectedResponse); + const [response] = + await client.listSKAdNetworkConversionValueSchemas(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listSkAdNetworkConversionValueSchemas as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listSkAdNetworkConversionValueSchemas as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listSKAdNetworkConversionValueSchemas without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema(), + ), + ]; + client.innerApiCalls.listSkAdNetworkConversionValueSchemas = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listSKAdNetworkConversionValueSchemas( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listSkAdNetworkConversionValueSchemas as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listSkAdNetworkConversionValueSchemas as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listSKAdNetworkConversionValueSchemas with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listSkAdNetworkConversionValueSchemas = + stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.listSKAdNetworkConversionValueSchemas(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listSkAdNetworkConversionValueSchemas as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listSkAdNetworkConversionValueSchemas as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listSKAdNetworkConversionValueSchemasStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema(), + ), + ]; + client.descriptors.page.listSKAdNetworkConversionValueSchemas.createStream = + stubPageStreamingCall(expectedResponse); + const stream = + client.listSKAdNetworkConversionValueSchemasStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema, + ) => { + 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.listSKAdNetworkConversionValueSchemas + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listSkAdNetworkConversionValueSchemas, + request, + ), + ); + assert( + ( + client.descriptors.page.listSKAdNetworkConversionValueSchemas + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('invokes listSKAdNetworkConversionValueSchemasStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listSKAdNetworkConversionValueSchemas.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = + client.listSKAdNetworkConversionValueSchemasStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listSKAdNetworkConversionValueSchemas + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listSkAdNetworkConversionValueSchemas, + request, + ), + ); + assert( + ( + client.descriptors.page.listSKAdNetworkConversionValueSchemas + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listSKAdNetworkConversionValueSchemas without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema(), + ), + ]; + client.descriptors.page.listSKAdNetworkConversionValueSchemas.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema[] = + []; + const iterable = + client.listSKAdNetworkConversionValueSchemasAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listSKAdNetworkConversionValueSchemas + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listSKAdNetworkConversionValueSchemas + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listSKAdNetworkConversionValueSchemas with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listSKAdNetworkConversionValueSchemas.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = + client.listSKAdNetworkConversionValueSchemasAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listSKAdNetworkConversionValueSchemas + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listSKAdNetworkConversionValueSchemas + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('searchChangeHistoryEvents', () => { + it('invokes searchChangeHistoryEvents without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest', + ['account'], + ); + request.account = defaultValue1; + const expectedHeaderRequestParams = `account=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent(), + ), + ]; + client.innerApiCalls.searchChangeHistoryEvents = + stubSimpleCall(expectedResponse); + const [response] = await client.searchChangeHistoryEvents(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.searchChangeHistoryEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchChangeHistoryEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes searchChangeHistoryEvents without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest', + ['account'], + ); + request.account = defaultValue1; + const expectedHeaderRequestParams = `account=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent(), + ), + ]; + client.innerApiCalls.searchChangeHistoryEvents = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.searchChangeHistoryEvents( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.IChangeHistoryEvent[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.searchChangeHistoryEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchChangeHistoryEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes searchChangeHistoryEvents with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest', + ['account'], + ); + request.account = defaultValue1; + const expectedHeaderRequestParams = `account=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.searchChangeHistoryEvents = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.searchChangeHistoryEvents(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.searchChangeHistoryEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchChangeHistoryEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes searchChangeHistoryEventsStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest', + ['account'], + ); + request.account = defaultValue1; + const expectedHeaderRequestParams = `account=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent(), + ), + ]; + client.descriptors.page.searchChangeHistoryEvents.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.searchChangeHistoryEventsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.ChangeHistoryEvent[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1alpha.ChangeHistoryEvent, + ) => { + 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.searchChangeHistoryEvents + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.searchChangeHistoryEvents, request), + ); + assert( + ( + client.descriptors.page.searchChangeHistoryEvents + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('invokes searchChangeHistoryEventsStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest', + ['account'], + ); + request.account = defaultValue1; + const expectedHeaderRequestParams = `account=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.searchChangeHistoryEvents.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.searchChangeHistoryEventsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.ChangeHistoryEvent[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1alpha.ChangeHistoryEvent, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.searchChangeHistoryEvents + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.searchChangeHistoryEvents, request), + ); + assert( + ( + client.descriptors.page.searchChangeHistoryEvents + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with searchChangeHistoryEvents without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest', + ['account'], + ); + request.account = defaultValue1; + const expectedHeaderRequestParams = `account=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent(), + ), + ]; + client.descriptors.page.searchChangeHistoryEvents.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.IChangeHistoryEvent[] = + []; + const iterable = client.searchChangeHistoryEventsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.searchChangeHistoryEvents + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.searchChangeHistoryEvents + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with searchChangeHistoryEvents with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest', + ['account'], + ); + request.account = defaultValue1; + const expectedHeaderRequestParams = `account=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.searchChangeHistoryEvents.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.searchChangeHistoryEventsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.IChangeHistoryEvent[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.searchChangeHistoryEvents + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.searchChangeHistoryEvents + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listConversionEvents', () => { + it('invokes listConversionEvents without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListConversionEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListConversionEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ConversionEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ConversionEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ConversionEvent(), + ), + ]; + client.innerApiCalls.listConversionEvents = + stubSimpleCall(expectedResponse); + const [response] = await client.listConversionEvents(request); + assert(stub.calledOnce); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listConversionEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listConversionEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listConversionEvents without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListConversionEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListConversionEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ConversionEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ConversionEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ConversionEvent(), + ), + ]; + client.innerApiCalls.listConversionEvents = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listConversionEvents( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.IConversionEvent[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert(stub.calledOnce); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listConversionEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listConversionEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listConversionEvents with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListConversionEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListConversionEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listConversionEvents = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listConversionEvents(request), expectedError); + assert(stub.calledOnce); + const actualRequest = ( + client.innerApiCalls.listConversionEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listConversionEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createSubpropertyEventFilter', () => { - it('invokes createSubpropertyEventFilter without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateSubpropertyEventFilterRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateSubpropertyEventFilterRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter() - ); - client.innerApiCalls.createSubpropertyEventFilter = stubSimpleCall(expectedResponse); - const [response] = await client.createSubpropertyEventFilter(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createSubpropertyEventFilter as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createSubpropertyEventFilter as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createSubpropertyEventFilter without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateSubpropertyEventFilterRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateSubpropertyEventFilterRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter() - ); - client.innerApiCalls.createSubpropertyEventFilter = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createSubpropertyEventFilter( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createSubpropertyEventFilter as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createSubpropertyEventFilter as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createSubpropertyEventFilter with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateSubpropertyEventFilterRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateSubpropertyEventFilterRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createSubpropertyEventFilter = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createSubpropertyEventFilter(request), expectedError); - const actualRequest = (client.innerApiCalls.createSubpropertyEventFilter as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createSubpropertyEventFilter as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createSubpropertyEventFilter with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateSubpropertyEventFilterRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateSubpropertyEventFilterRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createSubpropertyEventFilter(request), expectedError); - }); - }); - - describe('getSubpropertyEventFilter', () => { - it('invokes getSubpropertyEventFilter without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetSubpropertyEventFilterRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetSubpropertyEventFilterRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter() - ); - client.innerApiCalls.getSubpropertyEventFilter = stubSimpleCall(expectedResponse); - const [response] = await client.getSubpropertyEventFilter(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSubpropertyEventFilter as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSubpropertyEventFilter as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getSubpropertyEventFilter without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetSubpropertyEventFilterRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetSubpropertyEventFilterRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter() - ); - client.innerApiCalls.getSubpropertyEventFilter = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getSubpropertyEventFilter( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSubpropertyEventFilter as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSubpropertyEventFilter as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getSubpropertyEventFilter with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetSubpropertyEventFilterRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetSubpropertyEventFilterRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getSubpropertyEventFilter = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getSubpropertyEventFilter(request), expectedError); - const actualRequest = (client.innerApiCalls.getSubpropertyEventFilter as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSubpropertyEventFilter as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getSubpropertyEventFilter with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetSubpropertyEventFilterRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetSubpropertyEventFilterRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getSubpropertyEventFilter(request), expectedError); - }); - }); - - describe('updateSubpropertyEventFilter', () => { - it('invokes updateSubpropertyEventFilter without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateSubpropertyEventFilterRequest() - ); - request.subpropertyEventFilter ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateSubpropertyEventFilterRequest', ['subpropertyEventFilter', 'name']); - request.subpropertyEventFilter.name = defaultValue1; - const expectedHeaderRequestParams = `subproperty_event_filter.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter() - ); - client.innerApiCalls.updateSubpropertyEventFilter = stubSimpleCall(expectedResponse); - const [response] = await client.updateSubpropertyEventFilter(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateSubpropertyEventFilter as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSubpropertyEventFilter as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateSubpropertyEventFilter without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateSubpropertyEventFilterRequest() - ); - request.subpropertyEventFilter ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateSubpropertyEventFilterRequest', ['subpropertyEventFilter', 'name']); - request.subpropertyEventFilter.name = defaultValue1; - const expectedHeaderRequestParams = `subproperty_event_filter.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter() - ); - client.innerApiCalls.updateSubpropertyEventFilter = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateSubpropertyEventFilter( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateSubpropertyEventFilter as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSubpropertyEventFilter as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateSubpropertyEventFilter with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateSubpropertyEventFilterRequest() - ); - request.subpropertyEventFilter ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateSubpropertyEventFilterRequest', ['subpropertyEventFilter', 'name']); - request.subpropertyEventFilter.name = defaultValue1; - const expectedHeaderRequestParams = `subproperty_event_filter.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateSubpropertyEventFilter = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateSubpropertyEventFilter(request), expectedError); - const actualRequest = (client.innerApiCalls.updateSubpropertyEventFilter as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSubpropertyEventFilter as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateSubpropertyEventFilter with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateSubpropertyEventFilterRequest() - ); - request.subpropertyEventFilter ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateSubpropertyEventFilterRequest', ['subpropertyEventFilter', 'name']); - request.subpropertyEventFilter.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateSubpropertyEventFilter(request), expectedError); - }); - }); - - describe('deleteSubpropertyEventFilter', () => { - it('invokes deleteSubpropertyEventFilter without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteSubpropertyEventFilterRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteSubpropertyEventFilterRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteSubpropertyEventFilter = stubSimpleCall(expectedResponse); - const [response] = await client.deleteSubpropertyEventFilter(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteSubpropertyEventFilter as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSubpropertyEventFilter as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteSubpropertyEventFilter without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteSubpropertyEventFilterRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteSubpropertyEventFilterRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteSubpropertyEventFilter = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteSubpropertyEventFilter( - 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.deleteSubpropertyEventFilter as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSubpropertyEventFilter as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteSubpropertyEventFilter with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteSubpropertyEventFilterRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteSubpropertyEventFilterRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteSubpropertyEventFilter = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteSubpropertyEventFilter(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteSubpropertyEventFilter as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteSubpropertyEventFilter as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteSubpropertyEventFilter with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteSubpropertyEventFilterRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteSubpropertyEventFilterRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteSubpropertyEventFilter(request), expectedError); - }); - }); - - describe('createReportingDataAnnotation', () => { - it('invokes createReportingDataAnnotation without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateReportingDataAnnotationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateReportingDataAnnotationRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation() - ); - client.innerApiCalls.createReportingDataAnnotation = stubSimpleCall(expectedResponse); - const [response] = await client.createReportingDataAnnotation(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createReportingDataAnnotation as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createReportingDataAnnotation as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createReportingDataAnnotation without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateReportingDataAnnotationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateReportingDataAnnotationRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation() - ); - client.innerApiCalls.createReportingDataAnnotation = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createReportingDataAnnotation( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IReportingDataAnnotation|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createReportingDataAnnotation as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createReportingDataAnnotation as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createReportingDataAnnotation with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateReportingDataAnnotationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateReportingDataAnnotationRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createReportingDataAnnotation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createReportingDataAnnotation(request), expectedError); - const actualRequest = (client.innerApiCalls.createReportingDataAnnotation as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createReportingDataAnnotation as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createReportingDataAnnotation with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.CreateReportingDataAnnotationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.CreateReportingDataAnnotationRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createReportingDataAnnotation(request), expectedError); - }); - }); - - describe('getReportingDataAnnotation', () => { - it('invokes getReportingDataAnnotation without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetReportingDataAnnotationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetReportingDataAnnotationRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation() - ); - client.innerApiCalls.getReportingDataAnnotation = stubSimpleCall(expectedResponse); - const [response] = await client.getReportingDataAnnotation(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getReportingDataAnnotation as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getReportingDataAnnotation as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getReportingDataAnnotation without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetReportingDataAnnotationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetReportingDataAnnotationRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation() - ); - client.innerApiCalls.getReportingDataAnnotation = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getReportingDataAnnotation( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IReportingDataAnnotation|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getReportingDataAnnotation as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getReportingDataAnnotation as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getReportingDataAnnotation with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetReportingDataAnnotationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetReportingDataAnnotationRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getReportingDataAnnotation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getReportingDataAnnotation(request), expectedError); - const actualRequest = (client.innerApiCalls.getReportingDataAnnotation as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getReportingDataAnnotation as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getReportingDataAnnotation with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetReportingDataAnnotationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetReportingDataAnnotationRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getReportingDataAnnotation(request), expectedError); - }); - }); - - describe('updateReportingDataAnnotation', () => { - it('invokes updateReportingDataAnnotation without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateReportingDataAnnotationRequest() - ); - request.reportingDataAnnotation ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateReportingDataAnnotationRequest', ['reportingDataAnnotation', 'name']); - request.reportingDataAnnotation.name = defaultValue1; - const expectedHeaderRequestParams = `reporting_data_annotation.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation() - ); - client.innerApiCalls.updateReportingDataAnnotation = stubSimpleCall(expectedResponse); - const [response] = await client.updateReportingDataAnnotation(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateReportingDataAnnotation as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateReportingDataAnnotation as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateReportingDataAnnotation without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateReportingDataAnnotationRequest() - ); - request.reportingDataAnnotation ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateReportingDataAnnotationRequest', ['reportingDataAnnotation', 'name']); - request.reportingDataAnnotation.name = defaultValue1; - const expectedHeaderRequestParams = `reporting_data_annotation.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation() - ); - client.innerApiCalls.updateReportingDataAnnotation = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateReportingDataAnnotation( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IReportingDataAnnotation|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateReportingDataAnnotation as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateReportingDataAnnotation as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateReportingDataAnnotation with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateReportingDataAnnotationRequest() - ); - request.reportingDataAnnotation ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateReportingDataAnnotationRequest', ['reportingDataAnnotation', 'name']); - request.reportingDataAnnotation.name = defaultValue1; - const expectedHeaderRequestParams = `reporting_data_annotation.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateReportingDataAnnotation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateReportingDataAnnotation(request), expectedError); - const actualRequest = (client.innerApiCalls.updateReportingDataAnnotation as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateReportingDataAnnotation as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateReportingDataAnnotation with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateReportingDataAnnotationRequest() - ); - request.reportingDataAnnotation ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateReportingDataAnnotationRequest', ['reportingDataAnnotation', 'name']); - request.reportingDataAnnotation.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateReportingDataAnnotation(request), expectedError); - }); - }); - - describe('deleteReportingDataAnnotation', () => { - it('invokes deleteReportingDataAnnotation without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteReportingDataAnnotationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteReportingDataAnnotationRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteReportingDataAnnotation = stubSimpleCall(expectedResponse); - const [response] = await client.deleteReportingDataAnnotation(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteReportingDataAnnotation as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteReportingDataAnnotation as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteReportingDataAnnotation without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteReportingDataAnnotationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteReportingDataAnnotationRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteReportingDataAnnotation = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteReportingDataAnnotation( - 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.deleteReportingDataAnnotation as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteReportingDataAnnotation as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteReportingDataAnnotation with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteReportingDataAnnotationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteReportingDataAnnotationRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteReportingDataAnnotation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteReportingDataAnnotation(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteReportingDataAnnotation as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteReportingDataAnnotation as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteReportingDataAnnotation with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.DeleteReportingDataAnnotationRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.DeleteReportingDataAnnotationRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteReportingDataAnnotation(request), expectedError); - }); - }); - - describe('submitUserDeletion', () => { - it('invokes submitUserDeletion without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SubmitUserDeletionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.SubmitUserDeletionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SubmitUserDeletionResponse() - ); - client.innerApiCalls.submitUserDeletion = stubSimpleCall(expectedResponse); - const [response] = await client.submitUserDeletion(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.submitUserDeletion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.submitUserDeletion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes submitUserDeletion without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SubmitUserDeletionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.SubmitUserDeletionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SubmitUserDeletionResponse() - ); - client.innerApiCalls.submitUserDeletion = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.submitUserDeletion( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ISubmitUserDeletionResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.submitUserDeletion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.submitUserDeletion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes submitUserDeletion with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SubmitUserDeletionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.SubmitUserDeletionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.submitUserDeletion = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.submitUserDeletion(request), expectedError); - const actualRequest = (client.innerApiCalls.submitUserDeletion as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.submitUserDeletion as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes submitUserDeletion with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SubmitUserDeletionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.SubmitUserDeletionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.submitUserDeletion(request), expectedError); - }); - }); - - describe('updateSubpropertySyncConfig', () => { - it('invokes updateSubpropertySyncConfig without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateSubpropertySyncConfigRequest() - ); - request.subpropertySyncConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateSubpropertySyncConfigRequest', ['subpropertySyncConfig', 'name']); - request.subpropertySyncConfig.name = defaultValue1; - const expectedHeaderRequestParams = `subproperty_sync_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig() - ); - client.innerApiCalls.updateSubpropertySyncConfig = stubSimpleCall(expectedResponse); - const [response] = await client.updateSubpropertySyncConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateSubpropertySyncConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSubpropertySyncConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateSubpropertySyncConfig without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateSubpropertySyncConfigRequest() - ); - request.subpropertySyncConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateSubpropertySyncConfigRequest', ['subpropertySyncConfig', 'name']); - request.subpropertySyncConfig.name = defaultValue1; - const expectedHeaderRequestParams = `subproperty_sync_config.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig() - ); - client.innerApiCalls.updateSubpropertySyncConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateSubpropertySyncConfig( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateSubpropertySyncConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSubpropertySyncConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateSubpropertySyncConfig with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateSubpropertySyncConfigRequest() - ); - request.subpropertySyncConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateSubpropertySyncConfigRequest', ['subpropertySyncConfig', 'name']); - request.subpropertySyncConfig.name = defaultValue1; - const expectedHeaderRequestParams = `subproperty_sync_config.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateSubpropertySyncConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateSubpropertySyncConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.updateSubpropertySyncConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateSubpropertySyncConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateSubpropertySyncConfig with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UpdateSubpropertySyncConfigRequest() - ); - request.subpropertySyncConfig ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.UpdateSubpropertySyncConfigRequest', ['subpropertySyncConfig', 'name']); - request.subpropertySyncConfig.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateSubpropertySyncConfig(request), expectedError); - }); - }); - - describe('getSubpropertySyncConfig', () => { - it('invokes getSubpropertySyncConfig without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetSubpropertySyncConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetSubpropertySyncConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig() - ); - client.innerApiCalls.getSubpropertySyncConfig = stubSimpleCall(expectedResponse); - const [response] = await client.getSubpropertySyncConfig(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSubpropertySyncConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSubpropertySyncConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getSubpropertySyncConfig without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetSubpropertySyncConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetSubpropertySyncConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig() - ); - client.innerApiCalls.getSubpropertySyncConfig = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getSubpropertySyncConfig( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getSubpropertySyncConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSubpropertySyncConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getSubpropertySyncConfig with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetSubpropertySyncConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetSubpropertySyncConfigRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getSubpropertySyncConfig = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getSubpropertySyncConfig(request), expectedError); - const actualRequest = (client.innerApiCalls.getSubpropertySyncConfig as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getSubpropertySyncConfig as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getSubpropertySyncConfig with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetSubpropertySyncConfigRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetSubpropertySyncConfigRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getSubpropertySyncConfig(request), expectedError); - }); - }); - - describe('getReportingIdentitySettings', () => { - it('invokes getReportingIdentitySettings without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetReportingIdentitySettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetReportingIdentitySettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ReportingIdentitySettings() - ); - client.innerApiCalls.getReportingIdentitySettings = stubSimpleCall(expectedResponse); - const [response] = await client.getReportingIdentitySettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getReportingIdentitySettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getReportingIdentitySettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getReportingIdentitySettings without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetReportingIdentitySettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetReportingIdentitySettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ReportingIdentitySettings() - ); - client.innerApiCalls.getReportingIdentitySettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getReportingIdentitySettings( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IReportingIdentitySettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getReportingIdentitySettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getReportingIdentitySettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getReportingIdentitySettings with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetReportingIdentitySettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetReportingIdentitySettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getReportingIdentitySettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getReportingIdentitySettings(request), expectedError); - const actualRequest = (client.innerApiCalls.getReportingIdentitySettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getReportingIdentitySettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getReportingIdentitySettings with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetReportingIdentitySettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetReportingIdentitySettingsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getReportingIdentitySettings(request), expectedError); - }); - }); - - describe('getUserProvidedDataSettings', () => { - it('invokes getUserProvidedDataSettings without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetUserProvidedDataSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetUserProvidedDataSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UserProvidedDataSettings() - ); - client.innerApiCalls.getUserProvidedDataSettings = stubSimpleCall(expectedResponse); - const [response] = await client.getUserProvidedDataSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getUserProvidedDataSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUserProvidedDataSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getUserProvidedDataSettings without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetUserProvidedDataSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetUserProvidedDataSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.UserProvidedDataSettings() - ); - client.innerApiCalls.getUserProvidedDataSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getUserProvidedDataSettings( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IUserProvidedDataSettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getUserProvidedDataSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUserProvidedDataSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getUserProvidedDataSettings with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetUserProvidedDataSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetUserProvidedDataSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getUserProvidedDataSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getUserProvidedDataSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.getUserProvidedDataSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUserProvidedDataSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getUserProvidedDataSettings with closed client', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.GetUserProvidedDataSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.GetUserProvidedDataSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getUserProvidedDataSettings(request), expectedError); - }); - }); - - describe('listAccounts', () => { - it('invokes listAccounts without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAccountsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Account()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Account()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Account()), - ]; - client.innerApiCalls.listAccounts = stubSimpleCall(expectedResponse); - const [response] = await client.listAccounts(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes listAccounts without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAccountsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Account()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Account()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Account()), - ]; - client.innerApiCalls.listAccounts = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listAccounts( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IAccount[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes listAccounts with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAccountsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listAccounts = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listAccounts(request), expectedError); - }); - - it('invokes listAccountsStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAccountsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Account()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Account()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Account()), - ]; - client.descriptors.page.listAccounts.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listAccountsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.Account[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.Account) => { - 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.listAccounts.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listAccounts, request)); - }); - - it('invokes listAccountsStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAccountsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listAccounts.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listAccountsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.Account[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.Account) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listAccounts.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listAccounts, request)); - }); - - it('uses async iteration with listAccounts without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAccountsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Account()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Account()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Account()), - ]; - client.descriptors.page.listAccounts.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.IAccount[] = []; - const iterable = client.listAccountsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listConversionEventsStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListConversionEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListConversionEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ConversionEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ConversionEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ConversionEvent(), + ), + ]; + client.descriptors.page.listConversionEvents.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listConversionEventsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.ConversionEvent[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.ConversionEvent) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert(stub.calledOnce); + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listConversionEvents.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listConversionEvents, request), + ); + assert( + (client.descriptors.page.listConversionEvents.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listConversionEventsStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListConversionEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListConversionEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listConversionEvents.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listConversionEventsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.ConversionEvent[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.ConversionEvent) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert(stub.calledOnce); + assert( + (client.descriptors.page.listConversionEvents.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listConversionEvents, request), + ); + assert( + (client.descriptors.page.listConversionEvents.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listConversionEvents without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListConversionEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListConversionEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ConversionEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ConversionEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ConversionEvent(), + ), + ]; + client.descriptors.page.listConversionEvents.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.IConversionEvent[] = + []; + const iterable = client.listConversionEventsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert(stub.calledOnce); + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listConversionEvents.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listConversionEvents.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listConversionEvents with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListConversionEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListConversionEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listConversionEvents.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listConversionEventsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.IConversionEvent[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert(stub.calledOnce); + assert.deepStrictEqual( + ( + client.descriptors.page.listConversionEvents.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listConversionEvents.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listKeyEvents', () => { + it('invokes listKeyEvents without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListKeyEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListKeyEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.KeyEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.KeyEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.KeyEvent(), + ), + ]; + client.innerApiCalls.listKeyEvents = stubSimpleCall(expectedResponse); + const [response] = await client.listKeyEvents(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listKeyEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listKeyEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listKeyEvents without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListKeyEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListKeyEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.KeyEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.KeyEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.KeyEvent(), + ), + ]; + client.innerApiCalls.listKeyEvents = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listKeyEvents( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IKeyEvent[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listAccounts.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); - - it('uses async iteration with listAccounts with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAccountsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listAccounts.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listAccountsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.IAccount[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listAccounts.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); - }); - - describe('listAccountSummaries', () => { - it('invokes listAccountSummaries without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAccountSummariesRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccountSummary()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccountSummary()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccountSummary()), - ]; - client.innerApiCalls.listAccountSummaries = stubSimpleCall(expectedResponse); - const [response] = await client.listAccountSummaries(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes listAccountSummaries without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAccountSummariesRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccountSummary()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccountSummary()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccountSummary()), - ]; - client.innerApiCalls.listAccountSummaries = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listAccountSummaries( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IAccountSummary[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes listAccountSummaries with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAccountSummariesRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listAccountSummaries = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listAccountSummaries(request), expectedError); - }); - - it('invokes listAccountSummariesStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAccountSummariesRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccountSummary()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccountSummary()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccountSummary()), - ]; - client.descriptors.page.listAccountSummaries.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listAccountSummariesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.AccountSummary[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.AccountSummary) => { - 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.listAccountSummaries.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listAccountSummaries, request)); - }); - - it('invokes listAccountSummariesStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAccountSummariesRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listAccountSummaries.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listAccountSummariesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.AccountSummary[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.AccountSummary) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listAccountSummaries.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listAccountSummaries, request)); - }); - - it('uses async iteration with listAccountSummaries without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAccountSummariesRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccountSummary()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccountSummary()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccountSummary()), - ]; - client.descriptors.page.listAccountSummaries.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.IAccountSummary[] = []; - const iterable = client.listAccountSummariesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listKeyEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listKeyEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listKeyEvents with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListKeyEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListKeyEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listKeyEvents = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listKeyEvents(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listKeyEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listKeyEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listKeyEventsStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListKeyEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListKeyEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.KeyEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.KeyEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.KeyEvent(), + ), + ]; + client.descriptors.page.listKeyEvents.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listKeyEventsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.KeyEvent[] = []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.KeyEvent) => { + 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.listKeyEvents.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listKeyEvents, request), + ); + assert( + (client.descriptors.page.listKeyEvents.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listKeyEventsStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListKeyEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListKeyEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listKeyEvents.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listKeyEventsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.KeyEvent[] = []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.KeyEvent) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listKeyEvents.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listKeyEvents, request), + ); + assert( + (client.descriptors.page.listKeyEvents.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listKeyEvents without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListKeyEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListKeyEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.KeyEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.KeyEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.KeyEvent(), + ), + ]; + client.descriptors.page.listKeyEvents.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.IKeyEvent[] = []; + const iterable = client.listKeyEventsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listKeyEvents.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listKeyEvents.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listKeyEvents with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListKeyEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListKeyEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listKeyEvents.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listKeyEventsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.IKeyEvent[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listKeyEvents.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listKeyEvents.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listDisplayVideo360AdvertiserLinks', () => { + it('invokes listDisplayVideo360AdvertiserLinks without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink(), + ), + ]; + client.innerApiCalls.listDisplayVideo360AdvertiserLinks = + stubSimpleCall(expectedResponse); + const [response] = + await client.listDisplayVideo360AdvertiserLinks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDisplayVideo360AdvertiserLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDisplayVideo360AdvertiserLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDisplayVideo360AdvertiserLinks without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink(), + ), + ]; + client.innerApiCalls.listDisplayVideo360AdvertiserLinks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listDisplayVideo360AdvertiserLinks( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listAccountSummaries.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); - - it('uses async iteration with listAccountSummaries with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAccountSummariesRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listAccountSummaries.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listAccountSummariesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.IAccountSummary[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listAccountSummaries.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); - }); - - describe('listProperties', () => { - it('invokes listProperties without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListPropertiesRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Property()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Property()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Property()), - ]; - client.innerApiCalls.listProperties = stubSimpleCall(expectedResponse); - const [response] = await client.listProperties(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes listProperties without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListPropertiesRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Property()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Property()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Property()), - ]; - client.innerApiCalls.listProperties = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listProperties( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IProperty[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes listProperties with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListPropertiesRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listProperties = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listProperties(request), expectedError); - }); - - it('invokes listPropertiesStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListPropertiesRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Property()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Property()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Property()), - ]; - client.descriptors.page.listProperties.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listPropertiesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.Property[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.Property) => { - 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.listProperties.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listProperties, request)); - }); - - it('invokes listPropertiesStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListPropertiesRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listProperties.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listPropertiesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.Property[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.Property) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listProperties.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listProperties, request)); - }); - - it('uses async iteration with listProperties without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListPropertiesRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Property()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Property()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Property()), - ]; - client.descriptors.page.listProperties.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.IProperty[] = []; - const iterable = client.listPropertiesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDisplayVideo360AdvertiserLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDisplayVideo360AdvertiserLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDisplayVideo360AdvertiserLinks with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listDisplayVideo360AdvertiserLinks = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listDisplayVideo360AdvertiserLinks(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listDisplayVideo360AdvertiserLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDisplayVideo360AdvertiserLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDisplayVideo360AdvertiserLinksStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink(), + ), + ]; + client.descriptors.page.listDisplayVideo360AdvertiserLinks.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listDisplayVideo360AdvertiserLinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink, + ) => { + 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.listDisplayVideo360AdvertiserLinks + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listDisplayVideo360AdvertiserLinks, + request, + ), + ); + assert( + ( + client.descriptors.page.listDisplayVideo360AdvertiserLinks + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('invokes listDisplayVideo360AdvertiserLinksStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDisplayVideo360AdvertiserLinks.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listDisplayVideo360AdvertiserLinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listDisplayVideo360AdvertiserLinks + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listDisplayVideo360AdvertiserLinks, + request, + ), + ); + assert( + ( + client.descriptors.page.listDisplayVideo360AdvertiserLinks + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listDisplayVideo360AdvertiserLinks without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink(), + ), + ]; + client.descriptors.page.listDisplayVideo360AdvertiserLinks.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink[] = + []; + const iterable = client.listDisplayVideo360AdvertiserLinksAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listDisplayVideo360AdvertiserLinks + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listDisplayVideo360AdvertiserLinks + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listDisplayVideo360AdvertiserLinks with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDisplayVideo360AdvertiserLinks.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listDisplayVideo360AdvertiserLinksAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listDisplayVideo360AdvertiserLinks + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listDisplayVideo360AdvertiserLinks + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listDisplayVideo360AdvertiserLinkProposals', () => { + it('invokes listDisplayVideo360AdvertiserLinkProposals without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal(), + ), + ]; + client.innerApiCalls.listDisplayVideo360AdvertiserLinkProposals = + stubSimpleCall(expectedResponse); + const [response] = + await client.listDisplayVideo360AdvertiserLinkProposals(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls + .listDisplayVideo360AdvertiserLinkProposals as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .listDisplayVideo360AdvertiserLinkProposals as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDisplayVideo360AdvertiserLinkProposals without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal(), + ), + ]; + client.innerApiCalls.listDisplayVideo360AdvertiserLinkProposals = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listDisplayVideo360AdvertiserLinkProposals( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listProperties.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); - - it('uses async iteration with listProperties with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListPropertiesRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listProperties.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listPropertiesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.IProperty[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listProperties.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); - }); - - describe('listFirebaseLinks', () => { - it('invokes listFirebaseLinks without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListFirebaseLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListFirebaseLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.FirebaseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.FirebaseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.FirebaseLink()), - ]; - client.innerApiCalls.listFirebaseLinks = stubSimpleCall(expectedResponse); - const [response] = await client.listFirebaseLinks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listFirebaseLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listFirebaseLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listFirebaseLinks without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListFirebaseLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListFirebaseLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.FirebaseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.FirebaseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.FirebaseLink()), - ]; - client.innerApiCalls.listFirebaseLinks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listFirebaseLinks( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IFirebaseLink[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listFirebaseLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listFirebaseLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listFirebaseLinks with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListFirebaseLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListFirebaseLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listFirebaseLinks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listFirebaseLinks(request), expectedError); - const actualRequest = (client.innerApiCalls.listFirebaseLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listFirebaseLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listFirebaseLinksStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListFirebaseLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListFirebaseLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.FirebaseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.FirebaseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.FirebaseLink()), - ]; - client.descriptors.page.listFirebaseLinks.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listFirebaseLinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.FirebaseLink[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.FirebaseLink) => { - 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.listFirebaseLinks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listFirebaseLinks, request)); - assert( - (client.descriptors.page.listFirebaseLinks.createStream 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 + .listDisplayVideo360AdvertiserLinkProposals as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .listDisplayVideo360AdvertiserLinkProposals as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listFirebaseLinksStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListFirebaseLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListFirebaseLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listFirebaseLinks.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listFirebaseLinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.FirebaseLink[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.FirebaseLink) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listFirebaseLinks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listFirebaseLinks, request)); - assert( - (client.descriptors.page.listFirebaseLinks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listDisplayVideo360AdvertiserLinkProposals with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listDisplayVideo360AdvertiserLinkProposals = + stubSimpleCall(undefined, expectedError); + await assert.rejects( + client.listDisplayVideo360AdvertiserLinkProposals(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls + .listDisplayVideo360AdvertiserLinkProposals as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls + .listDisplayVideo360AdvertiserLinkProposals as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listFirebaseLinks without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListFirebaseLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListFirebaseLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.FirebaseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.FirebaseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.FirebaseLink()), - ]; - client.descriptors.page.listFirebaseLinks.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.IFirebaseLink[] = []; - const iterable = client.listFirebaseLinksAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listDisplayVideo360AdvertiserLinkProposalsStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal(), + ), + ]; + client.descriptors.page.listDisplayVideo360AdvertiserLinkProposals.createStream = + stubPageStreamingCall(expectedResponse); + const stream = + client.listDisplayVideo360AdvertiserLinkProposalsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal, + ) => { + 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.listDisplayVideo360AdvertiserLinkProposals + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listDisplayVideo360AdvertiserLinkProposals, + request, + ), + ); + assert( + ( + client.descriptors.page.listDisplayVideo360AdvertiserLinkProposals + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('invokes listDisplayVideo360AdvertiserLinkProposalsStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDisplayVideo360AdvertiserLinkProposals.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = + client.listDisplayVideo360AdvertiserLinkProposalsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listDisplayVideo360AdvertiserLinkProposals + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listDisplayVideo360AdvertiserLinkProposals, + request, + ), + ); + assert( + ( + client.descriptors.page.listDisplayVideo360AdvertiserLinkProposals + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listDisplayVideo360AdvertiserLinkProposals without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal(), + ), + ]; + client.descriptors.page.listDisplayVideo360AdvertiserLinkProposals.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal[] = + []; + const iterable = + client.listDisplayVideo360AdvertiserLinkProposalsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listDisplayVideo360AdvertiserLinkProposals + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listDisplayVideo360AdvertiserLinkProposals + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listDisplayVideo360AdvertiserLinkProposals with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDisplayVideo360AdvertiserLinkProposals.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = + client.listDisplayVideo360AdvertiserLinkProposalsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listDisplayVideo360AdvertiserLinkProposals + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listDisplayVideo360AdvertiserLinkProposals + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listCustomDimensions', () => { + it('invokes listCustomDimensions without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListCustomDimensionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListCustomDimensionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomDimension(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomDimension(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomDimension(), + ), + ]; + client.innerApiCalls.listCustomDimensions = + stubSimpleCall(expectedResponse); + const [response] = await client.listCustomDimensions(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCustomDimensions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCustomDimensions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listCustomDimensions without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListCustomDimensionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListCustomDimensionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomDimension(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomDimension(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomDimension(), + ), + ]; + client.innerApiCalls.listCustomDimensions = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listCustomDimensions( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.ICustomDimension[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listFirebaseLinks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listFirebaseLinks.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.listCustomDimensions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCustomDimensions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listFirebaseLinks with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListFirebaseLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListFirebaseLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listFirebaseLinks.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listFirebaseLinksAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.IFirebaseLink[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listFirebaseLinks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listFirebaseLinks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listCustomDimensions with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListCustomDimensionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListCustomDimensionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listCustomDimensions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listCustomDimensions(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listCustomDimensions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCustomDimensions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listCustomDimensionsStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListCustomDimensionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListCustomDimensionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomDimension(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomDimension(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomDimension(), + ), + ]; + client.descriptors.page.listCustomDimensions.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listCustomDimensionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.CustomDimension[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.CustomDimension) => { + 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.listCustomDimensions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCustomDimensions, request), + ); + assert( + (client.descriptors.page.listCustomDimensions.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listCustomDimensionsStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListCustomDimensionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListCustomDimensionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCustomDimensions.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listCustomDimensionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.CustomDimension[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.CustomDimension) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listCustomDimensions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCustomDimensions, request), + ); + assert( + (client.descriptors.page.listCustomDimensions.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listCustomDimensions without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListCustomDimensionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListCustomDimensionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomDimension(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomDimension(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomDimension(), + ), + ]; + client.descriptors.page.listCustomDimensions.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.ICustomDimension[] = + []; + const iterable = client.listCustomDimensionsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listCustomDimensions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listCustomDimensions.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listCustomDimensions with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListCustomDimensionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListCustomDimensionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCustomDimensions.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listCustomDimensionsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.ICustomDimension[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listCustomDimensions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listCustomDimensions.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listCustomMetrics', () => { + it('invokes listCustomMetrics without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListCustomMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListCustomMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomMetric(), + ), + ]; + client.innerApiCalls.listCustomMetrics = stubSimpleCall(expectedResponse); + const [response] = await client.listCustomMetrics(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCustomMetrics as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCustomMetrics as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listCustomMetrics without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListCustomMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListCustomMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomMetric(), + ), + ]; + client.innerApiCalls.listCustomMetrics = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listCustomMetrics( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.ICustomMetric[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCustomMetrics as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCustomMetrics as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listCustomMetrics with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListCustomMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListCustomMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listCustomMetrics = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listCustomMetrics(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listCustomMetrics as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCustomMetrics as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listCustomMetricsStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListCustomMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListCustomMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomMetric(), + ), + ]; + client.descriptors.page.listCustomMetrics.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listCustomMetricsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.CustomMetric[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.CustomMetric) => { + 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.listCustomMetrics.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCustomMetrics, request), + ); + assert( + (client.descriptors.page.listCustomMetrics.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listCustomMetricsStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListCustomMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListCustomMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCustomMetrics.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listCustomMetricsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.CustomMetric[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.CustomMetric) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listCustomMetrics.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCustomMetrics, request), + ); + assert( + (client.descriptors.page.listCustomMetrics.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listCustomMetrics without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListCustomMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListCustomMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CustomMetric(), + ), + ]; + client.descriptors.page.listCustomMetrics.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.ICustomMetric[] = + []; + const iterable = client.listCustomMetricsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listCustomMetrics.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listCustomMetrics.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listCustomMetrics with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListCustomMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListCustomMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCustomMetrics.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listCustomMetricsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.ICustomMetric[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listCustomMetrics.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listCustomMetrics.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listDataStreams', () => { + it('invokes listDataStreams without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListDataStreamsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListDataStreamsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataStream(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataStream(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataStream(), + ), + ]; + client.innerApiCalls.listDataStreams = stubSimpleCall(expectedResponse); + const [response] = await client.listDataStreams(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDataStreams as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDataStreams as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDataStreams without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListDataStreamsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListDataStreamsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataStream(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataStream(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataStream(), + ), + ]; + client.innerApiCalls.listDataStreams = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listDataStreams( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IDataStream[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDataStreams as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDataStreams as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDataStreams with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListDataStreamsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListDataStreamsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listDataStreams = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listDataStreams(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listDataStreams as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDataStreams as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDataStreamsStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListDataStreamsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListDataStreamsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataStream(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataStream(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataStream(), + ), + ]; + client.descriptors.page.listDataStreams.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listDataStreamsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.DataStream[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.DataStream) => { + 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.listDataStreams.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listDataStreams, request), + ); + assert( + (client.descriptors.page.listDataStreams.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listDataStreamsStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListDataStreamsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListDataStreamsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDataStreams.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listDataStreamsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.DataStream[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.DataStream) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listDataStreams.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listDataStreams, request), + ); + assert( + (client.descriptors.page.listDataStreams.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listDataStreams without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListDataStreamsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListDataStreamsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataStream(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataStream(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.DataStream(), + ), + ]; + client.descriptors.page.listDataStreams.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.IDataStream[] = []; + const iterable = client.listDataStreamsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listDataStreams.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listDataStreams.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listDataStreams with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListDataStreamsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListDataStreamsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDataStreams.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listDataStreamsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.IDataStream[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listDataStreams.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listDataStreams.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listAudiences', () => { + it('invokes listAudiences without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAudiencesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListAudiencesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Audience(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Audience(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Audience(), + ), + ]; + client.innerApiCalls.listAudiences = stubSimpleCall(expectedResponse); + const [response] = await client.listAudiences(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listAudiences as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listAudiences as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listAudiences without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAudiencesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListAudiencesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Audience(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Audience(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Audience(), + ), + ]; + client.innerApiCalls.listAudiences = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listAudiences( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1alpha.IAudience[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listAudiences as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listAudiences as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listAudiences with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAudiencesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListAudiencesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listAudiences = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listAudiences(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listAudiences as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listAudiences as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listAudiencesStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAudiencesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListAudiencesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Audience(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Audience(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Audience(), + ), + ]; + client.descriptors.page.listAudiences.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listAudiencesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.Audience[] = []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.Audience) => { + 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.listAudiences.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listAudiences, request), + ); + assert( + (client.descriptors.page.listAudiences.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listAudiencesStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAudiencesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListAudiencesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listAudiences.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listAudiencesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.Audience[] = []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.Audience) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listAudiences.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listAudiences, request), + ); + assert( + (client.descriptors.page.listAudiences.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listAudiences without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAudiencesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListAudiencesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Audience(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Audience(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.Audience(), + ), + ]; + client.descriptors.page.listAudiences.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.IAudience[] = []; + const iterable = client.listAudiencesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listAudiences.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listAudiences.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listAudiences with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAudiencesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListAudiencesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listAudiences.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listAudiencesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.IAudience[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listAudiences.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listAudiences.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listSearchAds360Links', () => { + it('invokes listSearchAds360Links without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchAds360Link(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchAds360Link(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchAds360Link(), + ), + ]; + client.innerApiCalls.listSearchAds360Links = + stubSimpleCall(expectedResponse); + const [response] = await client.listSearchAds360Links(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listSearchAds360Links as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listSearchAds360Links as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listSearchAds360Links without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchAds360Link(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchAds360Link(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchAds360Link(), + ), + ]; + client.innerApiCalls.listSearchAds360Links = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listSearchAds360Links( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.ISearchAds360Link[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listSearchAds360Links as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listSearchAds360Links as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listSearchAds360Links with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listSearchAds360Links = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listSearchAds360Links(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listSearchAds360Links as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listSearchAds360Links as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listSearchAds360LinksStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchAds360Link(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchAds360Link(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchAds360Link(), + ), + ]; + client.descriptors.page.listSearchAds360Links.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listSearchAds360LinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.SearchAds360Link[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1alpha.SearchAds360Link, + ) => { + 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.listSearchAds360Links + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listSearchAds360Links, request), + ); + assert( + ( + client.descriptors.page.listSearchAds360Links + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('invokes listSearchAds360LinksStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listSearchAds360Links.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listSearchAds360LinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.SearchAds360Link[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1alpha.SearchAds360Link, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listSearchAds360Links + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listSearchAds360Links, request), + ); + assert( + ( + client.descriptors.page.listSearchAds360Links + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listSearchAds360Links without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchAds360Link(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchAds360Link(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SearchAds360Link(), + ), + ]; + client.descriptors.page.listSearchAds360Links.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.ISearchAds360Link[] = + []; + const iterable = client.listSearchAds360LinksAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listSearchAds360Links + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listSearchAds360Links + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listSearchAds360Links with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listSearchAds360Links.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listSearchAds360LinksAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.ISearchAds360Link[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listSearchAds360Links + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listSearchAds360Links + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listAccessBindings', () => { + it('invokes listAccessBindings without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAccessBindingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListAccessBindingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccessBinding(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccessBinding(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccessBinding(), + ), + ]; + client.innerApiCalls.listAccessBindings = + stubSimpleCall(expectedResponse); + const [response] = await client.listAccessBindings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listAccessBindings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listAccessBindings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listGoogleAdsLinks', () => { - it('invokes listGoogleAdsLinks without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.GoogleAdsLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.GoogleAdsLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.GoogleAdsLink()), - ]; - client.innerApiCalls.listGoogleAdsLinks = stubSimpleCall(expectedResponse); - const [response] = await client.listGoogleAdsLinks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listGoogleAdsLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGoogleAdsLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listGoogleAdsLinks without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.GoogleAdsLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.GoogleAdsLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.GoogleAdsLink()), - ]; - client.innerApiCalls.listGoogleAdsLinks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listGoogleAdsLinks( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IGoogleAdsLink[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listGoogleAdsLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGoogleAdsLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listGoogleAdsLinks with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listGoogleAdsLinks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listGoogleAdsLinks(request), expectedError); - const actualRequest = (client.innerApiCalls.listGoogleAdsLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGoogleAdsLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listGoogleAdsLinksStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.GoogleAdsLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.GoogleAdsLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.GoogleAdsLink()), - ]; - client.descriptors.page.listGoogleAdsLinks.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listGoogleAdsLinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.GoogleAdsLink[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.GoogleAdsLink) => { - 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.listGoogleAdsLinks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listGoogleAdsLinks, request)); - assert( - (client.descriptors.page.listGoogleAdsLinks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listAccessBindings without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAccessBindingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListAccessBindingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccessBinding(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccessBinding(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccessBinding(), + ), + ]; + client.innerApiCalls.listAccessBindings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listAccessBindings( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.IAccessBinding[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listAccessBindings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listAccessBindings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listGoogleAdsLinksStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listGoogleAdsLinks.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listGoogleAdsLinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.GoogleAdsLink[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.GoogleAdsLink) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listGoogleAdsLinks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listGoogleAdsLinks, request)); - assert( - (client.descriptors.page.listGoogleAdsLinks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listAccessBindings with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAccessBindingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListAccessBindingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listAccessBindings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listAccessBindings(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listAccessBindings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listAccessBindings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listGoogleAdsLinks without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.GoogleAdsLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.GoogleAdsLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.GoogleAdsLink()), - ]; - client.descriptors.page.listGoogleAdsLinks.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.IGoogleAdsLink[] = []; - const iterable = client.listGoogleAdsLinksAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listGoogleAdsLinks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listGoogleAdsLinks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listAccessBindingsStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAccessBindingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListAccessBindingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccessBinding(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccessBinding(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccessBinding(), + ), + ]; + client.descriptors.page.listAccessBindings.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listAccessBindingsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.AccessBinding[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.AccessBinding) => { + 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.listAccessBindings.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listAccessBindings, request), + ); + assert( + (client.descriptors.page.listAccessBindings.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listGoogleAdsLinks with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListGoogleAdsLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listGoogleAdsLinks.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listGoogleAdsLinksAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.IGoogleAdsLink[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listGoogleAdsLinks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listGoogleAdsLinks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listAccessBindingsStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAccessBindingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListAccessBindingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listAccessBindings.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listAccessBindingsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.AccessBinding[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.AccessBinding) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listAccessBindings.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listAccessBindings, request), + ); + assert( + (client.descriptors.page.listAccessBindings.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('listMeasurementProtocolSecrets', () => { - it('invokes listMeasurementProtocolSecrets without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret()), - ]; - client.innerApiCalls.listMeasurementProtocolSecrets = stubSimpleCall(expectedResponse); - const [response] = await client.listMeasurementProtocolSecrets(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listMeasurementProtocolSecrets without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret()), - ]; - client.innerApiCalls.listMeasurementProtocolSecrets = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listMeasurementProtocolSecrets( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listMeasurementProtocolSecrets with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listMeasurementProtocolSecrets = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listMeasurementProtocolSecrets(request), expectedError); - const actualRequest = (client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listMeasurementProtocolSecretsStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret()), - ]; - client.descriptors.page.listMeasurementProtocolSecrets.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listMeasurementProtocolSecretsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret) => { - 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.listMeasurementProtocolSecrets.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listMeasurementProtocolSecrets, request)); - assert( - (client.descriptors.page.listMeasurementProtocolSecrets.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listAccessBindings without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAccessBindingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListAccessBindingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccessBinding(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccessBinding(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AccessBinding(), + ), + ]; + client.descriptors.page.listAccessBindings.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.IAccessBinding[] = + []; + const iterable = client.listAccessBindingsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listAccessBindings.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listAccessBindings.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listMeasurementProtocolSecretsStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listMeasurementProtocolSecrets.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listMeasurementProtocolSecretsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listMeasurementProtocolSecrets.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listMeasurementProtocolSecrets, request)); - assert( - (client.descriptors.page.listMeasurementProtocolSecrets.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listAccessBindings with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAccessBindingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListAccessBindingsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listAccessBindings.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listAccessBindingsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.IAccessBinding[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listAccessBindings.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listAccessBindings.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listExpandedDataSets', () => { + it('invokes listExpandedDataSets without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ExpandedDataSet(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ExpandedDataSet(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ExpandedDataSet(), + ), + ]; + client.innerApiCalls.listExpandedDataSets = + stubSimpleCall(expectedResponse); + const [response] = await client.listExpandedDataSets(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listExpandedDataSets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listExpandedDataSets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listMeasurementProtocolSecrets without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.MeasurementProtocolSecret()), - ]; - client.descriptors.page.listMeasurementProtocolSecrets.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret[] = []; - const iterable = client.listMeasurementProtocolSecretsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listExpandedDataSets without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ExpandedDataSet(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ExpandedDataSet(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ExpandedDataSet(), + ), + ]; + client.innerApiCalls.listExpandedDataSets = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listExpandedDataSets( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.IExpandedDataSet[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listMeasurementProtocolSecrets.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listMeasurementProtocolSecrets.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.listExpandedDataSets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listExpandedDataSets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listMeasurementProtocolSecrets with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListMeasurementProtocolSecretsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listMeasurementProtocolSecrets.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listMeasurementProtocolSecretsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.IMeasurementProtocolSecret[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listMeasurementProtocolSecrets.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listMeasurementProtocolSecrets.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listExpandedDataSets with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listExpandedDataSets = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listExpandedDataSets(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listExpandedDataSets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listExpandedDataSets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listSKAdNetworkConversionValueSchemas', () => { - it('invokes listSKAdNetworkConversionValueSchemas without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema()), - ]; - client.innerApiCalls.listSkAdNetworkConversionValueSchemas = stubSimpleCall(expectedResponse); - const [response] = await client.listSKAdNetworkConversionValueSchemas(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listSkAdNetworkConversionValueSchemas as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listSkAdNetworkConversionValueSchemas as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listSKAdNetworkConversionValueSchemas without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema()), - ]; - client.innerApiCalls.listSkAdNetworkConversionValueSchemas = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listSKAdNetworkConversionValueSchemas( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listSkAdNetworkConversionValueSchemas as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listSkAdNetworkConversionValueSchemas as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listSKAdNetworkConversionValueSchemas with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listSkAdNetworkConversionValueSchemas = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listSKAdNetworkConversionValueSchemas(request), expectedError); - const actualRequest = (client.innerApiCalls.listSkAdNetworkConversionValueSchemas as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listSkAdNetworkConversionValueSchemas as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listSKAdNetworkConversionValueSchemasStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema()), - ]; - client.descriptors.page.listSKAdNetworkConversionValueSchemas.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listSKAdNetworkConversionValueSchemasStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema) => { - 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.listSKAdNetworkConversionValueSchemas.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listSkAdNetworkConversionValueSchemas, request)); - assert( - (client.descriptors.page.listSKAdNetworkConversionValueSchemas.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listExpandedDataSetsStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ExpandedDataSet(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ExpandedDataSet(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ExpandedDataSet(), + ), + ]; + client.descriptors.page.listExpandedDataSets.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listExpandedDataSetsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.ExpandedDataSet[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.ExpandedDataSet) => { + 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.listExpandedDataSets.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listExpandedDataSets, request), + ); + assert( + (client.descriptors.page.listExpandedDataSets.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listSKAdNetworkConversionValueSchemasStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listSKAdNetworkConversionValueSchemas.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listSKAdNetworkConversionValueSchemasStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listSKAdNetworkConversionValueSchemas.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listSkAdNetworkConversionValueSchemas, request)); - assert( - (client.descriptors.page.listSKAdNetworkConversionValueSchemas.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listExpandedDataSetsStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listExpandedDataSets.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listExpandedDataSetsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.ExpandedDataSet[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.ExpandedDataSet) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listExpandedDataSets.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listExpandedDataSets, request), + ); + assert( + (client.descriptors.page.listExpandedDataSets.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listSKAdNetworkConversionValueSchemas without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SKAdNetworkConversionValueSchema()), - ]; - client.descriptors.page.listSKAdNetworkConversionValueSchemas.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema[] = []; - const iterable = client.listSKAdNetworkConversionValueSchemasAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listSKAdNetworkConversionValueSchemas.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listSKAdNetworkConversionValueSchemas.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listExpandedDataSets without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ExpandedDataSet(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ExpandedDataSet(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ExpandedDataSet(), + ), + ]; + client.descriptors.page.listExpandedDataSets.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.IExpandedDataSet[] = + []; + const iterable = client.listExpandedDataSetsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listExpandedDataSets.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listExpandedDataSets.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listSKAdNetworkConversionValueSchemas with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSKAdNetworkConversionValueSchemasRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listSKAdNetworkConversionValueSchemas.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listSKAdNetworkConversionValueSchemasAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.ISKAdNetworkConversionValueSchema[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listSKAdNetworkConversionValueSchemas.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listSKAdNetworkConversionValueSchemas.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listExpandedDataSets with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listExpandedDataSets.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listExpandedDataSetsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.IExpandedDataSet[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listExpandedDataSets.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listExpandedDataSets.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listChannelGroups', () => { + it('invokes listChannelGroups without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListChannelGroupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListChannelGroupsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChannelGroup(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChannelGroup(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChannelGroup(), + ), + ]; + client.innerApiCalls.listChannelGroups = stubSimpleCall(expectedResponse); + const [response] = await client.listChannelGroups(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listChannelGroups as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listChannelGroups as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('searchChangeHistoryEvents', () => { - it('invokes searchChangeHistoryEvents without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest', ['account']); - request.account = defaultValue1; - const expectedHeaderRequestParams = `account=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent()), - ]; - client.innerApiCalls.searchChangeHistoryEvents = stubSimpleCall(expectedResponse); - const [response] = await client.searchChangeHistoryEvents(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.searchChangeHistoryEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchChangeHistoryEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes searchChangeHistoryEvents without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest', ['account']); - request.account = defaultValue1; - const expectedHeaderRequestParams = `account=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent()), - ]; - client.innerApiCalls.searchChangeHistoryEvents = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.searchChangeHistoryEvents( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IChangeHistoryEvent[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.searchChangeHistoryEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchChangeHistoryEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes searchChangeHistoryEvents with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest', ['account']); - request.account = defaultValue1; - const expectedHeaderRequestParams = `account=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.searchChangeHistoryEvents = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.searchChangeHistoryEvents(request), expectedError); - const actualRequest = (client.innerApiCalls.searchChangeHistoryEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchChangeHistoryEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes searchChangeHistoryEventsStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest', ['account']); - request.account = defaultValue1; - const expectedHeaderRequestParams = `account=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent()), - ]; - client.descriptors.page.searchChangeHistoryEvents.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.searchChangeHistoryEventsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.ChangeHistoryEvent[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.ChangeHistoryEvent) => { - 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.searchChangeHistoryEvents.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.searchChangeHistoryEvents, request)); - assert( - (client.descriptors.page.searchChangeHistoryEvents.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listChannelGroups without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListChannelGroupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListChannelGroupsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChannelGroup(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChannelGroup(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChannelGroup(), + ), + ]; + client.innerApiCalls.listChannelGroups = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listChannelGroups( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.IChannelGroup[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listChannelGroups as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listChannelGroups as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes searchChangeHistoryEventsStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest', ['account']); - request.account = defaultValue1; - const expectedHeaderRequestParams = `account=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.searchChangeHistoryEvents.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.searchChangeHistoryEventsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.ChangeHistoryEvent[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.ChangeHistoryEvent) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.searchChangeHistoryEvents.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.searchChangeHistoryEvents, request)); - assert( - (client.descriptors.page.searchChangeHistoryEvents.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listChannelGroups with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListChannelGroupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListChannelGroupsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listChannelGroups = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listChannelGroups(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listChannelGroups as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listChannelGroups as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with searchChangeHistoryEvents without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest', ['account']); - request.account = defaultValue1; - const expectedHeaderRequestParams = `account=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChangeHistoryEvent()), - ]; - client.descriptors.page.searchChangeHistoryEvents.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.IChangeHistoryEvent[] = []; - const iterable = client.searchChangeHistoryEventsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.searchChangeHistoryEvents.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.searchChangeHistoryEvents.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listChannelGroupsStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListChannelGroupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListChannelGroupsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChannelGroup(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChannelGroup(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChannelGroup(), + ), + ]; + client.descriptors.page.listChannelGroups.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listChannelGroupsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.ChannelGroup[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.ChannelGroup) => { + 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.listChannelGroups.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listChannelGroups, request), + ); + assert( + (client.descriptors.page.listChannelGroups.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with searchChangeHistoryEvents with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.SearchChangeHistoryEventsRequest', ['account']); - request.account = defaultValue1; - const expectedHeaderRequestParams = `account=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.searchChangeHistoryEvents.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.searchChangeHistoryEventsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.IChangeHistoryEvent[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.searchChangeHistoryEvents.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.searchChangeHistoryEvents.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listChannelGroupsStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListChannelGroupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListChannelGroupsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listChannelGroups.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listChannelGroupsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.ChannelGroup[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.ChannelGroup) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listChannelGroups.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listChannelGroups, request), + ); + assert( + (client.descriptors.page.listChannelGroups.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('listConversionEvents', () => { - it('invokes listConversionEvents without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListConversionEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListConversionEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ConversionEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ConversionEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ConversionEvent()), - ]; - client.innerApiCalls.listConversionEvents = stubSimpleCall(expectedResponse); - const [response] = await client.listConversionEvents(request); - assert(stub.calledOnce); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listConversionEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listConversionEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listConversionEvents without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListConversionEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListConversionEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ConversionEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ConversionEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ConversionEvent()), - ]; - client.innerApiCalls.listConversionEvents = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listConversionEvents( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IConversionEvent[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert(stub.calledOnce); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listConversionEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listConversionEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listConversionEvents with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListConversionEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListConversionEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listConversionEvents = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listConversionEvents(request), expectedError); - assert(stub.calledOnce); - const actualRequest = (client.innerApiCalls.listConversionEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listConversionEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listConversionEventsStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListConversionEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListConversionEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ConversionEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ConversionEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ConversionEvent()), - ]; - client.descriptors.page.listConversionEvents.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listConversionEventsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.ConversionEvent[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.ConversionEvent) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert(stub.calledOnce); - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listConversionEvents.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listConversionEvents, request)); - assert( - (client.descriptors.page.listConversionEvents.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listChannelGroups without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListChannelGroupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListChannelGroupsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChannelGroup(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChannelGroup(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ChannelGroup(), + ), + ]; + client.descriptors.page.listChannelGroups.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.IChannelGroup[] = + []; + const iterable = client.listChannelGroupsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listChannelGroups.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listChannelGroups.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listConversionEventsStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListConversionEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListConversionEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listConversionEvents.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listConversionEventsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.ConversionEvent[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.ConversionEvent) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert(stub.calledOnce); - assert((client.descriptors.page.listConversionEvents.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listConversionEvents, request)); - assert( - (client.descriptors.page.listConversionEvents.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listChannelGroups with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListChannelGroupsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListChannelGroupsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listChannelGroups.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listChannelGroupsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.IChannelGroup[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listChannelGroups.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listChannelGroups.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listBigQueryLinks', () => { + it('invokes listBigQueryLinks without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListBigQueryLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListBigQueryLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BigQueryLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BigQueryLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BigQueryLink(), + ), + ]; + client.innerApiCalls.listBigQueryLinks = stubSimpleCall(expectedResponse); + const [response] = await client.listBigQueryLinks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBigQueryLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBigQueryLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listConversionEvents without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListConversionEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListConversionEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ConversionEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ConversionEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ConversionEvent()), - ]; - client.descriptors.page.listConversionEvents.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.IConversionEvent[] = []; - const iterable = client.listConversionEventsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listBigQueryLinks without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListBigQueryLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListBigQueryLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BigQueryLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BigQueryLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BigQueryLink(), + ), + ]; + client.innerApiCalls.listBigQueryLinks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listBigQueryLinks( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.IBigQueryLink[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert(stub.calledOnce); - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listConversionEvents.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listConversionEvents.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.listBigQueryLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBigQueryLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listConversionEvents with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListConversionEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListConversionEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listConversionEvents.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listConversionEventsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.IConversionEvent[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert(stub.calledOnce); - assert.deepStrictEqual( - (client.descriptors.page.listConversionEvents.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listConversionEvents.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listBigQueryLinks with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListBigQueryLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListBigQueryLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listBigQueryLinks = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listBigQueryLinks(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listBigQueryLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBigQueryLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listKeyEvents', () => { - it('invokes listKeyEvents without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListKeyEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListKeyEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.KeyEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.KeyEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.KeyEvent()), - ]; - client.innerApiCalls.listKeyEvents = stubSimpleCall(expectedResponse); - const [response] = await client.listKeyEvents(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listKeyEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listKeyEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listKeyEvents without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListKeyEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListKeyEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.KeyEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.KeyEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.KeyEvent()), - ]; - client.innerApiCalls.listKeyEvents = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listKeyEvents( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IKeyEvent[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listKeyEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listKeyEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listKeyEvents with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListKeyEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListKeyEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listKeyEvents = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listKeyEvents(request), expectedError); - const actualRequest = (client.innerApiCalls.listKeyEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listKeyEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listKeyEventsStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListKeyEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListKeyEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.KeyEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.KeyEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.KeyEvent()), - ]; - client.descriptors.page.listKeyEvents.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listKeyEventsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.KeyEvent[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.KeyEvent) => { - 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.listKeyEvents.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listKeyEvents, request)); - assert( - (client.descriptors.page.listKeyEvents.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listBigQueryLinksStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListBigQueryLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListBigQueryLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BigQueryLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BigQueryLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BigQueryLink(), + ), + ]; + client.descriptors.page.listBigQueryLinks.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listBigQueryLinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.BigQueryLink[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.BigQueryLink) => { + 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.listBigQueryLinks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listBigQueryLinks, request), + ); + assert( + (client.descriptors.page.listBigQueryLinks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listKeyEventsStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListKeyEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListKeyEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listKeyEvents.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listKeyEventsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.KeyEvent[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.KeyEvent) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listKeyEvents.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listKeyEvents, request)); - assert( - (client.descriptors.page.listKeyEvents.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listBigQueryLinksStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListBigQueryLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListBigQueryLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listBigQueryLinks.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listBigQueryLinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.BigQueryLink[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.BigQueryLink) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listBigQueryLinks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listBigQueryLinks, request), + ); + assert( + (client.descriptors.page.listBigQueryLinks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listKeyEvents without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListKeyEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListKeyEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.KeyEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.KeyEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.KeyEvent()), - ]; - client.descriptors.page.listKeyEvents.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.IKeyEvent[] = []; - const iterable = client.listKeyEventsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listKeyEvents.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listKeyEvents.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listBigQueryLinks without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListBigQueryLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListBigQueryLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BigQueryLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BigQueryLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.BigQueryLink(), + ), + ]; + client.descriptors.page.listBigQueryLinks.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.IBigQueryLink[] = + []; + const iterable = client.listBigQueryLinksAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listBigQueryLinks.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listBigQueryLinks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listKeyEvents with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListKeyEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListKeyEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listKeyEvents.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listKeyEventsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.IKeyEvent[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listKeyEvents.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listKeyEvents.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listBigQueryLinks with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListBigQueryLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListBigQueryLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listBigQueryLinks.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listBigQueryLinksAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.IBigQueryLink[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listBigQueryLinks.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listBigQueryLinks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listAdSenseLinks', () => { + it('invokes listAdSenseLinks without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAdSenseLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListAdSenseLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AdSenseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AdSenseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AdSenseLink(), + ), + ]; + client.innerApiCalls.listAdSenseLinks = stubSimpleCall(expectedResponse); + const [response] = await client.listAdSenseLinks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listAdSenseLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listAdSenseLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listDisplayVideo360AdvertiserLinks', () => { - it('invokes listDisplayVideo360AdvertiserLinks without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink()), - ]; - client.innerApiCalls.listDisplayVideo360AdvertiserLinks = stubSimpleCall(expectedResponse); - const [response] = await client.listDisplayVideo360AdvertiserLinks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDisplayVideo360AdvertiserLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDisplayVideo360AdvertiserLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listDisplayVideo360AdvertiserLinks without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink()), - ]; - client.innerApiCalls.listDisplayVideo360AdvertiserLinks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listDisplayVideo360AdvertiserLinks( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDisplayVideo360AdvertiserLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDisplayVideo360AdvertiserLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listDisplayVideo360AdvertiserLinks with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listDisplayVideo360AdvertiserLinks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listDisplayVideo360AdvertiserLinks(request), expectedError); - const actualRequest = (client.innerApiCalls.listDisplayVideo360AdvertiserLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDisplayVideo360AdvertiserLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listDisplayVideo360AdvertiserLinksStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink()), - ]; - client.descriptors.page.listDisplayVideo360AdvertiserLinks.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listDisplayVideo360AdvertiserLinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink) => { - 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.listDisplayVideo360AdvertiserLinks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listDisplayVideo360AdvertiserLinks, request)); - assert( - (client.descriptors.page.listDisplayVideo360AdvertiserLinks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listAdSenseLinks without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAdSenseLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListAdSenseLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AdSenseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AdSenseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AdSenseLink(), + ), + ]; + client.innerApiCalls.listAdSenseLinks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listAdSenseLinks( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.IAdSenseLink[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listAdSenseLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listAdSenseLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listDisplayVideo360AdvertiserLinksStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listDisplayVideo360AdvertiserLinks.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listDisplayVideo360AdvertiserLinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listDisplayVideo360AdvertiserLinks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listDisplayVideo360AdvertiserLinks, request)); - assert( - (client.descriptors.page.listDisplayVideo360AdvertiserLinks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listAdSenseLinks with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAdSenseLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListAdSenseLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listAdSenseLinks = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listAdSenseLinks(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listAdSenseLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listAdSenseLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listDisplayVideo360AdvertiserLinks without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLink()), - ]; - client.descriptors.page.listDisplayVideo360AdvertiserLinks.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink[] = []; - const iterable = client.listDisplayVideo360AdvertiserLinksAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listDisplayVideo360AdvertiserLinks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listDisplayVideo360AdvertiserLinks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listAdSenseLinksStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAdSenseLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListAdSenseLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AdSenseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AdSenseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AdSenseLink(), + ), + ]; + client.descriptors.page.listAdSenseLinks.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listAdSenseLinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.AdSenseLink[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.AdSenseLink) => { + 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.listAdSenseLinks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listAdSenseLinks, request), + ); + assert( + (client.descriptors.page.listAdSenseLinks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listDisplayVideo360AdvertiserLinks with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listDisplayVideo360AdvertiserLinks.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listDisplayVideo360AdvertiserLinksAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLink[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listDisplayVideo360AdvertiserLinks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listDisplayVideo360AdvertiserLinks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listAdSenseLinksStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAdSenseLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListAdSenseLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listAdSenseLinks.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listAdSenseLinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.AdSenseLink[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.AdSenseLink) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listAdSenseLinks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listAdSenseLinks, request), + ); + assert( + (client.descriptors.page.listAdSenseLinks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('listDisplayVideo360AdvertiserLinkProposals', () => { - it('invokes listDisplayVideo360AdvertiserLinkProposals without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal()), - ]; - client.innerApiCalls.listDisplayVideo360AdvertiserLinkProposals = stubSimpleCall(expectedResponse); - const [response] = await client.listDisplayVideo360AdvertiserLinkProposals(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDisplayVideo360AdvertiserLinkProposals as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDisplayVideo360AdvertiserLinkProposals as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listDisplayVideo360AdvertiserLinkProposals without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal()), - ]; - client.innerApiCalls.listDisplayVideo360AdvertiserLinkProposals = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listDisplayVideo360AdvertiserLinkProposals( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDisplayVideo360AdvertiserLinkProposals as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDisplayVideo360AdvertiserLinkProposals as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listDisplayVideo360AdvertiserLinkProposals with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listDisplayVideo360AdvertiserLinkProposals = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listDisplayVideo360AdvertiserLinkProposals(request), expectedError); - const actualRequest = (client.innerApiCalls.listDisplayVideo360AdvertiserLinkProposals as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDisplayVideo360AdvertiserLinkProposals as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listDisplayVideo360AdvertiserLinkProposalsStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal()), - ]; - client.descriptors.page.listDisplayVideo360AdvertiserLinkProposals.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listDisplayVideo360AdvertiserLinkProposalsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal) => { - 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.listDisplayVideo360AdvertiserLinkProposals.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listDisplayVideo360AdvertiserLinkProposals, request)); - assert( - (client.descriptors.page.listDisplayVideo360AdvertiserLinkProposals.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listAdSenseLinks without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAdSenseLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListAdSenseLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AdSenseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AdSenseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.AdSenseLink(), + ), + ]; + client.descriptors.page.listAdSenseLinks.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.IAdSenseLink[] = + []; + const iterable = client.listAdSenseLinksAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listAdSenseLinks.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listAdSenseLinks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listDisplayVideo360AdvertiserLinkProposalsStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listDisplayVideo360AdvertiserLinkProposals.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listDisplayVideo360AdvertiserLinkProposalsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listDisplayVideo360AdvertiserLinkProposals.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listDisplayVideo360AdvertiserLinkProposals, request)); - assert( - (client.descriptors.page.listDisplayVideo360AdvertiserLinkProposals.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listAdSenseLinks with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListAdSenseLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListAdSenseLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listAdSenseLinks.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listAdSenseLinksAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.IAdSenseLink[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listAdSenseLinks.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listAdSenseLinks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listEventCreateRules', () => { + it('invokes listEventCreateRules without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListEventCreateRulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListEventCreateRulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventCreateRule(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventCreateRule(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventCreateRule(), + ), + ]; + client.innerApiCalls.listEventCreateRules = + stubSimpleCall(expectedResponse); + const [response] = await client.listEventCreateRules(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listEventCreateRules as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listEventCreateRules as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listDisplayVideo360AdvertiserLinkProposals without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DisplayVideo360AdvertiserLinkProposal()), - ]; - client.descriptors.page.listDisplayVideo360AdvertiserLinkProposals.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal[] = []; - const iterable = client.listDisplayVideo360AdvertiserLinkProposalsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listEventCreateRules without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListEventCreateRulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListEventCreateRulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventCreateRule(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventCreateRule(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventCreateRule(), + ), + ]; + client.innerApiCalls.listEventCreateRules = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listEventCreateRules( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.IEventCreateRule[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listDisplayVideo360AdvertiserLinkProposals.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listDisplayVideo360AdvertiserLinkProposals.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.listEventCreateRules as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listEventCreateRules as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listDisplayVideo360AdvertiserLinkProposals with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListDisplayVideo360AdvertiserLinkProposalsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listDisplayVideo360AdvertiserLinkProposals.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listDisplayVideo360AdvertiserLinkProposalsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.IDisplayVideo360AdvertiserLinkProposal[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listDisplayVideo360AdvertiserLinkProposals.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listDisplayVideo360AdvertiserLinkProposals.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listEventCreateRules with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListEventCreateRulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListEventCreateRulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listEventCreateRules = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listEventCreateRules(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listEventCreateRules as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listEventCreateRules as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listCustomDimensions', () => { - it('invokes listCustomDimensions without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListCustomDimensionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListCustomDimensionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomDimension()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomDimension()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomDimension()), - ]; - client.innerApiCalls.listCustomDimensions = stubSimpleCall(expectedResponse); - const [response] = await client.listCustomDimensions(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCustomDimensions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCustomDimensions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCustomDimensions without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListCustomDimensionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListCustomDimensionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomDimension()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomDimension()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomDimension()), - ]; - client.innerApiCalls.listCustomDimensions = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listCustomDimensions( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ICustomDimension[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCustomDimensions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCustomDimensions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCustomDimensions with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListCustomDimensionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListCustomDimensionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listCustomDimensions = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listCustomDimensions(request), expectedError); - const actualRequest = (client.innerApiCalls.listCustomDimensions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCustomDimensions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCustomDimensionsStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListCustomDimensionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListCustomDimensionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomDimension()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomDimension()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomDimension()), - ]; - client.descriptors.page.listCustomDimensions.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listCustomDimensionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.CustomDimension[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.CustomDimension) => { - 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.listCustomDimensions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCustomDimensions, request)); - assert( - (client.descriptors.page.listCustomDimensions.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listEventCreateRulesStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListEventCreateRulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListEventCreateRulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventCreateRule(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventCreateRule(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventCreateRule(), + ), + ]; + client.descriptors.page.listEventCreateRules.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listEventCreateRulesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.EventCreateRule[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.EventCreateRule) => { + 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.listEventCreateRules.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listEventCreateRules, request), + ); + assert( + (client.descriptors.page.listEventCreateRules.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listCustomDimensionsStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListCustomDimensionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListCustomDimensionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCustomDimensions.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listCustomDimensionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.CustomDimension[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.CustomDimension) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listCustomDimensions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCustomDimensions, request)); - assert( - (client.descriptors.page.listCustomDimensions.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listEventCreateRulesStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListEventCreateRulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListEventCreateRulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listEventCreateRules.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listEventCreateRulesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.EventCreateRule[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.EventCreateRule) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listEventCreateRules.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listEventCreateRules, request), + ); + assert( + (client.descriptors.page.listEventCreateRules.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listCustomDimensions without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListCustomDimensionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListCustomDimensionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomDimension()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomDimension()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomDimension()), - ]; - client.descriptors.page.listCustomDimensions.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.ICustomDimension[] = []; - const iterable = client.listCustomDimensionsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listCustomDimensions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCustomDimensions.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listEventCreateRules without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListEventCreateRulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListEventCreateRulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventCreateRule(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventCreateRule(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventCreateRule(), + ), + ]; + client.descriptors.page.listEventCreateRules.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.IEventCreateRule[] = + []; + const iterable = client.listEventCreateRulesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listEventCreateRules.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listEventCreateRules.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listCustomDimensions with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListCustomDimensionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListCustomDimensionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCustomDimensions.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listCustomDimensionsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.ICustomDimension[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listCustomDimensions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCustomDimensions.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listEventCreateRules with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListEventCreateRulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListEventCreateRulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listEventCreateRules.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listEventCreateRulesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.IEventCreateRule[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listEventCreateRules.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listEventCreateRules.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listEventEditRules', () => { + it('invokes listEventEditRules without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListEventEditRulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListEventEditRulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventEditRule(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventEditRule(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventEditRule(), + ), + ]; + client.innerApiCalls.listEventEditRules = + stubSimpleCall(expectedResponse); + const [response] = await client.listEventEditRules(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listEventEditRules as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listEventEditRules as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listCustomMetrics', () => { - it('invokes listCustomMetrics without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListCustomMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListCustomMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomMetric()), - ]; - client.innerApiCalls.listCustomMetrics = stubSimpleCall(expectedResponse); - const [response] = await client.listCustomMetrics(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCustomMetrics as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCustomMetrics as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCustomMetrics without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListCustomMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListCustomMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomMetric()), - ]; - client.innerApiCalls.listCustomMetrics = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listCustomMetrics( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ICustomMetric[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCustomMetrics as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCustomMetrics as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCustomMetrics with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListCustomMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListCustomMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listCustomMetrics = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listCustomMetrics(request), expectedError); - const actualRequest = (client.innerApiCalls.listCustomMetrics as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCustomMetrics as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCustomMetricsStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListCustomMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListCustomMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomMetric()), - ]; - client.descriptors.page.listCustomMetrics.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listCustomMetricsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.CustomMetric[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.CustomMetric) => { - 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.listCustomMetrics.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCustomMetrics, request)); - assert( - (client.descriptors.page.listCustomMetrics.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listEventEditRules without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListEventEditRulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListEventEditRulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventEditRule(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventEditRule(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventEditRule(), + ), + ]; + client.innerApiCalls.listEventEditRules = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listEventEditRules( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.IEventEditRule[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listEventEditRules as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listEventEditRules as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listCustomMetricsStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListCustomMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListCustomMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCustomMetrics.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listCustomMetricsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.CustomMetric[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.CustomMetric) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listCustomMetrics.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCustomMetrics, request)); - assert( - (client.descriptors.page.listCustomMetrics.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listEventEditRules with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListEventEditRulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListEventEditRulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listEventEditRules = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listEventEditRules(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listEventEditRules as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listEventEditRules as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listCustomMetrics without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListCustomMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListCustomMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CustomMetric()), - ]; - client.descriptors.page.listCustomMetrics.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.ICustomMetric[] = []; - const iterable = client.listCustomMetricsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listCustomMetrics.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCustomMetrics.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listEventEditRulesStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListEventEditRulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListEventEditRulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventEditRule(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventEditRule(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventEditRule(), + ), + ]; + client.descriptors.page.listEventEditRules.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listEventEditRulesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.EventEditRule[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.EventEditRule) => { + 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.listEventEditRules.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listEventEditRules, request), + ); + assert( + (client.descriptors.page.listEventEditRules.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listCustomMetrics with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListCustomMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListCustomMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCustomMetrics.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listCustomMetricsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.ICustomMetric[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listCustomMetrics.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCustomMetrics.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listEventEditRulesStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListEventEditRulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListEventEditRulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listEventEditRules.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listEventEditRulesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.EventEditRule[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1alpha.EventEditRule) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listEventEditRules.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listEventEditRules, request), + ); + assert( + (client.descriptors.page.listEventEditRules.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('listDataStreams', () => { - it('invokes listDataStreams without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListDataStreamsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListDataStreamsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DataStream()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DataStream()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DataStream()), - ]; - client.innerApiCalls.listDataStreams = stubSimpleCall(expectedResponse); - const [response] = await client.listDataStreams(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDataStreams as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDataStreams as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listDataStreams without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListDataStreamsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListDataStreamsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DataStream()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DataStream()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DataStream()), - ]; - client.innerApiCalls.listDataStreams = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listDataStreams( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IDataStream[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDataStreams as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDataStreams as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listDataStreams with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListDataStreamsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListDataStreamsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listDataStreams = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listDataStreams(request), expectedError); - const actualRequest = (client.innerApiCalls.listDataStreams as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDataStreams as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listDataStreamsStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListDataStreamsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListDataStreamsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DataStream()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DataStream()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DataStream()), - ]; - client.descriptors.page.listDataStreams.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listDataStreamsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.DataStream[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.DataStream) => { - 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.listDataStreams.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listDataStreams, request)); - assert( - (client.descriptors.page.listDataStreams.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listEventEditRules without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListEventEditRulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListEventEditRulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventEditRule(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventEditRule(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.EventEditRule(), + ), + ]; + client.descriptors.page.listEventEditRules.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.IEventEditRule[] = + []; + const iterable = client.listEventEditRulesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listEventEditRules.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listEventEditRules.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listDataStreamsStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListDataStreamsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListDataStreamsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listDataStreams.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listDataStreamsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.DataStream[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.DataStream) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listDataStreams.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listDataStreams, request)); - assert( - (client.descriptors.page.listDataStreams.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listEventEditRules with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListEventEditRulesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListEventEditRulesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listEventEditRules.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listEventEditRulesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.IEventEditRule[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listEventEditRules.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listEventEditRules.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listCalculatedMetrics', () => { + it('invokes listCalculatedMetrics without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CalculatedMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CalculatedMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CalculatedMetric(), + ), + ]; + client.innerApiCalls.listCalculatedMetrics = + stubSimpleCall(expectedResponse); + const [response] = await client.listCalculatedMetrics(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCalculatedMetrics as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCalculatedMetrics as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listDataStreams without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListDataStreamsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListDataStreamsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DataStream()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DataStream()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.DataStream()), - ]; - client.descriptors.page.listDataStreams.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.IDataStream[] = []; - const iterable = client.listDataStreamsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listCalculatedMetrics without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CalculatedMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CalculatedMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CalculatedMetric(), + ), + ]; + client.innerApiCalls.listCalculatedMetrics = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listCalculatedMetrics( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.ICalculatedMetric[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listDataStreams.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listDataStreams.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.listCalculatedMetrics as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCalculatedMetrics as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listDataStreams with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListDataStreamsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListDataStreamsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listDataStreams.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listDataStreamsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.IDataStream[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listDataStreams.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listDataStreams.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listCalculatedMetrics with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listCalculatedMetrics = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listCalculatedMetrics(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listCalculatedMetrics as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCalculatedMetrics as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listAudiences', () => { - it('invokes listAudiences without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAudiencesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListAudiencesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Audience()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Audience()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Audience()), - ]; - client.innerApiCalls.listAudiences = stubSimpleCall(expectedResponse); - const [response] = await client.listAudiences(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listAudiences as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listAudiences as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listAudiences without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAudiencesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListAudiencesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Audience()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Audience()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Audience()), - ]; - client.innerApiCalls.listAudiences = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listAudiences( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IAudience[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listAudiences as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listAudiences as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listAudiences with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAudiencesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListAudiencesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listAudiences = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listAudiences(request), expectedError); - const actualRequest = (client.innerApiCalls.listAudiences as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listAudiences as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listAudiencesStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAudiencesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListAudiencesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Audience()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Audience()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Audience()), - ]; - client.descriptors.page.listAudiences.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listAudiencesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.Audience[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.Audience) => { - 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.listAudiences.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listAudiences, request)); - assert( - (client.descriptors.page.listAudiences.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listCalculatedMetricsStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CalculatedMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CalculatedMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CalculatedMetric(), + ), + ]; + client.descriptors.page.listCalculatedMetrics.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listCalculatedMetricsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.CalculatedMetric[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1alpha.CalculatedMetric, + ) => { + 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.listCalculatedMetrics + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listCalculatedMetrics, request), + ); + assert( + ( + client.descriptors.page.listCalculatedMetrics + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listAudiencesStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAudiencesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListAudiencesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listAudiences.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listAudiencesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.Audience[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.Audience) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listAudiences.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listAudiences, request)); - assert( - (client.descriptors.page.listAudiences.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listCalculatedMetricsStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCalculatedMetrics.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listCalculatedMetricsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.CalculatedMetric[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1alpha.CalculatedMetric, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listCalculatedMetrics + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listCalculatedMetrics, request), + ); + assert( + ( + client.descriptors.page.listCalculatedMetrics + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('uses async iteration with listAudiences without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAudiencesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListAudiencesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Audience()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Audience()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.Audience()), - ]; - client.descriptors.page.listAudiences.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.IAudience[] = []; - const iterable = client.listAudiencesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('uses async iteration with listCalculatedMetrics without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CalculatedMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CalculatedMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.CalculatedMetric(), + ), + ]; + client.descriptors.page.listCalculatedMetrics.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.ICalculatedMetric[] = + []; + const iterable = client.listCalculatedMetricsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listCalculatedMetrics + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listCalculatedMetrics + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listCalculatedMetrics with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCalculatedMetrics.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listCalculatedMetricsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.ICalculatedMetric[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listCalculatedMetrics + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listCalculatedMetrics + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listRollupPropertySourceLinks', () => { + it('invokes listRollupPropertySourceLinks without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink(), + ), + ]; + client.innerApiCalls.listRollupPropertySourceLinks = + stubSimpleCall(expectedResponse); + const [response] = await client.listRollupPropertySourceLinks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listRollupPropertySourceLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listRollupPropertySourceLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listRollupPropertySourceLinks without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink(), + ), + ]; + client.innerApiCalls.listRollupPropertySourceLinks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listRollupPropertySourceLinks( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listAudiences.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listAudiences.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.listRollupPropertySourceLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listRollupPropertySourceLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listAudiences with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAudiencesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListAudiencesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listAudiences.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listAudiencesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.IAudience[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listAudiences.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listAudiences.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listRollupPropertySourceLinks with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listRollupPropertySourceLinks = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listRollupPropertySourceLinks(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listRollupPropertySourceLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listRollupPropertySourceLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listSearchAds360Links', () => { - it('invokes listSearchAds360Links without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SearchAds360Link()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SearchAds360Link()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SearchAds360Link()), - ]; - client.innerApiCalls.listSearchAds360Links = stubSimpleCall(expectedResponse); - const [response] = await client.listSearchAds360Links(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listSearchAds360Links as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listSearchAds360Links as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listSearchAds360Links without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SearchAds360Link()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SearchAds360Link()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SearchAds360Link()), - ]; - client.innerApiCalls.listSearchAds360Links = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listSearchAds360Links( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ISearchAds360Link[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listSearchAds360Links as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listSearchAds360Links as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listSearchAds360Links with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listSearchAds360Links = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listSearchAds360Links(request), expectedError); - const actualRequest = (client.innerApiCalls.listSearchAds360Links as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listSearchAds360Links as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listSearchAds360LinksStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SearchAds360Link()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SearchAds360Link()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SearchAds360Link()), - ]; - client.descriptors.page.listSearchAds360Links.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listSearchAds360LinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.SearchAds360Link[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.SearchAds360Link) => { - 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.listSearchAds360Links.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listSearchAds360Links, request)); - assert( - (client.descriptors.page.listSearchAds360Links.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listRollupPropertySourceLinksStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink(), + ), + ]; + client.descriptors.page.listRollupPropertySourceLinks.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listRollupPropertySourceLinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.RollupPropertySourceLink[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1alpha.RollupPropertySourceLink, + ) => { + 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.listRollupPropertySourceLinks + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listRollupPropertySourceLinks, + request, + ), + ); + assert( + ( + client.descriptors.page.listRollupPropertySourceLinks + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('invokes listRollupPropertySourceLinksStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listRollupPropertySourceLinks.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listRollupPropertySourceLinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.RollupPropertySourceLink[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1alpha.RollupPropertySourceLink, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listRollupPropertySourceLinks + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listRollupPropertySourceLinks, + request, + ), + ); + assert( + ( + client.descriptors.page.listRollupPropertySourceLinks + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listSearchAds360LinksStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listSearchAds360Links.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listSearchAds360LinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.SearchAds360Link[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.SearchAds360Link) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listSearchAds360Links.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listSearchAds360Links, request)); - assert( - (client.descriptors.page.listSearchAds360Links.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listRollupPropertySourceLinks without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink(), + ), + ]; + client.descriptors.page.listRollupPropertySourceLinks.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink[] = + []; + const iterable = client.listRollupPropertySourceLinksAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listRollupPropertySourceLinks + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listRollupPropertySourceLinks + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('uses async iteration with listSearchAds360Links without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SearchAds360Link()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SearchAds360Link()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SearchAds360Link()), - ]; - client.descriptors.page.listSearchAds360Links.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.ISearchAds360Link[] = []; - const iterable = client.listSearchAds360LinksAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('uses async iteration with listRollupPropertySourceLinks with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listRollupPropertySourceLinks.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listRollupPropertySourceLinksAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listRollupPropertySourceLinks + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listRollupPropertySourceLinks + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listSubpropertyEventFilters', () => { + it('invokes listSubpropertyEventFilters without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter(), + ), + ]; + client.innerApiCalls.listSubpropertyEventFilters = + stubSimpleCall(expectedResponse); + const [response] = await client.listSubpropertyEventFilters(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listSubpropertyEventFilters as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listSubpropertyEventFilters as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listSubpropertyEventFilters without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter(), + ), + ]; + client.innerApiCalls.listSubpropertyEventFilters = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listSubpropertyEventFilters( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listSearchAds360Links.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listSearchAds360Links.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.listSubpropertyEventFilters as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listSubpropertyEventFilters as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listSearchAds360Links with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSearchAds360LinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listSearchAds360Links.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listSearchAds360LinksAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.ISearchAds360Link[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listSearchAds360Links.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listSearchAds360Links.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listSubpropertyEventFilters with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listSubpropertyEventFilters = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listSubpropertyEventFilters(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listSubpropertyEventFilters as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listSubpropertyEventFilters as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listAccessBindings', () => { - it('invokes listAccessBindings without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAccessBindingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListAccessBindingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccessBinding()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccessBinding()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccessBinding()), - ]; - client.innerApiCalls.listAccessBindings = stubSimpleCall(expectedResponse); - const [response] = await client.listAccessBindings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listAccessBindings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listAccessBindings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listAccessBindings without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAccessBindingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListAccessBindingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccessBinding()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccessBinding()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccessBinding()), - ]; - client.innerApiCalls.listAccessBindings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listAccessBindings( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IAccessBinding[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listAccessBindings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listAccessBindings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listAccessBindings with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAccessBindingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListAccessBindingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listAccessBindings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listAccessBindings(request), expectedError); - const actualRequest = (client.innerApiCalls.listAccessBindings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listAccessBindings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listAccessBindingsStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAccessBindingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListAccessBindingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccessBinding()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccessBinding()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccessBinding()), - ]; - client.descriptors.page.listAccessBindings.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listAccessBindingsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.AccessBinding[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.AccessBinding) => { - 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.listAccessBindings.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listAccessBindings, request)); - assert( - (client.descriptors.page.listAccessBindings.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listSubpropertyEventFiltersStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter(), + ), + ]; + client.descriptors.page.listSubpropertyEventFilters.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listSubpropertyEventFiltersStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.SubpropertyEventFilter[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1alpha.SubpropertyEventFilter, + ) => { + 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.listSubpropertyEventFilters + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listSubpropertyEventFilters, + request, + ), + ); + assert( + ( + client.descriptors.page.listSubpropertyEventFilters + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listAccessBindingsStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAccessBindingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListAccessBindingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listAccessBindings.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listAccessBindingsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.AccessBinding[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.AccessBinding) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listAccessBindings.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listAccessBindings, request)); - assert( - (client.descriptors.page.listAccessBindings.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listSubpropertyEventFiltersStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listSubpropertyEventFilters.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listSubpropertyEventFiltersStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.SubpropertyEventFilter[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1alpha.SubpropertyEventFilter, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listSubpropertyEventFilters + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listSubpropertyEventFilters, + request, + ), + ); + assert( + ( + client.descriptors.page.listSubpropertyEventFilters + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('uses async iteration with listAccessBindings without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAccessBindingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListAccessBindingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccessBinding()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccessBinding()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AccessBinding()), - ]; - client.descriptors.page.listAccessBindings.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.IAccessBinding[] = []; - const iterable = client.listAccessBindingsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('uses async iteration with listSubpropertyEventFilters without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter(), + ), + ]; + client.descriptors.page.listSubpropertyEventFilters.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter[] = + []; + const iterable = client.listSubpropertyEventFiltersAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listSubpropertyEventFilters + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listSubpropertyEventFilters + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listSubpropertyEventFilters with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listSubpropertyEventFilters.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listSubpropertyEventFiltersAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listSubpropertyEventFilters + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listSubpropertyEventFilters + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listReportingDataAnnotations', () => { + it('invokes listReportingDataAnnotations without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation(), + ), + ]; + client.innerApiCalls.listReportingDataAnnotations = + stubSimpleCall(expectedResponse); + const [response] = await client.listReportingDataAnnotations(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listReportingDataAnnotations as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listReportingDataAnnotations as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listReportingDataAnnotations without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation(), + ), + ]; + client.innerApiCalls.listReportingDataAnnotations = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listReportingDataAnnotations( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.IReportingDataAnnotation[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listAccessBindings.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listAccessBindings.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.listReportingDataAnnotations as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listReportingDataAnnotations as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listAccessBindings with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAccessBindingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListAccessBindingsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listAccessBindings.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listAccessBindingsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.IAccessBinding[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listAccessBindings.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listAccessBindings.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listReportingDataAnnotations with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listReportingDataAnnotations = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listReportingDataAnnotations(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listReportingDataAnnotations as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listReportingDataAnnotations as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listExpandedDataSets', () => { - it('invokes listExpandedDataSets without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ExpandedDataSet()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ExpandedDataSet()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ExpandedDataSet()), - ]; - client.innerApiCalls.listExpandedDataSets = stubSimpleCall(expectedResponse); - const [response] = await client.listExpandedDataSets(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listExpandedDataSets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listExpandedDataSets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listExpandedDataSets without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ExpandedDataSet()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ExpandedDataSet()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ExpandedDataSet()), - ]; - client.innerApiCalls.listExpandedDataSets = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listExpandedDataSets( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IExpandedDataSet[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listExpandedDataSets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listExpandedDataSets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listExpandedDataSets with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listExpandedDataSets = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listExpandedDataSets(request), expectedError); - const actualRequest = (client.innerApiCalls.listExpandedDataSets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listExpandedDataSets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listExpandedDataSetsStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ExpandedDataSet()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ExpandedDataSet()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ExpandedDataSet()), - ]; - client.descriptors.page.listExpandedDataSets.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listExpandedDataSetsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.ExpandedDataSet[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.ExpandedDataSet) => { - 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.listExpandedDataSets.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listExpandedDataSets, request)); - assert( - (client.descriptors.page.listExpandedDataSets.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listReportingDataAnnotationsStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation(), + ), + ]; + client.descriptors.page.listReportingDataAnnotations.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listReportingDataAnnotationsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.ReportingDataAnnotation[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1alpha.ReportingDataAnnotation, + ) => { + 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.listReportingDataAnnotations + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listReportingDataAnnotations, + request, + ), + ); + assert( + ( + client.descriptors.page.listReportingDataAnnotations + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listExpandedDataSetsStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listExpandedDataSets.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listExpandedDataSetsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.ExpandedDataSet[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.ExpandedDataSet) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listExpandedDataSets.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listExpandedDataSets, request)); - assert( - (client.descriptors.page.listExpandedDataSets.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listReportingDataAnnotationsStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listReportingDataAnnotations.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listReportingDataAnnotationsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.ReportingDataAnnotation[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1alpha.ReportingDataAnnotation, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listReportingDataAnnotations + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listReportingDataAnnotations, + request, + ), + ); + assert( + ( + client.descriptors.page.listReportingDataAnnotations + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('uses async iteration with listExpandedDataSets without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ExpandedDataSet()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ExpandedDataSet()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ExpandedDataSet()), - ]; - client.descriptors.page.listExpandedDataSets.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.IExpandedDataSet[] = []; - const iterable = client.listExpandedDataSetsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('uses async iteration with listReportingDataAnnotations without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation(), + ), + ]; + client.descriptors.page.listReportingDataAnnotations.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.IReportingDataAnnotation[] = + []; + const iterable = client.listReportingDataAnnotationsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listReportingDataAnnotations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listReportingDataAnnotations + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listReportingDataAnnotations with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listReportingDataAnnotations.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listReportingDataAnnotationsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.IReportingDataAnnotation[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listReportingDataAnnotations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listReportingDataAnnotations + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listSubpropertySyncConfigs', () => { + it('invokes listSubpropertySyncConfigs without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig(), + ), + ]; + client.innerApiCalls.listSubpropertySyncConfigs = + stubSimpleCall(expectedResponse); + const [response] = await client.listSubpropertySyncConfigs(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listSubpropertySyncConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listSubpropertySyncConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listSubpropertySyncConfigs without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig(), + ), + ]; + client.innerApiCalls.listSubpropertySyncConfigs = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listSubpropertySyncConfigs( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listExpandedDataSets.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listExpandedDataSets.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.listSubpropertySyncConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listSubpropertySyncConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listExpandedDataSets with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListExpandedDataSetsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listExpandedDataSets.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listExpandedDataSetsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.IExpandedDataSet[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listExpandedDataSets.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listExpandedDataSets.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listSubpropertySyncConfigs with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listSubpropertySyncConfigs = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listSubpropertySyncConfigs(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listSubpropertySyncConfigs as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listSubpropertySyncConfigs as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listChannelGroups', () => { - it('invokes listChannelGroups without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListChannelGroupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListChannelGroupsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChannelGroup()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChannelGroup()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChannelGroup()), - ]; - client.innerApiCalls.listChannelGroups = stubSimpleCall(expectedResponse); - const [response] = await client.listChannelGroups(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listChannelGroups as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listChannelGroups as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listChannelGroups without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListChannelGroupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListChannelGroupsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChannelGroup()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChannelGroup()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChannelGroup()), - ]; - client.innerApiCalls.listChannelGroups = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listChannelGroups( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IChannelGroup[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listChannelGroups as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listChannelGroups as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listChannelGroups with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListChannelGroupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListChannelGroupsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listChannelGroups = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listChannelGroups(request), expectedError); - const actualRequest = (client.innerApiCalls.listChannelGroups as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listChannelGroups as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listChannelGroupsStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListChannelGroupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListChannelGroupsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChannelGroup()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChannelGroup()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChannelGroup()), - ]; - client.descriptors.page.listChannelGroups.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listChannelGroupsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.ChannelGroup[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.ChannelGroup) => { - 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.listChannelGroups.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listChannelGroups, request)); - assert( - (client.descriptors.page.listChannelGroups.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listSubpropertySyncConfigsStream without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig(), + ), + ]; + client.descriptors.page.listSubpropertySyncConfigs.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listSubpropertySyncConfigsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.SubpropertySyncConfig[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1alpha.SubpropertySyncConfig, + ) => { + 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.listSubpropertySyncConfigs + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listSubpropertySyncConfigs, request), + ); + assert( + ( + client.descriptors.page.listSubpropertySyncConfigs + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listChannelGroupsStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListChannelGroupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListChannelGroupsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listChannelGroups.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listChannelGroupsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.ChannelGroup[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.ChannelGroup) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listChannelGroups.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listChannelGroups, request)); - assert( - (client.descriptors.page.listChannelGroups.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listSubpropertySyncConfigsStream with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listSubpropertySyncConfigs.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listSubpropertySyncConfigsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1alpha.SubpropertySyncConfig[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1alpha.SubpropertySyncConfig, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listSubpropertySyncConfigs + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listSubpropertySyncConfigs, request), + ); + assert( + ( + client.descriptors.page.listSubpropertySyncConfigs + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('uses async iteration with listChannelGroups without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListChannelGroupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListChannelGroupsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChannelGroup()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChannelGroup()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ChannelGroup()), - ]; - client.descriptors.page.listChannelGroups.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.IChannelGroup[] = []; - const iterable = client.listChannelGroupsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listChannelGroups.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listChannelGroups.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listSubpropertySyncConfigs without error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig(), + ), + ]; + client.descriptors.page.listSubpropertySyncConfigs.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig[] = + []; + const iterable = client.listSubpropertySyncConfigsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listSubpropertySyncConfigs + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listSubpropertySyncConfigs + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('uses async iteration with listChannelGroups with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListChannelGroupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListChannelGroupsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listChannelGroups.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listChannelGroupsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.IChannelGroup[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listChannelGroups.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listChannelGroups.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listSubpropertySyncConfigs with error', async () => { + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listSubpropertySyncConfigs.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listSubpropertySyncConfigsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listSubpropertySyncConfigs + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listSubpropertySyncConfigs + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('Path templates', () => { + describe('account', async () => { + const fakePath = '/rendered/path/account'; + const expectedParameters = { + account: 'accountValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.accountPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.accountPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('accountPath', () => { + const result = client.accountPath('accountValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.accountPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountFromAccountName', () => { + const result = client.matchAccountFromAccountName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + (client.pathTemplates.accountPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); - describe('listBigQueryLinks', () => { - it('invokes listBigQueryLinks without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListBigQueryLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListBigQueryLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.BigQueryLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.BigQueryLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.BigQueryLink()), - ]; - client.innerApiCalls.listBigQueryLinks = stubSimpleCall(expectedResponse); - const [response] = await client.listBigQueryLinks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listBigQueryLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBigQueryLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listBigQueryLinks without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListBigQueryLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListBigQueryLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.BigQueryLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.BigQueryLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.BigQueryLink()), - ]; - client.innerApiCalls.listBigQueryLinks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listBigQueryLinks( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IBigQueryLink[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listBigQueryLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBigQueryLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listBigQueryLinks with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListBigQueryLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListBigQueryLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listBigQueryLinks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listBigQueryLinks(request), expectedError); - const actualRequest = (client.innerApiCalls.listBigQueryLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBigQueryLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listBigQueryLinksStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListBigQueryLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListBigQueryLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.BigQueryLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.BigQueryLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.BigQueryLink()), - ]; - client.descriptors.page.listBigQueryLinks.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listBigQueryLinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.BigQueryLink[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.BigQueryLink) => { - 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.listBigQueryLinks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listBigQueryLinks, request)); - assert( - (client.descriptors.page.listBigQueryLinks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('accountAccessBinding', async () => { + const fakePath = '/rendered/path/accountAccessBinding'; + const expectedParameters = { + account: 'accountValue', + access_binding: 'accessBindingValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.accountAccessBindingPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.accountAccessBindingPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('accountAccessBindingPath', () => { + const result = client.accountAccessBindingPath( + 'accountValue', + 'accessBindingValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.accountAccessBindingPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountFromAccountAccessBindingName', () => { + const result = + client.matchAccountFromAccountAccessBindingName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + ( + client.pathTemplates.accountAccessBindingPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccessBindingFromAccountAccessBindingName', () => { + const result = + client.matchAccessBindingFromAccountAccessBindingName(fakePath); + assert.strictEqual(result, 'accessBindingValue'); + assert( + ( + client.pathTemplates.accountAccessBindingPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('invokes listBigQueryLinksStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListBigQueryLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListBigQueryLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listBigQueryLinks.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listBigQueryLinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.BigQueryLink[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.BigQueryLink) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listBigQueryLinks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listBigQueryLinks, request)); - assert( - (client.descriptors.page.listBigQueryLinks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('accountSummary', async () => { + const fakePath = '/rendered/path/accountSummary'; + const expectedParameters = { + account_summary: 'accountSummaryValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.accountSummaryPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.accountSummaryPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('accountSummaryPath', () => { + const result = client.accountSummaryPath('accountSummaryValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.accountSummaryPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountSummaryFromAccountSummaryName', () => { + const result = + client.matchAccountSummaryFromAccountSummaryName(fakePath); + assert.strictEqual(result, 'accountSummaryValue'); + assert( + (client.pathTemplates.accountSummaryPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('uses async iteration with listBigQueryLinks without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListBigQueryLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListBigQueryLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.BigQueryLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.BigQueryLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.BigQueryLink()), - ]; - client.descriptors.page.listBigQueryLinks.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.IBigQueryLink[] = []; - const iterable = client.listBigQueryLinksAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listBigQueryLinks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listBigQueryLinks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('adSenseLink', async () => { + const fakePath = '/rendered/path/adSenseLink'; + const expectedParameters = { + property: 'propertyValue', + adsense_link: 'adsenseLinkValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.adSenseLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.adSenseLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('adSenseLinkPath', () => { + const result = client.adSenseLinkPath( + 'propertyValue', + 'adsenseLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.adSenseLinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromAdSenseLinkName', () => { + const result = client.matchPropertyFromAdSenseLinkName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.adSenseLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAdsenseLinkFromAdSenseLinkName', () => { + const result = client.matchAdsenseLinkFromAdSenseLinkName(fakePath); + assert.strictEqual(result, 'adsenseLinkValue'); + assert( + (client.pathTemplates.adSenseLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('uses async iteration with listBigQueryLinks with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListBigQueryLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListBigQueryLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listBigQueryLinks.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listBigQueryLinksAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.IBigQueryLink[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listBigQueryLinks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listBigQueryLinks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('attributionSettings', async () => { + const fakePath = '/rendered/path/attributionSettings'; + const expectedParameters = { + property: 'propertyValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.attributionSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.attributionSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('attributionSettingsPath', () => { + const result = client.attributionSettingsPath('propertyValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.attributionSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromAttributionSettingsName', () => { + const result = + client.matchPropertyFromAttributionSettingsName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + ( + client.pathTemplates.attributionSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); - describe('listAdSenseLinks', () => { - it('invokes listAdSenseLinks without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAdSenseLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListAdSenseLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AdSenseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AdSenseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AdSenseLink()), - ]; - client.innerApiCalls.listAdSenseLinks = stubSimpleCall(expectedResponse); - const [response] = await client.listAdSenseLinks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listAdSenseLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listAdSenseLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listAdSenseLinks without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAdSenseLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListAdSenseLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AdSenseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AdSenseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AdSenseLink()), - ]; - client.innerApiCalls.listAdSenseLinks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listAdSenseLinks( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IAdSenseLink[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listAdSenseLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listAdSenseLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listAdSenseLinks with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAdSenseLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListAdSenseLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listAdSenseLinks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listAdSenseLinks(request), expectedError); - const actualRequest = (client.innerApiCalls.listAdSenseLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listAdSenseLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listAdSenseLinksStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAdSenseLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListAdSenseLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AdSenseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AdSenseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AdSenseLink()), - ]; - client.descriptors.page.listAdSenseLinks.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listAdSenseLinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.AdSenseLink[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.AdSenseLink) => { - 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.listAdSenseLinks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listAdSenseLinks, request)); - assert( - (client.descriptors.page.listAdSenseLinks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('audience', async () => { + const fakePath = '/rendered/path/audience'; + const expectedParameters = { + property: 'propertyValue', + audience: 'audienceValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.audiencePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.audiencePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('audiencePath', () => { + const result = client.audiencePath('propertyValue', 'audienceValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.audiencePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromAudienceName', () => { + const result = client.matchPropertyFromAudienceName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.audiencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAudienceFromAudienceName', () => { + const result = client.matchAudienceFromAudienceName(fakePath); + assert.strictEqual(result, 'audienceValue'); + assert( + (client.pathTemplates.audiencePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('invokes listAdSenseLinksStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAdSenseLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListAdSenseLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listAdSenseLinks.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listAdSenseLinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.AdSenseLink[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.AdSenseLink) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listAdSenseLinks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listAdSenseLinks, request)); - assert( - (client.descriptors.page.listAdSenseLinks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('bigQueryLink', async () => { + const fakePath = '/rendered/path/bigQueryLink'; + const expectedParameters = { + property: 'propertyValue', + bigquery_link: 'bigqueryLinkValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.bigQueryLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.bigQueryLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('bigQueryLinkPath', () => { + const result = client.bigQueryLinkPath( + 'propertyValue', + 'bigqueryLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.bigQueryLinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromBigQueryLinkName', () => { + const result = client.matchPropertyFromBigQueryLinkName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.bigQueryLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchBigqueryLinkFromBigQueryLinkName', () => { + const result = client.matchBigqueryLinkFromBigQueryLinkName(fakePath); + assert.strictEqual(result, 'bigqueryLinkValue'); + assert( + (client.pathTemplates.bigQueryLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('uses async iteration with listAdSenseLinks without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAdSenseLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListAdSenseLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AdSenseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AdSenseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.AdSenseLink()), - ]; - client.descriptors.page.listAdSenseLinks.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.IAdSenseLink[] = []; - const iterable = client.listAdSenseLinksAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listAdSenseLinks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listAdSenseLinks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('calculatedMetric', async () => { + const fakePath = '/rendered/path/calculatedMetric'; + const expectedParameters = { + property: 'propertyValue', + calculated_metric: 'calculatedMetricValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.calculatedMetricPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.calculatedMetricPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('calculatedMetricPath', () => { + const result = client.calculatedMetricPath( + 'propertyValue', + 'calculatedMetricValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.calculatedMetricPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromCalculatedMetricName', () => { + const result = client.matchPropertyFromCalculatedMetricName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.calculatedMetricPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCalculatedMetricFromCalculatedMetricName', () => { + const result = + client.matchCalculatedMetricFromCalculatedMetricName(fakePath); + assert.strictEqual(result, 'calculatedMetricValue'); + assert( + (client.pathTemplates.calculatedMetricPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('uses async iteration with listAdSenseLinks with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListAdSenseLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListAdSenseLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listAdSenseLinks.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listAdSenseLinksAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.IAdSenseLink[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listAdSenseLinks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listAdSenseLinks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('channelGroup', async () => { + const fakePath = '/rendered/path/channelGroup'; + const expectedParameters = { + property: 'propertyValue', + channel_group: 'channelGroupValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.channelGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.channelGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('channelGroupPath', () => { + const result = client.channelGroupPath( + 'propertyValue', + 'channelGroupValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.channelGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromChannelGroupName', () => { + const result = client.matchPropertyFromChannelGroupName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.channelGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchChannelGroupFromChannelGroupName', () => { + const result = client.matchChannelGroupFromChannelGroupName(fakePath); + assert.strictEqual(result, 'channelGroupValue'); + assert( + (client.pathTemplates.channelGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); - describe('listEventCreateRules', () => { - it('invokes listEventCreateRules without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListEventCreateRulesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListEventCreateRulesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventCreateRule()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventCreateRule()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventCreateRule()), - ]; - client.innerApiCalls.listEventCreateRules = stubSimpleCall(expectedResponse); - const [response] = await client.listEventCreateRules(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listEventCreateRules as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listEventCreateRules as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listEventCreateRules without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListEventCreateRulesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListEventCreateRulesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventCreateRule()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventCreateRule()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventCreateRule()), - ]; - client.innerApiCalls.listEventCreateRules = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listEventCreateRules( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IEventCreateRule[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listEventCreateRules as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listEventCreateRules as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listEventCreateRules with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListEventCreateRulesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListEventCreateRulesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listEventCreateRules = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listEventCreateRules(request), expectedError); - const actualRequest = (client.innerApiCalls.listEventCreateRules as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listEventCreateRules as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listEventCreateRulesStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListEventCreateRulesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListEventCreateRulesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventCreateRule()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventCreateRule()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventCreateRule()), - ]; - client.descriptors.page.listEventCreateRules.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listEventCreateRulesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.EventCreateRule[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.EventCreateRule) => { - 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.listEventCreateRules.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listEventCreateRules, request)); - assert( - (client.descriptors.page.listEventCreateRules.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('conversionEvent', async () => { + const fakePath = '/rendered/path/conversionEvent'; + const expectedParameters = { + property: 'propertyValue', + conversion_event: 'conversionEventValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.conversionEventPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.conversionEventPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('conversionEventPath', () => { + const result = client.conversionEventPath( + 'propertyValue', + 'conversionEventValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.conversionEventPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromConversionEventName', () => { + const result = client.matchPropertyFromConversionEventName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.conversionEventPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConversionEventFromConversionEventName', () => { + const result = + client.matchConversionEventFromConversionEventName(fakePath); + assert.strictEqual(result, 'conversionEventValue'); + assert( + (client.pathTemplates.conversionEventPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('invokes listEventCreateRulesStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListEventCreateRulesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListEventCreateRulesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listEventCreateRules.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listEventCreateRulesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.EventCreateRule[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.EventCreateRule) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listEventCreateRules.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listEventCreateRules, request)); - assert( - (client.descriptors.page.listEventCreateRules.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('customDimension', async () => { + const fakePath = '/rendered/path/customDimension'; + const expectedParameters = { + property: 'propertyValue', + custom_dimension: 'customDimensionValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.customDimensionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.customDimensionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('customDimensionPath', () => { + const result = client.customDimensionPath( + 'propertyValue', + 'customDimensionValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.customDimensionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromCustomDimensionName', () => { + const result = client.matchPropertyFromCustomDimensionName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.customDimensionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCustomDimensionFromCustomDimensionName', () => { + const result = + client.matchCustomDimensionFromCustomDimensionName(fakePath); + assert.strictEqual(result, 'customDimensionValue'); + assert( + (client.pathTemplates.customDimensionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('uses async iteration with listEventCreateRules without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListEventCreateRulesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListEventCreateRulesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventCreateRule()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventCreateRule()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventCreateRule()), - ]; - client.descriptors.page.listEventCreateRules.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.IEventCreateRule[] = []; - const iterable = client.listEventCreateRulesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listEventCreateRules.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listEventCreateRules.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('customMetric', async () => { + const fakePath = '/rendered/path/customMetric'; + const expectedParameters = { + property: 'propertyValue', + custom_metric: 'customMetricValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.customMetricPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.customMetricPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('customMetricPath', () => { + const result = client.customMetricPath( + 'propertyValue', + 'customMetricValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.customMetricPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromCustomMetricName', () => { + const result = client.matchPropertyFromCustomMetricName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.customMetricPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCustomMetricFromCustomMetricName', () => { + const result = client.matchCustomMetricFromCustomMetricName(fakePath); + assert.strictEqual(result, 'customMetricValue'); + assert( + (client.pathTemplates.customMetricPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('uses async iteration with listEventCreateRules with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListEventCreateRulesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListEventCreateRulesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listEventCreateRules.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listEventCreateRulesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.IEventCreateRule[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listEventCreateRules.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listEventCreateRules.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('dataRedactionSettings', async () => { + const fakePath = '/rendered/path/dataRedactionSettings'; + const expectedParameters = { + property: 'propertyValue', + data_stream: 'dataStreamValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.dataRedactionSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.dataRedactionSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('dataRedactionSettingsPath', () => { + const result = client.dataRedactionSettingsPath( + 'propertyValue', + 'dataStreamValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.dataRedactionSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromDataRedactionSettingsName', () => { + const result = + client.matchPropertyFromDataRedactionSettingsName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + ( + client.pathTemplates.dataRedactionSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDataStreamFromDataRedactionSettingsName', () => { + const result = + client.matchDataStreamFromDataRedactionSettingsName(fakePath); + assert.strictEqual(result, 'dataStreamValue'); + assert( + ( + client.pathTemplates.dataRedactionSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); - describe('listEventEditRules', () => { - it('invokes listEventEditRules without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListEventEditRulesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListEventEditRulesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventEditRule()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventEditRule()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventEditRule()), - ]; - client.innerApiCalls.listEventEditRules = stubSimpleCall(expectedResponse); - const [response] = await client.listEventEditRules(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listEventEditRules as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listEventEditRules as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listEventEditRules without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListEventEditRulesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListEventEditRulesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventEditRule()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventEditRule()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventEditRule()), - ]; - client.innerApiCalls.listEventEditRules = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listEventEditRules( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IEventEditRule[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listEventEditRules as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listEventEditRules as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listEventEditRules with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListEventEditRulesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListEventEditRulesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listEventEditRules = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listEventEditRules(request), expectedError); - const actualRequest = (client.innerApiCalls.listEventEditRules as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listEventEditRules as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listEventEditRulesStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListEventEditRulesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListEventEditRulesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventEditRule()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventEditRule()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventEditRule()), - ]; - client.descriptors.page.listEventEditRules.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listEventEditRulesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.EventEditRule[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.EventEditRule) => { - 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.listEventEditRules.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listEventEditRules, request)); - assert( - (client.descriptors.page.listEventEditRules.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('dataRetentionSettings', async () => { + const fakePath = '/rendered/path/dataRetentionSettings'; + const expectedParameters = { + property: 'propertyValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.dataRetentionSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.dataRetentionSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('dataRetentionSettingsPath', () => { + const result = client.dataRetentionSettingsPath('propertyValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.dataRetentionSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromDataRetentionSettingsName', () => { + const result = + client.matchPropertyFromDataRetentionSettingsName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + ( + client.pathTemplates.dataRetentionSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('invokes listEventEditRulesStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListEventEditRulesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListEventEditRulesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listEventEditRules.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listEventEditRulesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.EventEditRule[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.EventEditRule) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listEventEditRules.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listEventEditRules, request)); - assert( - (client.descriptors.page.listEventEditRules.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('dataSharingSettings', async () => { + const fakePath = '/rendered/path/dataSharingSettings'; + const expectedParameters = { + account: 'accountValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.dataSharingSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.dataSharingSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('dataSharingSettingsPath', () => { + const result = client.dataSharingSettingsPath('accountValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.dataSharingSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountFromDataSharingSettingsName', () => { + const result = client.matchAccountFromDataSharingSettingsName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + ( + client.pathTemplates.dataSharingSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('uses async iteration with listEventEditRules without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListEventEditRulesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListEventEditRulesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventEditRule()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventEditRule()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.EventEditRule()), - ]; - client.descriptors.page.listEventEditRules.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.IEventEditRule[] = []; - const iterable = client.listEventEditRulesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listEventEditRules.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listEventEditRules.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('dataStream', async () => { + const fakePath = '/rendered/path/dataStream'; + const expectedParameters = { + property: 'propertyValue', + data_stream: 'dataStreamValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.dataStreamPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.dataStreamPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('dataStreamPath', () => { + const result = client.dataStreamPath( + 'propertyValue', + 'dataStreamValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.dataStreamPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromDataStreamName', () => { + const result = client.matchPropertyFromDataStreamName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.dataStreamPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDataStreamFromDataStreamName', () => { + const result = client.matchDataStreamFromDataStreamName(fakePath); + assert.strictEqual(result, 'dataStreamValue'); + assert( + (client.pathTemplates.dataStreamPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('uses async iteration with listEventEditRules with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListEventEditRulesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListEventEditRulesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listEventEditRules.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listEventEditRulesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.IEventEditRule[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listEventEditRules.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listEventEditRules.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('displayVideo360AdvertiserLink', async () => { + const fakePath = '/rendered/path/displayVideo360AdvertiserLink'; + const expectedParameters = { + property: 'propertyValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.displayVideo360AdvertiserLinkPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.displayVideo360AdvertiserLinkPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('displayVideo360AdvertiserLinkPath', () => { + const result = + client.displayVideo360AdvertiserLinkPath('propertyValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.displayVideo360AdvertiserLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromDisplayVideo360AdvertiserLinkName', () => { + const result = + client.matchPropertyFromDisplayVideo360AdvertiserLinkName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + ( + client.pathTemplates.displayVideo360AdvertiserLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); - describe('listCalculatedMetrics', () => { - it('invokes listCalculatedMetrics without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CalculatedMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CalculatedMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CalculatedMetric()), - ]; - client.innerApiCalls.listCalculatedMetrics = stubSimpleCall(expectedResponse); - const [response] = await client.listCalculatedMetrics(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCalculatedMetrics as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCalculatedMetrics as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCalculatedMetrics without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CalculatedMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CalculatedMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CalculatedMetric()), - ]; - client.innerApiCalls.listCalculatedMetrics = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listCalculatedMetrics( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ICalculatedMetric[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCalculatedMetrics as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCalculatedMetrics as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCalculatedMetrics with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listCalculatedMetrics = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listCalculatedMetrics(request), expectedError); - const actualRequest = (client.innerApiCalls.listCalculatedMetrics as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCalculatedMetrics as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCalculatedMetricsStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CalculatedMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CalculatedMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CalculatedMetric()), - ]; - client.descriptors.page.listCalculatedMetrics.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listCalculatedMetricsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.CalculatedMetric[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.CalculatedMetric) => { - 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.listCalculatedMetrics.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCalculatedMetrics, request)); - assert( - (client.descriptors.page.listCalculatedMetrics.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('displayVideo360AdvertiserLinkProposal', async () => { + const fakePath = '/rendered/path/displayVideo360AdvertiserLinkProposal'; + const expectedParameters = { + property: 'propertyValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.displayVideo360AdvertiserLinkProposalPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.displayVideo360AdvertiserLinkProposalPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('displayVideo360AdvertiserLinkProposalPath', () => { + const result = + client.displayVideo360AdvertiserLinkProposalPath('propertyValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates + .displayVideo360AdvertiserLinkProposalPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromDisplayVideo360AdvertiserLinkProposalName', () => { + const result = + client.matchPropertyFromDisplayVideo360AdvertiserLinkProposalName( + fakePath, + ); + assert.strictEqual(result, 'propertyValue'); + assert( + ( + client.pathTemplates + .displayVideo360AdvertiserLinkProposalPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('invokes listCalculatedMetricsStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCalculatedMetrics.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listCalculatedMetricsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.CalculatedMetric[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.CalculatedMetric) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listCalculatedMetrics.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCalculatedMetrics, request)); - assert( - (client.descriptors.page.listCalculatedMetrics.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('enhancedMeasurementSettings', async () => { + const fakePath = '/rendered/path/enhancedMeasurementSettings'; + const expectedParameters = { + property: 'propertyValue', + data_stream: 'dataStreamValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.enhancedMeasurementSettingsPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.enhancedMeasurementSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('enhancedMeasurementSettingsPath', () => { + const result = client.enhancedMeasurementSettingsPath( + 'propertyValue', + 'dataStreamValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.enhancedMeasurementSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromEnhancedMeasurementSettingsName', () => { + const result = + client.matchPropertyFromEnhancedMeasurementSettingsName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + ( + client.pathTemplates.enhancedMeasurementSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDataStreamFromEnhancedMeasurementSettingsName', () => { + const result = + client.matchDataStreamFromEnhancedMeasurementSettingsName(fakePath); + assert.strictEqual(result, 'dataStreamValue'); + assert( + ( + client.pathTemplates.enhancedMeasurementSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('uses async iteration with listCalculatedMetrics without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CalculatedMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CalculatedMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.CalculatedMetric()), - ]; - client.descriptors.page.listCalculatedMetrics.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.ICalculatedMetric[] = []; - const iterable = client.listCalculatedMetricsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listCalculatedMetrics.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCalculatedMetrics.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('eventCreateRule', async () => { + const fakePath = '/rendered/path/eventCreateRule'; + const expectedParameters = { + property: 'propertyValue', + data_stream: 'dataStreamValue', + event_create_rule: 'eventCreateRuleValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.eventCreateRulePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.eventCreateRulePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('eventCreateRulePath', () => { + const result = client.eventCreateRulePath( + 'propertyValue', + 'dataStreamValue', + 'eventCreateRuleValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.eventCreateRulePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromEventCreateRuleName', () => { + const result = client.matchPropertyFromEventCreateRuleName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.eventCreateRulePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDataStreamFromEventCreateRuleName', () => { + const result = client.matchDataStreamFromEventCreateRuleName(fakePath); + assert.strictEqual(result, 'dataStreamValue'); + assert( + (client.pathTemplates.eventCreateRulePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchEventCreateRuleFromEventCreateRuleName', () => { + const result = + client.matchEventCreateRuleFromEventCreateRuleName(fakePath); + assert.strictEqual(result, 'eventCreateRuleValue'); + assert( + (client.pathTemplates.eventCreateRulePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('uses async iteration with listCalculatedMetrics with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListCalculatedMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCalculatedMetrics.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listCalculatedMetricsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.ICalculatedMetric[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listCalculatedMetrics.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCalculatedMetrics.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('eventEditRule', async () => { + const fakePath = '/rendered/path/eventEditRule'; + const expectedParameters = { + property: 'propertyValue', + data_stream: 'dataStreamValue', + event_edit_rule: 'eventEditRuleValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.eventEditRulePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.eventEditRulePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('eventEditRulePath', () => { + const result = client.eventEditRulePath( + 'propertyValue', + 'dataStreamValue', + 'eventEditRuleValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.eventEditRulePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromEventEditRuleName', () => { + const result = client.matchPropertyFromEventEditRuleName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.eventEditRulePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDataStreamFromEventEditRuleName', () => { + const result = client.matchDataStreamFromEventEditRuleName(fakePath); + assert.strictEqual(result, 'dataStreamValue'); + assert( + (client.pathTemplates.eventEditRulePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchEventEditRuleFromEventEditRuleName', () => { + const result = client.matchEventEditRuleFromEventEditRuleName(fakePath); + assert.strictEqual(result, 'eventEditRuleValue'); + assert( + (client.pathTemplates.eventEditRulePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); - describe('listRollupPropertySourceLinks', () => { - it('invokes listRollupPropertySourceLinks without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink()), - ]; - client.innerApiCalls.listRollupPropertySourceLinks = stubSimpleCall(expectedResponse); - const [response] = await client.listRollupPropertySourceLinks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listRollupPropertySourceLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listRollupPropertySourceLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listRollupPropertySourceLinks without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink()), - ]; - client.innerApiCalls.listRollupPropertySourceLinks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listRollupPropertySourceLinks( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listRollupPropertySourceLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listRollupPropertySourceLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listRollupPropertySourceLinks with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listRollupPropertySourceLinks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listRollupPropertySourceLinks(request), expectedError); - const actualRequest = (client.innerApiCalls.listRollupPropertySourceLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listRollupPropertySourceLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listRollupPropertySourceLinksStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink()), - ]; - client.descriptors.page.listRollupPropertySourceLinks.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listRollupPropertySourceLinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.RollupPropertySourceLink[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.RollupPropertySourceLink) => { - 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.listRollupPropertySourceLinks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listRollupPropertySourceLinks, request)); - assert( - (client.descriptors.page.listRollupPropertySourceLinks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('expandedDataSet', async () => { + const fakePath = '/rendered/path/expandedDataSet'; + const expectedParameters = { + property: 'propertyValue', + expanded_data_set: 'expandedDataSetValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.expandedDataSetPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.expandedDataSetPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('expandedDataSetPath', () => { + const result = client.expandedDataSetPath( + 'propertyValue', + 'expandedDataSetValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.expandedDataSetPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromExpandedDataSetName', () => { + const result = client.matchPropertyFromExpandedDataSetName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.expandedDataSetPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchExpandedDataSetFromExpandedDataSetName', () => { + const result = + client.matchExpandedDataSetFromExpandedDataSetName(fakePath); + assert.strictEqual(result, 'expandedDataSetValue'); + assert( + (client.pathTemplates.expandedDataSetPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('invokes listRollupPropertySourceLinksStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listRollupPropertySourceLinks.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listRollupPropertySourceLinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.RollupPropertySourceLink[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.RollupPropertySourceLink) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listRollupPropertySourceLinks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listRollupPropertySourceLinks, request)); - assert( - (client.descriptors.page.listRollupPropertySourceLinks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('firebaseLink', async () => { + const fakePath = '/rendered/path/firebaseLink'; + const expectedParameters = { + property: 'propertyValue', + firebase_link: 'firebaseLinkValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.firebaseLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.firebaseLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('firebaseLinkPath', () => { + const result = client.firebaseLinkPath( + 'propertyValue', + 'firebaseLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.firebaseLinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromFirebaseLinkName', () => { + const result = client.matchPropertyFromFirebaseLinkName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.firebaseLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchFirebaseLinkFromFirebaseLinkName', () => { + const result = client.matchFirebaseLinkFromFirebaseLinkName(fakePath); + assert.strictEqual(result, 'firebaseLinkValue'); + assert( + (client.pathTemplates.firebaseLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('uses async iteration with listRollupPropertySourceLinks without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.RollupPropertySourceLink()), - ]; - client.descriptors.page.listRollupPropertySourceLinks.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink[] = []; - const iterable = client.listRollupPropertySourceLinksAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listRollupPropertySourceLinks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listRollupPropertySourceLinks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('globalSiteTag', async () => { + const fakePath = '/rendered/path/globalSiteTag'; + const expectedParameters = { + property: 'propertyValue', + data_stream: 'dataStreamValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.globalSiteTagPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.globalSiteTagPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('globalSiteTagPath', () => { + const result = client.globalSiteTagPath( + 'propertyValue', + 'dataStreamValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.globalSiteTagPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromGlobalSiteTagName', () => { + const result = client.matchPropertyFromGlobalSiteTagName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.globalSiteTagPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDataStreamFromGlobalSiteTagName', () => { + const result = client.matchDataStreamFromGlobalSiteTagName(fakePath); + assert.strictEqual(result, 'dataStreamValue'); + assert( + (client.pathTemplates.globalSiteTagPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('uses async iteration with listRollupPropertySourceLinks with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListRollupPropertySourceLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listRollupPropertySourceLinks.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listRollupPropertySourceLinksAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.IRollupPropertySourceLink[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listRollupPropertySourceLinks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listRollupPropertySourceLinks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('googleAdsLink', async () => { + const fakePath = '/rendered/path/googleAdsLink'; + const expectedParameters = { + property: 'propertyValue', + google_ads_link: 'googleAdsLinkValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.googleAdsLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.googleAdsLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('googleAdsLinkPath', () => { + const result = client.googleAdsLinkPath( + 'propertyValue', + 'googleAdsLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.googleAdsLinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromGoogleAdsLinkName', () => { + const result = client.matchPropertyFromGoogleAdsLinkName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.googleAdsLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGoogleAdsLinkFromGoogleAdsLinkName', () => { + const result = client.matchGoogleAdsLinkFromGoogleAdsLinkName(fakePath); + assert.strictEqual(result, 'googleAdsLinkValue'); + assert( + (client.pathTemplates.googleAdsLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); - describe('listSubpropertyEventFilters', () => { - it('invokes listSubpropertyEventFilters without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter()), - ]; - client.innerApiCalls.listSubpropertyEventFilters = stubSimpleCall(expectedResponse); - const [response] = await client.listSubpropertyEventFilters(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listSubpropertyEventFilters as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listSubpropertyEventFilters as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listSubpropertyEventFilters without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter()), - ]; - client.innerApiCalls.listSubpropertyEventFilters = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listSubpropertyEventFilters( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listSubpropertyEventFilters as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listSubpropertyEventFilters as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listSubpropertyEventFilters with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listSubpropertyEventFilters = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listSubpropertyEventFilters(request), expectedError); - const actualRequest = (client.innerApiCalls.listSubpropertyEventFilters as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listSubpropertyEventFilters as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listSubpropertyEventFiltersStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter()), - ]; - client.descriptors.page.listSubpropertyEventFilters.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listSubpropertyEventFiltersStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.SubpropertyEventFilter[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.SubpropertyEventFilter) => { - 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.listSubpropertyEventFilters.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listSubpropertyEventFilters, request)); - assert( - (client.descriptors.page.listSubpropertyEventFilters.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('googleSignalsSettings', async () => { + const fakePath = '/rendered/path/googleSignalsSettings'; + const expectedParameters = { + property: 'propertyValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.googleSignalsSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.googleSignalsSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('googleSignalsSettingsPath', () => { + const result = client.googleSignalsSettingsPath('propertyValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.googleSignalsSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromGoogleSignalsSettingsName', () => { + const result = + client.matchPropertyFromGoogleSignalsSettingsName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + ( + client.pathTemplates.googleSignalsSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('invokes listSubpropertyEventFiltersStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listSubpropertyEventFilters.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listSubpropertyEventFiltersStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.SubpropertyEventFilter[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.SubpropertyEventFilter) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listSubpropertyEventFilters.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listSubpropertyEventFilters, request)); - assert( - (client.descriptors.page.listSubpropertyEventFilters.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('keyEvent', async () => { + const fakePath = '/rendered/path/keyEvent'; + const expectedParameters = { + property: 'propertyValue', + key_event: 'keyEventValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.keyEventPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.keyEventPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('keyEventPath', () => { + const result = client.keyEventPath('propertyValue', 'keyEventValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.keyEventPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromKeyEventName', () => { + const result = client.matchPropertyFromKeyEventName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.keyEventPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchKeyEventFromKeyEventName', () => { + const result = client.matchKeyEventFromKeyEventName(fakePath); + assert.strictEqual(result, 'keyEventValue'); + assert( + (client.pathTemplates.keyEventPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('uses async iteration with listSubpropertyEventFilters without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertyEventFilter()), - ]; - client.descriptors.page.listSubpropertyEventFilters.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter[] = []; - const iterable = client.listSubpropertyEventFiltersAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listSubpropertyEventFilters.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listSubpropertyEventFilters.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('measurementProtocolSecret', async () => { + const fakePath = '/rendered/path/measurementProtocolSecret'; + const expectedParameters = { + property: 'propertyValue', + data_stream: 'dataStreamValue', + measurement_protocol_secret: 'measurementProtocolSecretValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.measurementProtocolSecretPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.measurementProtocolSecretPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('measurementProtocolSecretPath', () => { + const result = client.measurementProtocolSecretPath( + 'propertyValue', + 'dataStreamValue', + 'measurementProtocolSecretValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.measurementProtocolSecretPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromMeasurementProtocolSecretName', () => { + const result = + client.matchPropertyFromMeasurementProtocolSecretName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + ( + client.pathTemplates.measurementProtocolSecretPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDataStreamFromMeasurementProtocolSecretName', () => { + const result = + client.matchDataStreamFromMeasurementProtocolSecretName(fakePath); + assert.strictEqual(result, 'dataStreamValue'); + assert( + ( + client.pathTemplates.measurementProtocolSecretPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMeasurementProtocolSecretFromMeasurementProtocolSecretName', () => { + const result = + client.matchMeasurementProtocolSecretFromMeasurementProtocolSecretName( + fakePath, + ); + assert.strictEqual(result, 'measurementProtocolSecretValue'); + assert( + ( + client.pathTemplates.measurementProtocolSecretPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('uses async iteration with listSubpropertyEventFilters with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSubpropertyEventFiltersRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listSubpropertyEventFilters.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listSubpropertyEventFiltersAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.ISubpropertyEventFilter[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listSubpropertyEventFilters.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listSubpropertyEventFilters.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('property', async () => { + const fakePath = '/rendered/path/property'; + const expectedParameters = { + property: 'propertyValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.propertyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.propertyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('propertyPath', () => { + const result = client.propertyPath('propertyValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.propertyPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromPropertyName', () => { + const result = client.matchPropertyFromPropertyName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.propertyPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); - describe('listReportingDataAnnotations', () => { - it('invokes listReportingDataAnnotations without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation()), - ]; - client.innerApiCalls.listReportingDataAnnotations = stubSimpleCall(expectedResponse); - const [response] = await client.listReportingDataAnnotations(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listReportingDataAnnotations as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listReportingDataAnnotations as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listReportingDataAnnotations without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation()), - ]; - client.innerApiCalls.listReportingDataAnnotations = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listReportingDataAnnotations( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.IReportingDataAnnotation[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listReportingDataAnnotations as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listReportingDataAnnotations as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listReportingDataAnnotations with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listReportingDataAnnotations = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listReportingDataAnnotations(request), expectedError); - const actualRequest = (client.innerApiCalls.listReportingDataAnnotations as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listReportingDataAnnotations as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listReportingDataAnnotationsStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation()), - ]; - client.descriptors.page.listReportingDataAnnotations.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listReportingDataAnnotationsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.ReportingDataAnnotation[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.ReportingDataAnnotation) => { - 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.listReportingDataAnnotations.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listReportingDataAnnotations, request)); - assert( - (client.descriptors.page.listReportingDataAnnotations.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('propertyAccessBinding', async () => { + const fakePath = '/rendered/path/propertyAccessBinding'; + const expectedParameters = { + property: 'propertyValue', + access_binding: 'accessBindingValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.propertyAccessBindingPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.propertyAccessBindingPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('propertyAccessBindingPath', () => { + const result = client.propertyAccessBindingPath( + 'propertyValue', + 'accessBindingValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.propertyAccessBindingPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromPropertyAccessBindingName', () => { + const result = + client.matchPropertyFromPropertyAccessBindingName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + ( + client.pathTemplates.propertyAccessBindingPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAccessBindingFromPropertyAccessBindingName', () => { + const result = + client.matchAccessBindingFromPropertyAccessBindingName(fakePath); + assert.strictEqual(result, 'accessBindingValue'); + assert( + ( + client.pathTemplates.propertyAccessBindingPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('invokes listReportingDataAnnotationsStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listReportingDataAnnotations.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listReportingDataAnnotationsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.ReportingDataAnnotation[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.ReportingDataAnnotation) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listReportingDataAnnotations.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listReportingDataAnnotations, request)); - assert( - (client.descriptors.page.listReportingDataAnnotations.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('reportingDataAnnotation', async () => { + const fakePath = '/rendered/path/reportingDataAnnotation'; + const expectedParameters = { + property: 'propertyValue', + reporting_data_annotation: 'reportingDataAnnotationValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.reportingDataAnnotationPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.reportingDataAnnotationPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('reportingDataAnnotationPath', () => { + const result = client.reportingDataAnnotationPath( + 'propertyValue', + 'reportingDataAnnotationValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.reportingDataAnnotationPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromReportingDataAnnotationName', () => { + const result = + client.matchPropertyFromReportingDataAnnotationName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + ( + client.pathTemplates.reportingDataAnnotationPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchReportingDataAnnotationFromReportingDataAnnotationName', () => { + const result = + client.matchReportingDataAnnotationFromReportingDataAnnotationName( + fakePath, + ); + assert.strictEqual(result, 'reportingDataAnnotationValue'); + assert( + ( + client.pathTemplates.reportingDataAnnotationPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('uses async iteration with listReportingDataAnnotations without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.ReportingDataAnnotation()), - ]; - client.descriptors.page.listReportingDataAnnotations.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.IReportingDataAnnotation[] = []; - const iterable = client.listReportingDataAnnotationsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listReportingDataAnnotations.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listReportingDataAnnotations.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('reportingIdentitySettings', async () => { + const fakePath = '/rendered/path/reportingIdentitySettings'; + const expectedParameters = { + property: 'propertyValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.reportingIdentitySettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.reportingIdentitySettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('reportingIdentitySettingsPath', () => { + const result = client.reportingIdentitySettingsPath('propertyValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.reportingIdentitySettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromReportingIdentitySettingsName', () => { + const result = + client.matchPropertyFromReportingIdentitySettingsName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + ( + client.pathTemplates.reportingIdentitySettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('uses async iteration with listReportingDataAnnotations with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListReportingDataAnnotationsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listReportingDataAnnotations.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listReportingDataAnnotationsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.IReportingDataAnnotation[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listReportingDataAnnotations.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listReportingDataAnnotations.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('rollupPropertySourceLink', async () => { + const fakePath = '/rendered/path/rollupPropertySourceLink'; + const expectedParameters = { + property: 'propertyValue', + rollup_property_source_link: 'rollupPropertySourceLinkValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.rollupPropertySourceLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.rollupPropertySourceLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('rollupPropertySourceLinkPath', () => { + const result = client.rollupPropertySourceLinkPath( + 'propertyValue', + 'rollupPropertySourceLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.rollupPropertySourceLinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromRollupPropertySourceLinkName', () => { + const result = + client.matchPropertyFromRollupPropertySourceLinkName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + ( + client.pathTemplates.rollupPropertySourceLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchRollupPropertySourceLinkFromRollupPropertySourceLinkName', () => { + const result = + client.matchRollupPropertySourceLinkFromRollupPropertySourceLinkName( + fakePath, + ); + assert.strictEqual(result, 'rollupPropertySourceLinkValue'); + assert( + ( + client.pathTemplates.rollupPropertySourceLinkPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); - describe('listSubpropertySyncConfigs', () => { - it('invokes listSubpropertySyncConfigs without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig()), - ]; - client.innerApiCalls.listSubpropertySyncConfigs = stubSimpleCall(expectedResponse); - const [response] = await client.listSubpropertySyncConfigs(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listSubpropertySyncConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listSubpropertySyncConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listSubpropertySyncConfigs without error using callback', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig()), - ]; - client.innerApiCalls.listSubpropertySyncConfigs = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listSubpropertySyncConfigs( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listSubpropertySyncConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listSubpropertySyncConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listSubpropertySyncConfigs with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listSubpropertySyncConfigs = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listSubpropertySyncConfigs(request), expectedError); - const actualRequest = (client.innerApiCalls.listSubpropertySyncConfigs as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listSubpropertySyncConfigs as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listSubpropertySyncConfigsStream without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig()), - ]; - client.descriptors.page.listSubpropertySyncConfigs.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listSubpropertySyncConfigsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.SubpropertySyncConfig[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.SubpropertySyncConfig) => { - 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.listSubpropertySyncConfigs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listSubpropertySyncConfigs, request)); - assert( - (client.descriptors.page.listSubpropertySyncConfigs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('sKAdNetworkConversionValueSchema', async () => { + const fakePath = '/rendered/path/sKAdNetworkConversionValueSchema'; + const expectedParameters = { + property: 'propertyValue', + data_stream: 'dataStreamValue', + skadnetwork_conversion_value_schema: + 'skadnetworkConversionValueSchemaValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.sKAdNetworkConversionValueSchemaPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.sKAdNetworkConversionValueSchemaPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('sKAdNetworkConversionValueSchemaPath', () => { + const result = client.sKAdNetworkConversionValueSchemaPath( + 'propertyValue', + 'dataStreamValue', + 'skadnetworkConversionValueSchemaValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.sKAdNetworkConversionValueSchemaPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromSKAdNetworkConversionValueSchemaName', () => { + const result = + client.matchPropertyFromSKAdNetworkConversionValueSchemaName( + fakePath, + ); + assert.strictEqual(result, 'propertyValue'); + assert( + ( + client.pathTemplates.sKAdNetworkConversionValueSchemaPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDataStreamFromSKAdNetworkConversionValueSchemaName', () => { + const result = + client.matchDataStreamFromSKAdNetworkConversionValueSchemaName( + fakePath, + ); + assert.strictEqual(result, 'dataStreamValue'); + assert( + ( + client.pathTemplates.sKAdNetworkConversionValueSchemaPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSkadnetworkConversionValueSchemaFromSKAdNetworkConversionValueSchemaName', () => { + const result = + client.matchSkadnetworkConversionValueSchemaFromSKAdNetworkConversionValueSchemaName( + fakePath, + ); + assert.strictEqual(result, 'skadnetworkConversionValueSchemaValue'); + assert( + ( + client.pathTemplates.sKAdNetworkConversionValueSchemaPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('invokes listSubpropertySyncConfigsStream with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listSubpropertySyncConfigs.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listSubpropertySyncConfigsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1alpha.SubpropertySyncConfig[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1alpha.SubpropertySyncConfig) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listSubpropertySyncConfigs.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listSubpropertySyncConfigs, request)); - assert( - (client.descriptors.page.listSubpropertySyncConfigs.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('searchAds360Link', async () => { + const fakePath = '/rendered/path/searchAds360Link'; + const expectedParameters = { + property: 'propertyValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.searchAds360LinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.searchAds360LinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('searchAds360LinkPath', () => { + const result = client.searchAds360LinkPath('propertyValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.searchAds360LinkPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromSearchAds360LinkName', () => { + const result = client.matchPropertyFromSearchAds360LinkName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.searchAds360LinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('uses async iteration with listSubpropertySyncConfigs without error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig()), - generateSampleMessage(new protos.google.analytics.admin.v1alpha.SubpropertySyncConfig()), - ]; - client.descriptors.page.listSubpropertySyncConfigs.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig[] = []; - const iterable = client.listSubpropertySyncConfigsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listSubpropertySyncConfigs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listSubpropertySyncConfigs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('subpropertyEventFilter', async () => { + const fakePath = '/rendered/path/subpropertyEventFilter'; + const expectedParameters = { + property: 'propertyValue', + sub_property_event_filter: 'subPropertyEventFilterValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.subpropertyEventFilterPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.subpropertyEventFilterPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('subpropertyEventFilterPath', () => { + const result = client.subpropertyEventFilterPath( + 'propertyValue', + 'subPropertyEventFilterValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.subpropertyEventFilterPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromSubpropertyEventFilterName', () => { + const result = + client.matchPropertyFromSubpropertyEventFilterName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + ( + client.pathTemplates.subpropertyEventFilterPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSubPropertyEventFilterFromSubpropertyEventFilterName', () => { + const result = + client.matchSubPropertyEventFilterFromSubpropertyEventFilterName( + fakePath, + ); + assert.strictEqual(result, 'subPropertyEventFilterValue'); + assert( + ( + client.pathTemplates.subpropertyEventFilterPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('uses async iteration with listSubpropertySyncConfigs with error', async () => { - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1alpha.ListSubpropertySyncConfigsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listSubpropertySyncConfigs.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listSubpropertySyncConfigsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1alpha.ISubpropertySyncConfig[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listSubpropertySyncConfigs.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listSubpropertySyncConfigs.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + describe('subpropertySyncConfig', async () => { + const fakePath = '/rendered/path/subpropertySyncConfig'; + const expectedParameters = { + property: 'propertyValue', + subproperty_sync_config: 'subpropertySyncConfigValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.subpropertySyncConfigPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.subpropertySyncConfigPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('subpropertySyncConfigPath', () => { + const result = client.subpropertySyncConfigPath( + 'propertyValue', + 'subpropertySyncConfigValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.subpropertySyncConfigPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromSubpropertySyncConfigName', () => { + const result = + client.matchPropertyFromSubpropertySyncConfigName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + ( + client.pathTemplates.subpropertySyncConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchSubpropertySyncConfigFromSubpropertySyncConfigName', () => { + const result = + client.matchSubpropertySyncConfigFromSubpropertySyncConfigName( + fakePath, + ); + assert.strictEqual(result, 'subpropertySyncConfigValue'); + assert( + ( + client.pathTemplates.subpropertySyncConfigPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); - describe('Path templates', () => { - - describe('account', async () => { - const fakePath = "/rendered/path/account"; - const expectedParameters = { - account: "accountValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.accountPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.accountPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('accountPath', () => { - const result = client.accountPath("accountValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.accountPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountFromAccountName', () => { - const result = client.matchAccountFromAccountName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.accountPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('accountAccessBinding', async () => { - const fakePath = "/rendered/path/accountAccessBinding"; - const expectedParameters = { - account: "accountValue", - access_binding: "accessBindingValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.accountAccessBindingPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.accountAccessBindingPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('accountAccessBindingPath', () => { - const result = client.accountAccessBindingPath("accountValue", "accessBindingValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.accountAccessBindingPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountFromAccountAccessBindingName', () => { - const result = client.matchAccountFromAccountAccessBindingName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.accountAccessBindingPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccessBindingFromAccountAccessBindingName', () => { - const result = client.matchAccessBindingFromAccountAccessBindingName(fakePath); - assert.strictEqual(result, "accessBindingValue"); - assert((client.pathTemplates.accountAccessBindingPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('accountSummary', async () => { - const fakePath = "/rendered/path/accountSummary"; - const expectedParameters = { - account_summary: "accountSummaryValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.accountSummaryPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.accountSummaryPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('accountSummaryPath', () => { - const result = client.accountSummaryPath("accountSummaryValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.accountSummaryPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountSummaryFromAccountSummaryName', () => { - const result = client.matchAccountSummaryFromAccountSummaryName(fakePath); - assert.strictEqual(result, "accountSummaryValue"); - assert((client.pathTemplates.accountSummaryPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('adSenseLink', async () => { - const fakePath = "/rendered/path/adSenseLink"; - const expectedParameters = { - property: "propertyValue", - adsense_link: "adsenseLinkValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.adSenseLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.adSenseLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('adSenseLinkPath', () => { - const result = client.adSenseLinkPath("propertyValue", "adsenseLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.adSenseLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromAdSenseLinkName', () => { - const result = client.matchPropertyFromAdSenseLinkName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.adSenseLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAdsenseLinkFromAdSenseLinkName', () => { - const result = client.matchAdsenseLinkFromAdSenseLinkName(fakePath); - assert.strictEqual(result, "adsenseLinkValue"); - assert((client.pathTemplates.adSenseLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('attributionSettings', async () => { - const fakePath = "/rendered/path/attributionSettings"; - const expectedParameters = { - property: "propertyValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.attributionSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.attributionSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('attributionSettingsPath', () => { - const result = client.attributionSettingsPath("propertyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.attributionSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromAttributionSettingsName', () => { - const result = client.matchPropertyFromAttributionSettingsName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.attributionSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('audience', async () => { - const fakePath = "/rendered/path/audience"; - const expectedParameters = { - property: "propertyValue", - audience: "audienceValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.audiencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.audiencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('audiencePath', () => { - const result = client.audiencePath("propertyValue", "audienceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.audiencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromAudienceName', () => { - const result = client.matchPropertyFromAudienceName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.audiencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAudienceFromAudienceName', () => { - const result = client.matchAudienceFromAudienceName(fakePath); - assert.strictEqual(result, "audienceValue"); - assert((client.pathTemplates.audiencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('bigQueryLink', async () => { - const fakePath = "/rendered/path/bigQueryLink"; - const expectedParameters = { - property: "propertyValue", - bigquery_link: "bigqueryLinkValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.bigQueryLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.bigQueryLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('bigQueryLinkPath', () => { - const result = client.bigQueryLinkPath("propertyValue", "bigqueryLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.bigQueryLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromBigQueryLinkName', () => { - const result = client.matchPropertyFromBigQueryLinkName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.bigQueryLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBigqueryLinkFromBigQueryLinkName', () => { - const result = client.matchBigqueryLinkFromBigQueryLinkName(fakePath); - assert.strictEqual(result, "bigqueryLinkValue"); - assert((client.pathTemplates.bigQueryLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('calculatedMetric', async () => { - const fakePath = "/rendered/path/calculatedMetric"; - const expectedParameters = { - property: "propertyValue", - calculated_metric: "calculatedMetricValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.calculatedMetricPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.calculatedMetricPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('calculatedMetricPath', () => { - const result = client.calculatedMetricPath("propertyValue", "calculatedMetricValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.calculatedMetricPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromCalculatedMetricName', () => { - const result = client.matchPropertyFromCalculatedMetricName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.calculatedMetricPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCalculatedMetricFromCalculatedMetricName', () => { - const result = client.matchCalculatedMetricFromCalculatedMetricName(fakePath); - assert.strictEqual(result, "calculatedMetricValue"); - assert((client.pathTemplates.calculatedMetricPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('channelGroup', async () => { - const fakePath = "/rendered/path/channelGroup"; - const expectedParameters = { - property: "propertyValue", - channel_group: "channelGroupValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.channelGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.channelGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('channelGroupPath', () => { - const result = client.channelGroupPath("propertyValue", "channelGroupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.channelGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromChannelGroupName', () => { - const result = client.matchPropertyFromChannelGroupName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.channelGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchChannelGroupFromChannelGroupName', () => { - const result = client.matchChannelGroupFromChannelGroupName(fakePath); - assert.strictEqual(result, "channelGroupValue"); - assert((client.pathTemplates.channelGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('conversionEvent', async () => { - const fakePath = "/rendered/path/conversionEvent"; - const expectedParameters = { - property: "propertyValue", - conversion_event: "conversionEventValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.conversionEventPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.conversionEventPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('conversionEventPath', () => { - const result = client.conversionEventPath("propertyValue", "conversionEventValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.conversionEventPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromConversionEventName', () => { - const result = client.matchPropertyFromConversionEventName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.conversionEventPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchConversionEventFromConversionEventName', () => { - const result = client.matchConversionEventFromConversionEventName(fakePath); - assert.strictEqual(result, "conversionEventValue"); - assert((client.pathTemplates.conversionEventPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('customDimension', async () => { - const fakePath = "/rendered/path/customDimension"; - const expectedParameters = { - property: "propertyValue", - custom_dimension: "customDimensionValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.customDimensionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.customDimensionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('customDimensionPath', () => { - const result = client.customDimensionPath("propertyValue", "customDimensionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.customDimensionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromCustomDimensionName', () => { - const result = client.matchPropertyFromCustomDimensionName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.customDimensionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCustomDimensionFromCustomDimensionName', () => { - const result = client.matchCustomDimensionFromCustomDimensionName(fakePath); - assert.strictEqual(result, "customDimensionValue"); - assert((client.pathTemplates.customDimensionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('customMetric', async () => { - const fakePath = "/rendered/path/customMetric"; - const expectedParameters = { - property: "propertyValue", - custom_metric: "customMetricValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.customMetricPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.customMetricPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('customMetricPath', () => { - const result = client.customMetricPath("propertyValue", "customMetricValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.customMetricPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromCustomMetricName', () => { - const result = client.matchPropertyFromCustomMetricName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.customMetricPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCustomMetricFromCustomMetricName', () => { - const result = client.matchCustomMetricFromCustomMetricName(fakePath); - assert.strictEqual(result, "customMetricValue"); - assert((client.pathTemplates.customMetricPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('dataRedactionSettings', async () => { - const fakePath = "/rendered/path/dataRedactionSettings"; - const expectedParameters = { - property: "propertyValue", - data_stream: "dataStreamValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.dataRedactionSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.dataRedactionSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('dataRedactionSettingsPath', () => { - const result = client.dataRedactionSettingsPath("propertyValue", "dataStreamValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.dataRedactionSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromDataRedactionSettingsName', () => { - const result = client.matchPropertyFromDataRedactionSettingsName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.dataRedactionSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDataStreamFromDataRedactionSettingsName', () => { - const result = client.matchDataStreamFromDataRedactionSettingsName(fakePath); - assert.strictEqual(result, "dataStreamValue"); - assert((client.pathTemplates.dataRedactionSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('dataRetentionSettings', async () => { - const fakePath = "/rendered/path/dataRetentionSettings"; - const expectedParameters = { - property: "propertyValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.dataRetentionSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.dataRetentionSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('dataRetentionSettingsPath', () => { - const result = client.dataRetentionSettingsPath("propertyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.dataRetentionSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromDataRetentionSettingsName', () => { - const result = client.matchPropertyFromDataRetentionSettingsName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.dataRetentionSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('dataSharingSettings', async () => { - const fakePath = "/rendered/path/dataSharingSettings"; - const expectedParameters = { - account: "accountValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.dataSharingSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.dataSharingSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('dataSharingSettingsPath', () => { - const result = client.dataSharingSettingsPath("accountValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.dataSharingSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchAccountFromDataSharingSettingsName', () => { - const result = client.matchAccountFromDataSharingSettingsName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.dataSharingSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('dataStream', async () => { - const fakePath = "/rendered/path/dataStream"; - const expectedParameters = { - property: "propertyValue", - data_stream: "dataStreamValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.dataStreamPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.dataStreamPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('dataStreamPath', () => { - const result = client.dataStreamPath("propertyValue", "dataStreamValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.dataStreamPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromDataStreamName', () => { - const result = client.matchPropertyFromDataStreamName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.dataStreamPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDataStreamFromDataStreamName', () => { - const result = client.matchDataStreamFromDataStreamName(fakePath); - assert.strictEqual(result, "dataStreamValue"); - assert((client.pathTemplates.dataStreamPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('displayVideo360AdvertiserLink', async () => { - const fakePath = "/rendered/path/displayVideo360AdvertiserLink"; - const expectedParameters = { - property: "propertyValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.displayVideo360AdvertiserLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.displayVideo360AdvertiserLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('displayVideo360AdvertiserLinkPath', () => { - const result = client.displayVideo360AdvertiserLinkPath("propertyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.displayVideo360AdvertiserLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromDisplayVideo360AdvertiserLinkName', () => { - const result = client.matchPropertyFromDisplayVideo360AdvertiserLinkName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.displayVideo360AdvertiserLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('displayVideo360AdvertiserLinkProposal', async () => { - const fakePath = "/rendered/path/displayVideo360AdvertiserLinkProposal"; - const expectedParameters = { - property: "propertyValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.displayVideo360AdvertiserLinkProposalPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.displayVideo360AdvertiserLinkProposalPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('displayVideo360AdvertiserLinkProposalPath', () => { - const result = client.displayVideo360AdvertiserLinkProposalPath("propertyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.displayVideo360AdvertiserLinkProposalPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromDisplayVideo360AdvertiserLinkProposalName', () => { - const result = client.matchPropertyFromDisplayVideo360AdvertiserLinkProposalName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.displayVideo360AdvertiserLinkProposalPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('enhancedMeasurementSettings', async () => { - const fakePath = "/rendered/path/enhancedMeasurementSettings"; - const expectedParameters = { - property: "propertyValue", - data_stream: "dataStreamValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.enhancedMeasurementSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.enhancedMeasurementSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('enhancedMeasurementSettingsPath', () => { - const result = client.enhancedMeasurementSettingsPath("propertyValue", "dataStreamValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.enhancedMeasurementSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromEnhancedMeasurementSettingsName', () => { - const result = client.matchPropertyFromEnhancedMeasurementSettingsName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.enhancedMeasurementSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDataStreamFromEnhancedMeasurementSettingsName', () => { - const result = client.matchDataStreamFromEnhancedMeasurementSettingsName(fakePath); - assert.strictEqual(result, "dataStreamValue"); - assert((client.pathTemplates.enhancedMeasurementSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('eventCreateRule', async () => { - const fakePath = "/rendered/path/eventCreateRule"; - const expectedParameters = { - property: "propertyValue", - data_stream: "dataStreamValue", - event_create_rule: "eventCreateRuleValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.eventCreateRulePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.eventCreateRulePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('eventCreateRulePath', () => { - const result = client.eventCreateRulePath("propertyValue", "dataStreamValue", "eventCreateRuleValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.eventCreateRulePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromEventCreateRuleName', () => { - const result = client.matchPropertyFromEventCreateRuleName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.eventCreateRulePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDataStreamFromEventCreateRuleName', () => { - const result = client.matchDataStreamFromEventCreateRuleName(fakePath); - assert.strictEqual(result, "dataStreamValue"); - assert((client.pathTemplates.eventCreateRulePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchEventCreateRuleFromEventCreateRuleName', () => { - const result = client.matchEventCreateRuleFromEventCreateRuleName(fakePath); - assert.strictEqual(result, "eventCreateRuleValue"); - assert((client.pathTemplates.eventCreateRulePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('eventEditRule', async () => { - const fakePath = "/rendered/path/eventEditRule"; - const expectedParameters = { - property: "propertyValue", - data_stream: "dataStreamValue", - event_edit_rule: "eventEditRuleValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.eventEditRulePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.eventEditRulePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('eventEditRulePath', () => { - const result = client.eventEditRulePath("propertyValue", "dataStreamValue", "eventEditRuleValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.eventEditRulePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromEventEditRuleName', () => { - const result = client.matchPropertyFromEventEditRuleName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.eventEditRulePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDataStreamFromEventEditRuleName', () => { - const result = client.matchDataStreamFromEventEditRuleName(fakePath); - assert.strictEqual(result, "dataStreamValue"); - assert((client.pathTemplates.eventEditRulePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchEventEditRuleFromEventEditRuleName', () => { - const result = client.matchEventEditRuleFromEventEditRuleName(fakePath); - assert.strictEqual(result, "eventEditRuleValue"); - assert((client.pathTemplates.eventEditRulePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('expandedDataSet', async () => { - const fakePath = "/rendered/path/expandedDataSet"; - const expectedParameters = { - property: "propertyValue", - expanded_data_set: "expandedDataSetValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.expandedDataSetPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.expandedDataSetPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('expandedDataSetPath', () => { - const result = client.expandedDataSetPath("propertyValue", "expandedDataSetValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.expandedDataSetPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromExpandedDataSetName', () => { - const result = client.matchPropertyFromExpandedDataSetName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.expandedDataSetPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchExpandedDataSetFromExpandedDataSetName', () => { - const result = client.matchExpandedDataSetFromExpandedDataSetName(fakePath); - assert.strictEqual(result, "expandedDataSetValue"); - assert((client.pathTemplates.expandedDataSetPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('firebaseLink', async () => { - const fakePath = "/rendered/path/firebaseLink"; - const expectedParameters = { - property: "propertyValue", - firebase_link: "firebaseLinkValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.firebaseLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.firebaseLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('firebaseLinkPath', () => { - const result = client.firebaseLinkPath("propertyValue", "firebaseLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.firebaseLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromFirebaseLinkName', () => { - const result = client.matchPropertyFromFirebaseLinkName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.firebaseLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchFirebaseLinkFromFirebaseLinkName', () => { - const result = client.matchFirebaseLinkFromFirebaseLinkName(fakePath); - assert.strictEqual(result, "firebaseLinkValue"); - assert((client.pathTemplates.firebaseLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('globalSiteTag', async () => { - const fakePath = "/rendered/path/globalSiteTag"; - const expectedParameters = { - property: "propertyValue", - data_stream: "dataStreamValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.globalSiteTagPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.globalSiteTagPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('globalSiteTagPath', () => { - const result = client.globalSiteTagPath("propertyValue", "dataStreamValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.globalSiteTagPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromGlobalSiteTagName', () => { - const result = client.matchPropertyFromGlobalSiteTagName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.globalSiteTagPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDataStreamFromGlobalSiteTagName', () => { - const result = client.matchDataStreamFromGlobalSiteTagName(fakePath); - assert.strictEqual(result, "dataStreamValue"); - assert((client.pathTemplates.globalSiteTagPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('googleAdsLink', async () => { - const fakePath = "/rendered/path/googleAdsLink"; - const expectedParameters = { - property: "propertyValue", - google_ads_link: "googleAdsLinkValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.googleAdsLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.googleAdsLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('googleAdsLinkPath', () => { - const result = client.googleAdsLinkPath("propertyValue", "googleAdsLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.googleAdsLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromGoogleAdsLinkName', () => { - const result = client.matchPropertyFromGoogleAdsLinkName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.googleAdsLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchGoogleAdsLinkFromGoogleAdsLinkName', () => { - const result = client.matchGoogleAdsLinkFromGoogleAdsLinkName(fakePath); - assert.strictEqual(result, "googleAdsLinkValue"); - assert((client.pathTemplates.googleAdsLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('googleSignalsSettings', async () => { - const fakePath = "/rendered/path/googleSignalsSettings"; - const expectedParameters = { - property: "propertyValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.googleSignalsSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.googleSignalsSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('googleSignalsSettingsPath', () => { - const result = client.googleSignalsSettingsPath("propertyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.googleSignalsSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromGoogleSignalsSettingsName', () => { - const result = client.matchPropertyFromGoogleSignalsSettingsName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.googleSignalsSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('keyEvent', async () => { - const fakePath = "/rendered/path/keyEvent"; - const expectedParameters = { - property: "propertyValue", - key_event: "keyEventValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.keyEventPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.keyEventPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('keyEventPath', () => { - const result = client.keyEventPath("propertyValue", "keyEventValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.keyEventPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromKeyEventName', () => { - const result = client.matchPropertyFromKeyEventName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.keyEventPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchKeyEventFromKeyEventName', () => { - const result = client.matchKeyEventFromKeyEventName(fakePath); - assert.strictEqual(result, "keyEventValue"); - assert((client.pathTemplates.keyEventPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('measurementProtocolSecret', async () => { - const fakePath = "/rendered/path/measurementProtocolSecret"; - const expectedParameters = { - property: "propertyValue", - data_stream: "dataStreamValue", - measurement_protocol_secret: "measurementProtocolSecretValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.measurementProtocolSecretPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.measurementProtocolSecretPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('measurementProtocolSecretPath', () => { - const result = client.measurementProtocolSecretPath("propertyValue", "dataStreamValue", "measurementProtocolSecretValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.measurementProtocolSecretPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromMeasurementProtocolSecretName', () => { - const result = client.matchPropertyFromMeasurementProtocolSecretName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.measurementProtocolSecretPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDataStreamFromMeasurementProtocolSecretName', () => { - const result = client.matchDataStreamFromMeasurementProtocolSecretName(fakePath); - assert.strictEqual(result, "dataStreamValue"); - assert((client.pathTemplates.measurementProtocolSecretPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchMeasurementProtocolSecretFromMeasurementProtocolSecretName', () => { - const result = client.matchMeasurementProtocolSecretFromMeasurementProtocolSecretName(fakePath); - assert.strictEqual(result, "measurementProtocolSecretValue"); - assert((client.pathTemplates.measurementProtocolSecretPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('property', async () => { - const fakePath = "/rendered/path/property"; - const expectedParameters = { - property: "propertyValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.propertyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.propertyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('propertyPath', () => { - const result = client.propertyPath("propertyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.propertyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromPropertyName', () => { - const result = client.matchPropertyFromPropertyName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.propertyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('propertyAccessBinding', async () => { - const fakePath = "/rendered/path/propertyAccessBinding"; - const expectedParameters = { - property: "propertyValue", - access_binding: "accessBindingValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.propertyAccessBindingPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.propertyAccessBindingPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('propertyAccessBindingPath', () => { - const result = client.propertyAccessBindingPath("propertyValue", "accessBindingValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.propertyAccessBindingPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromPropertyAccessBindingName', () => { - const result = client.matchPropertyFromPropertyAccessBindingName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.propertyAccessBindingPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAccessBindingFromPropertyAccessBindingName', () => { - const result = client.matchAccessBindingFromPropertyAccessBindingName(fakePath); - assert.strictEqual(result, "accessBindingValue"); - assert((client.pathTemplates.propertyAccessBindingPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('reportingDataAnnotation', async () => { - const fakePath = "/rendered/path/reportingDataAnnotation"; - const expectedParameters = { - property: "propertyValue", - reporting_data_annotation: "reportingDataAnnotationValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.reportingDataAnnotationPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.reportingDataAnnotationPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('reportingDataAnnotationPath', () => { - const result = client.reportingDataAnnotationPath("propertyValue", "reportingDataAnnotationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.reportingDataAnnotationPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromReportingDataAnnotationName', () => { - const result = client.matchPropertyFromReportingDataAnnotationName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.reportingDataAnnotationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchReportingDataAnnotationFromReportingDataAnnotationName', () => { - const result = client.matchReportingDataAnnotationFromReportingDataAnnotationName(fakePath); - assert.strictEqual(result, "reportingDataAnnotationValue"); - assert((client.pathTemplates.reportingDataAnnotationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('reportingIdentitySettings', async () => { - const fakePath = "/rendered/path/reportingIdentitySettings"; - const expectedParameters = { - property: "propertyValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.reportingIdentitySettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.reportingIdentitySettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('reportingIdentitySettingsPath', () => { - const result = client.reportingIdentitySettingsPath("propertyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.reportingIdentitySettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromReportingIdentitySettingsName', () => { - const result = client.matchPropertyFromReportingIdentitySettingsName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.reportingIdentitySettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('rollupPropertySourceLink', async () => { - const fakePath = "/rendered/path/rollupPropertySourceLink"; - const expectedParameters = { - property: "propertyValue", - rollup_property_source_link: "rollupPropertySourceLinkValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.rollupPropertySourceLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.rollupPropertySourceLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('rollupPropertySourceLinkPath', () => { - const result = client.rollupPropertySourceLinkPath("propertyValue", "rollupPropertySourceLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.rollupPropertySourceLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromRollupPropertySourceLinkName', () => { - const result = client.matchPropertyFromRollupPropertySourceLinkName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.rollupPropertySourceLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchRollupPropertySourceLinkFromRollupPropertySourceLinkName', () => { - const result = client.matchRollupPropertySourceLinkFromRollupPropertySourceLinkName(fakePath); - assert.strictEqual(result, "rollupPropertySourceLinkValue"); - assert((client.pathTemplates.rollupPropertySourceLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('sKAdNetworkConversionValueSchema', async () => { - const fakePath = "/rendered/path/sKAdNetworkConversionValueSchema"; - const expectedParameters = { - property: "propertyValue", - data_stream: "dataStreamValue", - skadnetwork_conversion_value_schema: "skadnetworkConversionValueSchemaValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.sKAdNetworkConversionValueSchemaPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.sKAdNetworkConversionValueSchemaPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('sKAdNetworkConversionValueSchemaPath', () => { - const result = client.sKAdNetworkConversionValueSchemaPath("propertyValue", "dataStreamValue", "skadnetworkConversionValueSchemaValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.sKAdNetworkConversionValueSchemaPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromSKAdNetworkConversionValueSchemaName', () => { - const result = client.matchPropertyFromSKAdNetworkConversionValueSchemaName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.sKAdNetworkConversionValueSchemaPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDataStreamFromSKAdNetworkConversionValueSchemaName', () => { - const result = client.matchDataStreamFromSKAdNetworkConversionValueSchemaName(fakePath); - assert.strictEqual(result, "dataStreamValue"); - assert((client.pathTemplates.sKAdNetworkConversionValueSchemaPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSkadnetworkConversionValueSchemaFromSKAdNetworkConversionValueSchemaName', () => { - const result = client.matchSkadnetworkConversionValueSchemaFromSKAdNetworkConversionValueSchemaName(fakePath); - assert.strictEqual(result, "skadnetworkConversionValueSchemaValue"); - assert((client.pathTemplates.sKAdNetworkConversionValueSchemaPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('searchAds360Link', async () => { - const fakePath = "/rendered/path/searchAds360Link"; - const expectedParameters = { - property: "propertyValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.searchAds360LinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.searchAds360LinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('searchAds360LinkPath', () => { - const result = client.searchAds360LinkPath("propertyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.searchAds360LinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromSearchAds360LinkName', () => { - const result = client.matchPropertyFromSearchAds360LinkName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.searchAds360LinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('subpropertyEventFilter', async () => { - const fakePath = "/rendered/path/subpropertyEventFilter"; - const expectedParameters = { - property: "propertyValue", - sub_property_event_filter: "subPropertyEventFilterValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.subpropertyEventFilterPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.subpropertyEventFilterPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('subpropertyEventFilterPath', () => { - const result = client.subpropertyEventFilterPath("propertyValue", "subPropertyEventFilterValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.subpropertyEventFilterPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromSubpropertyEventFilterName', () => { - const result = client.matchPropertyFromSubpropertyEventFilterName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.subpropertyEventFilterPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSubPropertyEventFilterFromSubpropertyEventFilterName', () => { - const result = client.matchSubPropertyEventFilterFromSubpropertyEventFilterName(fakePath); - assert.strictEqual(result, "subPropertyEventFilterValue"); - assert((client.pathTemplates.subpropertyEventFilterPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('subpropertySyncConfig', async () => { - const fakePath = "/rendered/path/subpropertySyncConfig"; - const expectedParameters = { - property: "propertyValue", - subproperty_sync_config: "subpropertySyncConfigValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.subpropertySyncConfigPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.subpropertySyncConfigPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('subpropertySyncConfigPath', () => { - const result = client.subpropertySyncConfigPath("propertyValue", "subpropertySyncConfigValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.subpropertySyncConfigPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromSubpropertySyncConfigName', () => { - const result = client.matchPropertyFromSubpropertySyncConfigName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.subpropertySyncConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchSubpropertySyncConfigFromSubpropertySyncConfigName', () => { - const result = client.matchSubpropertySyncConfigFromSubpropertySyncConfigName(fakePath); - assert.strictEqual(result, "subpropertySyncConfigValue"); - assert((client.pathTemplates.subpropertySyncConfigPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('userProvidedDataSettings', async () => { - const fakePath = "/rendered/path/userProvidedDataSettings"; - const expectedParameters = { - property: "propertyValue", - }; - const client = new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userProvidedDataSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userProvidedDataSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userProvidedDataSettingsPath', () => { - const result = client.userProvidedDataSettingsPath("propertyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userProvidedDataSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromUserProvidedDataSettingsName', () => { - const result = client.matchPropertyFromUserProvidedDataSettingsName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.userProvidedDataSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userProvidedDataSettings', async () => { + const fakePath = '/rendered/path/userProvidedDataSettings'; + const expectedParameters = { + property: 'propertyValue', + }; + const client = + new analyticsadminserviceModule.v1alpha.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userProvidedDataSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userProvidedDataSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userProvidedDataSettingsPath', () => { + const result = client.userProvidedDataSettingsPath('propertyValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.userProvidedDataSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromUserProvidedDataSettingsName', () => { + const result = + client.matchPropertyFromUserProvidedDataSettingsName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + ( + client.pathTemplates.userProvidedDataSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-analytics-admin/test/gapic_analytics_admin_service_v1beta.ts b/packages/google-analytics-admin/test/gapic_analytics_admin_service_v1beta.ts index 5328a0c1fa5a..88075e5db74f 100644 --- a/packages/google-analytics-admin/test/gapic_analytics_admin_service_v1beta.ts +++ b/packages/google-analytics-admin/test/gapic_analytics_admin_service_v1beta.ts @@ -19,7994 +19,10621 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as analyticsadminserviceModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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 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('v1beta.AnalyticsAdminServiceClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'analyticsadmin.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient(); - 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 = analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient.servicePath; - assert.strictEqual(servicePath, 'analyticsadmin.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'analyticsadmin.googleapis.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'analyticsadmin.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'analyticsadmin.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'analyticsadmin.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 analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'analyticsadmin.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 analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'analyticsadmin.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 analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('has universeDomain', () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has port', () => { - const port = analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient.port; - assert(port); - assert(typeof port === 'number'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient + .servicePath; + assert.strictEqual(servicePath, 'analyticsadmin.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient + .apiEndpoint; + assert.strictEqual(apiEndpoint, 'analyticsadmin.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + universeDomain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'analyticsadmin.example.com'); + }); - it('should create a client with no option', () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient(); - assert(client); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + universe_domain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'analyticsadmin.example.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - fallback: true, - }); - assert(client); + 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 analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'analyticsadmin.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 analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'analyticsadmin.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 analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.analyticsAdminServiceStub, undefined); - await client.initialize(); - assert(client.analyticsAdminServiceStub); - }); + it('has port', () => { + const port = + analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the initialized client', done => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.analyticsAdminServiceStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient(); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.analyticsAdminServiceStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('should create a client with gRPC fallback', () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + fallback: true, }); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - 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 initialize method and supports deferred initialization', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.analyticsAdminServiceStub, undefined); + await client.initialize(); + assert(client.analyticsAdminServiceStub); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - 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('has close method for the initialized client', (done) => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.analyticsAdminServiceStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('getAccount', () => { - it('invokes getAccount without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetAccountRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.Account() - ); - client.innerApiCalls.getAccount = stubSimpleCall(expectedResponse); - const [response] = await client.getAccount(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAccount without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetAccountRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.Account() - ); - client.innerApiCalls.getAccount = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getAccount( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IAccount|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAccount with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetAccountRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getAccount = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getAccount(request), expectedError); - const actualRequest = (client.innerApiCalls.getAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAccount with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetAccountRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getAccount(request), expectedError); - }); - }); - - describe('deleteAccount', () => { - it('invokes deleteAccount without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteAccountRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteAccount = stubSimpleCall(expectedResponse); - const [response] = await client.deleteAccount(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteAccount without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteAccountRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteAccount = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteAccount( - 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.deleteAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteAccount with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteAccountRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteAccount = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteAccount(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteAccount with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteAccountRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteAccountRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteAccount(request), expectedError); - }); - }); - - describe('updateAccount', () => { - it('invokes updateAccount without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateAccountRequest() - ); - request.account ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateAccountRequest', ['account', 'name']); - request.account.name = defaultValue1; - const expectedHeaderRequestParams = `account.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.Account() - ); - client.innerApiCalls.updateAccount = stubSimpleCall(expectedResponse); - const [response] = await client.updateAccount(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateAccount without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateAccountRequest() - ); - request.account ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateAccountRequest', ['account', 'name']); - request.account.name = defaultValue1; - const expectedHeaderRequestParams = `account.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.Account() - ); - client.innerApiCalls.updateAccount = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateAccount( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IAccount|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateAccount with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateAccountRequest() - ); - request.account ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateAccountRequest', ['account', 'name']); - request.account.name = defaultValue1; - const expectedHeaderRequestParams = `account.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateAccount = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateAccount(request), expectedError); - const actualRequest = (client.innerApiCalls.updateAccount as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateAccount as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateAccount with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateAccountRequest() - ); - request.account ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateAccountRequest', ['account', 'name']); - request.account.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateAccount(request), expectedError); - }); - }); - - describe('provisionAccountTicket', () => { - it('invokes provisionAccountTicket without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ProvisionAccountTicketRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ProvisionAccountTicketResponse() - ); - client.innerApiCalls.provisionAccountTicket = stubSimpleCall(expectedResponse); - const [response] = await client.provisionAccountTicket(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes provisionAccountTicket without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ProvisionAccountTicketRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ProvisionAccountTicketResponse() - ); - client.innerApiCalls.provisionAccountTicket = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.provisionAccountTicket( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IProvisionAccountTicketResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); + it('has close method for the non-initialized client', (done) => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.analyticsAdminServiceStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes provisionAccountTicket with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ProvisionAccountTicketRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.provisionAccountTicket = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.provisionAccountTicket(request), expectedError); - }); - - it('invokes provisionAccountTicket with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ProvisionAccountTicketRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.provisionAccountTicket(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + 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('getProperty', () => { - it('invokes getProperty without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetPropertyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetPropertyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.Property() - ); - client.innerApiCalls.getProperty = stubSimpleCall(expectedResponse); - const [response] = await client.getProperty(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getProperty as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getProperty as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getProperty without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetPropertyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetPropertyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.Property() - ); - client.innerApiCalls.getProperty = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getProperty( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IProperty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getProperty as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getProperty as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getProperty with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetPropertyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetPropertyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getProperty = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getProperty(request), expectedError); - const actualRequest = (client.innerApiCalls.getProperty as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getProperty as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getProperty with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetPropertyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetPropertyRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getProperty(request), expectedError); - }); - }); - - describe('createProperty', () => { - it('invokes createProperty without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreatePropertyRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.Property() - ); - client.innerApiCalls.createProperty = stubSimpleCall(expectedResponse); - const [response] = await client.createProperty(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes createProperty without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreatePropertyRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.Property() - ); - client.innerApiCalls.createProperty = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createProperty( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IProperty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + 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('getAccount', () => { + it('invokes getAccount without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetAccountRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.Account(), + ); + client.innerApiCalls.getAccount = stubSimpleCall(expectedResponse); + const [response] = await client.getAccount(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createProperty with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreatePropertyRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.createProperty = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createProperty(request), expectedError); - }); - - it('invokes createProperty with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreatePropertyRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createProperty(request), expectedError); - }); + it('invokes getAccount without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetAccountRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.Account(), + ); + client.innerApiCalls.getAccount = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getAccount( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IAccount | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteProperty', () => { - it('invokes deleteProperty without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeletePropertyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeletePropertyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.Property() - ); - client.innerApiCalls.deleteProperty = stubSimpleCall(expectedResponse); - const [response] = await client.deleteProperty(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteProperty as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteProperty as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteProperty without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeletePropertyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeletePropertyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.Property() - ); - client.innerApiCalls.deleteProperty = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteProperty( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IProperty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteProperty as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteProperty as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteProperty with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeletePropertyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeletePropertyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteProperty = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteProperty(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteProperty as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteProperty as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteProperty with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeletePropertyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeletePropertyRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteProperty(request), expectedError); - }); - }); - - describe('updateProperty', () => { - it('invokes updateProperty without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdatePropertyRequest() - ); - request.property ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdatePropertyRequest', ['property', 'name']); - request.property.name = defaultValue1; - const expectedHeaderRequestParams = `property.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.Property() - ); - client.innerApiCalls.updateProperty = stubSimpleCall(expectedResponse); - const [response] = await client.updateProperty(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateProperty as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateProperty as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateProperty without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdatePropertyRequest() - ); - request.property ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdatePropertyRequest', ['property', 'name']); - request.property.name = defaultValue1; - const expectedHeaderRequestParams = `property.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.Property() - ); - client.innerApiCalls.updateProperty = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateProperty( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IProperty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateProperty as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateProperty as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateProperty with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdatePropertyRequest() - ); - request.property ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdatePropertyRequest', ['property', 'name']); - request.property.name = defaultValue1; - const expectedHeaderRequestParams = `property.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateProperty = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateProperty(request), expectedError); - const actualRequest = (client.innerApiCalls.updateProperty as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateProperty as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateProperty with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdatePropertyRequest() - ); - request.property ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdatePropertyRequest', ['property', 'name']); - request.property.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateProperty(request), expectedError); - }); - }); - - describe('createFirebaseLink', () => { - it('invokes createFirebaseLink without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateFirebaseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateFirebaseLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.FirebaseLink() - ); - client.innerApiCalls.createFirebaseLink = stubSimpleCall(expectedResponse); - const [response] = await client.createFirebaseLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createFirebaseLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createFirebaseLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createFirebaseLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateFirebaseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateFirebaseLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.FirebaseLink() - ); - client.innerApiCalls.createFirebaseLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createFirebaseLink( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IFirebaseLink|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createFirebaseLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createFirebaseLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createFirebaseLink with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateFirebaseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateFirebaseLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createFirebaseLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createFirebaseLink(request), expectedError); - const actualRequest = (client.innerApiCalls.createFirebaseLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createFirebaseLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createFirebaseLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateFirebaseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateFirebaseLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createFirebaseLink(request), expectedError); - }); - }); - - describe('deleteFirebaseLink', () => { - it('invokes deleteFirebaseLink without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteFirebaseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteFirebaseLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteFirebaseLink = stubSimpleCall(expectedResponse); - const [response] = await client.deleteFirebaseLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteFirebaseLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteFirebaseLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteFirebaseLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteFirebaseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteFirebaseLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteFirebaseLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteFirebaseLink( - 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.deleteFirebaseLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteFirebaseLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteFirebaseLink with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteFirebaseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteFirebaseLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteFirebaseLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteFirebaseLink(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteFirebaseLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteFirebaseLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteFirebaseLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteFirebaseLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteFirebaseLinkRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteFirebaseLink(request), expectedError); - }); - }); - - describe('createGoogleAdsLink', () => { - it('invokes createGoogleAdsLink without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GoogleAdsLink() - ); - client.innerApiCalls.createGoogleAdsLink = stubSimpleCall(expectedResponse); - const [response] = await client.createGoogleAdsLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createGoogleAdsLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createGoogleAdsLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createGoogleAdsLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GoogleAdsLink() - ); - client.innerApiCalls.createGoogleAdsLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createGoogleAdsLink( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IGoogleAdsLink|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createGoogleAdsLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createGoogleAdsLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createGoogleAdsLink with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createGoogleAdsLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createGoogleAdsLink(request), expectedError); - const actualRequest = (client.innerApiCalls.createGoogleAdsLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createGoogleAdsLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createGoogleAdsLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createGoogleAdsLink(request), expectedError); - }); - }); - - describe('updateGoogleAdsLink', () => { - it('invokes updateGoogleAdsLink without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest() - ); - request.googleAdsLink ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest', ['googleAdsLink', 'name']); - request.googleAdsLink.name = defaultValue1; - const expectedHeaderRequestParams = `google_ads_link.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GoogleAdsLink() - ); - client.innerApiCalls.updateGoogleAdsLink = stubSimpleCall(expectedResponse); - const [response] = await client.updateGoogleAdsLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateGoogleAdsLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGoogleAdsLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateGoogleAdsLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest() - ); - request.googleAdsLink ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest', ['googleAdsLink', 'name']); - request.googleAdsLink.name = defaultValue1; - const expectedHeaderRequestParams = `google_ads_link.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GoogleAdsLink() - ); - client.innerApiCalls.updateGoogleAdsLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateGoogleAdsLink( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IGoogleAdsLink|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateGoogleAdsLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGoogleAdsLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateGoogleAdsLink with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest() - ); - request.googleAdsLink ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest', ['googleAdsLink', 'name']); - request.googleAdsLink.name = defaultValue1; - const expectedHeaderRequestParams = `google_ads_link.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateGoogleAdsLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateGoogleAdsLink(request), expectedError); - const actualRequest = (client.innerApiCalls.updateGoogleAdsLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateGoogleAdsLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateGoogleAdsLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest() - ); - request.googleAdsLink ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest', ['googleAdsLink', 'name']); - request.googleAdsLink.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateGoogleAdsLink(request), expectedError); - }); - }); - - describe('deleteGoogleAdsLink', () => { - it('invokes deleteGoogleAdsLink without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteGoogleAdsLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteGoogleAdsLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteGoogleAdsLink = stubSimpleCall(expectedResponse); - const [response] = await client.deleteGoogleAdsLink(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteGoogleAdsLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteGoogleAdsLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteGoogleAdsLink without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteGoogleAdsLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteGoogleAdsLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteGoogleAdsLink = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteGoogleAdsLink( - 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.deleteGoogleAdsLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteGoogleAdsLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteGoogleAdsLink with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteGoogleAdsLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteGoogleAdsLinkRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteGoogleAdsLink = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteGoogleAdsLink(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteGoogleAdsLink as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteGoogleAdsLink as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteGoogleAdsLink with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteGoogleAdsLinkRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteGoogleAdsLinkRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteGoogleAdsLink(request), expectedError); - }); - }); - - describe('getDataSharingSettings', () => { - it('invokes getDataSharingSettings without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetDataSharingSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetDataSharingSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DataSharingSettings() - ); - client.innerApiCalls.getDataSharingSettings = stubSimpleCall(expectedResponse); - const [response] = await client.getDataSharingSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDataSharingSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataSharingSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDataSharingSettings without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetDataSharingSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetDataSharingSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DataSharingSettings() - ); - client.innerApiCalls.getDataSharingSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getDataSharingSettings( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IDataSharingSettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDataSharingSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataSharingSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDataSharingSettings with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetDataSharingSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetDataSharingSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getDataSharingSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getDataSharingSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.getDataSharingSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataSharingSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDataSharingSettings with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetDataSharingSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetDataSharingSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getDataSharingSettings(request), expectedError); - }); - }); - - describe('getMeasurementProtocolSecret', () => { - it('invokes getMeasurementProtocolSecret without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetMeasurementProtocolSecretRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret() - ); - client.innerApiCalls.getMeasurementProtocolSecret = stubSimpleCall(expectedResponse); - const [response] = await client.getMeasurementProtocolSecret(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getMeasurementProtocolSecret without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetMeasurementProtocolSecretRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret() - ); - client.innerApiCalls.getMeasurementProtocolSecret = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getMeasurementProtocolSecret( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getMeasurementProtocolSecret with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetMeasurementProtocolSecretRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getMeasurementProtocolSecret = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getMeasurementProtocolSecret(request), expectedError); - const actualRequest = (client.innerApiCalls.getMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getMeasurementProtocolSecret with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetMeasurementProtocolSecretRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getMeasurementProtocolSecret(request), expectedError); - }); - }); - - describe('createMeasurementProtocolSecret', () => { - it('invokes createMeasurementProtocolSecret without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateMeasurementProtocolSecretRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret() - ); - client.innerApiCalls.createMeasurementProtocolSecret = stubSimpleCall(expectedResponse); - const [response] = await client.createMeasurementProtocolSecret(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createMeasurementProtocolSecret without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateMeasurementProtocolSecretRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret() - ); - client.innerApiCalls.createMeasurementProtocolSecret = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createMeasurementProtocolSecret( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createMeasurementProtocolSecret with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateMeasurementProtocolSecretRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createMeasurementProtocolSecret = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createMeasurementProtocolSecret(request), expectedError); - const actualRequest = (client.innerApiCalls.createMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createMeasurementProtocolSecret with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateMeasurementProtocolSecretRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createMeasurementProtocolSecret(request), expectedError); - }); - }); - - describe('deleteMeasurementProtocolSecret', () => { - it('invokes deleteMeasurementProtocolSecret without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteMeasurementProtocolSecretRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteMeasurementProtocolSecret = stubSimpleCall(expectedResponse); - const [response] = await client.deleteMeasurementProtocolSecret(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteMeasurementProtocolSecret without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteMeasurementProtocolSecretRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteMeasurementProtocolSecret = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteMeasurementProtocolSecret( - 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.deleteMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteMeasurementProtocolSecret with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteMeasurementProtocolSecretRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteMeasurementProtocolSecret = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteMeasurementProtocolSecret(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteMeasurementProtocolSecret with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteMeasurementProtocolSecretRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteMeasurementProtocolSecretRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteMeasurementProtocolSecret(request), expectedError); - }); - }); - - describe('updateMeasurementProtocolSecret', () => { - it('invokes updateMeasurementProtocolSecret without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateMeasurementProtocolSecretRequest() - ); - request.measurementProtocolSecret ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateMeasurementProtocolSecretRequest', ['measurementProtocolSecret', 'name']); - request.measurementProtocolSecret.name = defaultValue1; - const expectedHeaderRequestParams = `measurement_protocol_secret.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret() - ); - client.innerApiCalls.updateMeasurementProtocolSecret = stubSimpleCall(expectedResponse); - const [response] = await client.updateMeasurementProtocolSecret(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateMeasurementProtocolSecret without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateMeasurementProtocolSecretRequest() - ); - request.measurementProtocolSecret ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateMeasurementProtocolSecretRequest', ['measurementProtocolSecret', 'name']); - request.measurementProtocolSecret.name = defaultValue1; - const expectedHeaderRequestParams = `measurement_protocol_secret.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret() - ); - client.innerApiCalls.updateMeasurementProtocolSecret = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateMeasurementProtocolSecret( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateMeasurementProtocolSecret with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateMeasurementProtocolSecretRequest() - ); - request.measurementProtocolSecret ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateMeasurementProtocolSecretRequest', ['measurementProtocolSecret', 'name']); - request.measurementProtocolSecret.name = defaultValue1; - const expectedHeaderRequestParams = `measurement_protocol_secret.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateMeasurementProtocolSecret = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateMeasurementProtocolSecret(request), expectedError); - const actualRequest = (client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateMeasurementProtocolSecret with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateMeasurementProtocolSecretRequest() - ); - request.measurementProtocolSecret ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateMeasurementProtocolSecretRequest', ['measurementProtocolSecret', 'name']); - request.measurementProtocolSecret.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateMeasurementProtocolSecret(request), expectedError); - }); - }); - - describe('acknowledgeUserDataCollection', () => { - it('invokes acknowledgeUserDataCollection without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.AcknowledgeUserDataCollectionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.AcknowledgeUserDataCollectionRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.AcknowledgeUserDataCollectionResponse() - ); - client.innerApiCalls.acknowledgeUserDataCollection = stubSimpleCall(expectedResponse); - const [response] = await client.acknowledgeUserDataCollection(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.acknowledgeUserDataCollection as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.acknowledgeUserDataCollection as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes acknowledgeUserDataCollection without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.AcknowledgeUserDataCollectionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.AcknowledgeUserDataCollectionRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.AcknowledgeUserDataCollectionResponse() - ); - client.innerApiCalls.acknowledgeUserDataCollection = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.acknowledgeUserDataCollection( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.acknowledgeUserDataCollection as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.acknowledgeUserDataCollection as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes acknowledgeUserDataCollection with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.AcknowledgeUserDataCollectionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.AcknowledgeUserDataCollectionRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.acknowledgeUserDataCollection = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.acknowledgeUserDataCollection(request), expectedError); - const actualRequest = (client.innerApiCalls.acknowledgeUserDataCollection as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.acknowledgeUserDataCollection as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes acknowledgeUserDataCollection with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.AcknowledgeUserDataCollectionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.AcknowledgeUserDataCollectionRequest', ['property']); - request.property = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.acknowledgeUserDataCollection(request), expectedError); - }); - }); - - describe('createConversionEvent', () => { - it('invokes createConversionEvent without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateConversionEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ConversionEvent() - ); - client.innerApiCalls.createConversionEvent = stubSimpleCall(expectedResponse); - const [response] = await client.createConversionEvent(request); - assert(stub.calledOnce); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createConversionEvent without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateConversionEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ConversionEvent() - ); - client.innerApiCalls.createConversionEvent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createConversionEvent( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IConversionEvent|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert(stub.calledOnce); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createConversionEvent with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateConversionEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createConversionEvent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createConversionEvent(request), expectedError); - assert(stub.calledOnce); - const actualRequest = (client.innerApiCalls.createConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createConversionEvent with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateConversionEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createConversionEvent(request), expectedError); - assert(stub.calledOnce); - }); - }); - - describe('updateConversionEvent', () => { - it('invokes updateConversionEvent without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateConversionEventRequest() - ); - request.conversionEvent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateConversionEventRequest', ['conversionEvent', 'name']); - request.conversionEvent.name = defaultValue1; - const expectedHeaderRequestParams = `conversion_event.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ConversionEvent() - ); - client.innerApiCalls.updateConversionEvent = stubSimpleCall(expectedResponse); - const [response] = await client.updateConversionEvent(request); - assert(stub.calledOnce); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateConversionEvent without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateConversionEventRequest() - ); - request.conversionEvent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateConversionEventRequest', ['conversionEvent', 'name']); - request.conversionEvent.name = defaultValue1; - const expectedHeaderRequestParams = `conversion_event.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ConversionEvent() - ); - client.innerApiCalls.updateConversionEvent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateConversionEvent( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IConversionEvent|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert(stub.calledOnce); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateConversionEvent with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateConversionEventRequest() - ); - request.conversionEvent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateConversionEventRequest', ['conversionEvent', 'name']); - request.conversionEvent.name = defaultValue1; - const expectedHeaderRequestParams = `conversion_event.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateConversionEvent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateConversionEvent(request), expectedError); - assert(stub.calledOnce); - const actualRequest = (client.innerApiCalls.updateConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateConversionEvent with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateConversionEventRequest() - ); - request.conversionEvent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateConversionEventRequest', ['conversionEvent', 'name']); - request.conversionEvent.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateConversionEvent(request), expectedError); - assert(stub.calledOnce); - }); - }); - - describe('getConversionEvent', () => { - it('invokes getConversionEvent without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetConversionEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ConversionEvent() - ); - client.innerApiCalls.getConversionEvent = stubSimpleCall(expectedResponse); - const [response] = await client.getConversionEvent(request); - assert(stub.calledOnce); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getConversionEvent without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetConversionEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ConversionEvent() - ); - client.innerApiCalls.getConversionEvent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getConversionEvent( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IConversionEvent|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert(stub.calledOnce); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getConversionEvent with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetConversionEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getConversionEvent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getConversionEvent(request), expectedError); - assert(stub.calledOnce); - const actualRequest = (client.innerApiCalls.getConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getConversionEvent with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetConversionEventRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getConversionEvent(request), expectedError); - assert(stub.calledOnce); - }); - }); - - describe('deleteConversionEvent', () => { - it('invokes deleteConversionEvent without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteConversionEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteConversionEvent = stubSimpleCall(expectedResponse); - const [response] = await client.deleteConversionEvent(request); - assert(stub.calledOnce); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteConversionEvent without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteConversionEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteConversionEvent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteConversionEvent( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert(stub.calledOnce); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteConversionEvent with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteConversionEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteConversionEvent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteConversionEvent(request), expectedError); - assert(stub.calledOnce); - const actualRequest = (client.innerApiCalls.deleteConversionEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteConversionEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteConversionEvent with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteConversionEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteConversionEventRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteConversionEvent(request), expectedError); - assert(stub.calledOnce); - }); - }); - - describe('createKeyEvent', () => { - it('invokes createKeyEvent without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateKeyEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.KeyEvent() - ); - client.innerApiCalls.createKeyEvent = stubSimpleCall(expectedResponse); - const [response] = await client.createKeyEvent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createKeyEvent without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateKeyEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.KeyEvent() - ); - client.innerApiCalls.createKeyEvent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createKeyEvent( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IKeyEvent|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createKeyEvent with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateKeyEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createKeyEvent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createKeyEvent(request), expectedError); - const actualRequest = (client.innerApiCalls.createKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createKeyEvent with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateKeyEventRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createKeyEvent(request), expectedError); - }); - }); - - describe('updateKeyEvent', () => { - it('invokes updateKeyEvent without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateKeyEventRequest() - ); - request.keyEvent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateKeyEventRequest', ['keyEvent', 'name']); - request.keyEvent.name = defaultValue1; - const expectedHeaderRequestParams = `key_event.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.KeyEvent() - ); - client.innerApiCalls.updateKeyEvent = stubSimpleCall(expectedResponse); - const [response] = await client.updateKeyEvent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateKeyEvent without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateKeyEventRequest() - ); - request.keyEvent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateKeyEventRequest', ['keyEvent', 'name']); - request.keyEvent.name = defaultValue1; - const expectedHeaderRequestParams = `key_event.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.KeyEvent() - ); - client.innerApiCalls.updateKeyEvent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateKeyEvent( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IKeyEvent|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateKeyEvent with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateKeyEventRequest() - ); - request.keyEvent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateKeyEventRequest', ['keyEvent', 'name']); - request.keyEvent.name = defaultValue1; - const expectedHeaderRequestParams = `key_event.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateKeyEvent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateKeyEvent(request), expectedError); - const actualRequest = (client.innerApiCalls.updateKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateKeyEvent with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateKeyEventRequest() - ); - request.keyEvent ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateKeyEventRequest', ['keyEvent', 'name']); - request.keyEvent.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateKeyEvent(request), expectedError); - }); - }); - - describe('getKeyEvent', () => { - it('invokes getKeyEvent without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetKeyEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.KeyEvent() - ); - client.innerApiCalls.getKeyEvent = stubSimpleCall(expectedResponse); - const [response] = await client.getKeyEvent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getKeyEvent without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetKeyEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.KeyEvent() - ); - client.innerApiCalls.getKeyEvent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getKeyEvent( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IKeyEvent|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getKeyEvent with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetKeyEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getKeyEvent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getKeyEvent(request), expectedError); - const actualRequest = (client.innerApiCalls.getKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getKeyEvent with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetKeyEventRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getKeyEvent(request), expectedError); - }); - }); - - describe('deleteKeyEvent', () => { - it('invokes deleteKeyEvent without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteKeyEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteKeyEvent = stubSimpleCall(expectedResponse); - const [response] = await client.deleteKeyEvent(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteKeyEvent without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteKeyEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteKeyEvent = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteKeyEvent( - 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.deleteKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteKeyEvent with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteKeyEventRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteKeyEvent = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteKeyEvent(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteKeyEvent as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteKeyEvent as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteKeyEvent with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteKeyEventRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteKeyEventRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteKeyEvent(request), expectedError); - }); - }); - - describe('createCustomDimension', () => { - it('invokes createCustomDimension without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateCustomDimensionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CustomDimension() - ); - client.innerApiCalls.createCustomDimension = stubSimpleCall(expectedResponse); - const [response] = await client.createCustomDimension(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCustomDimension without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateCustomDimensionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CustomDimension() - ); - client.innerApiCalls.createCustomDimension = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createCustomDimension( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.ICustomDimension|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCustomDimension with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateCustomDimensionRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createCustomDimension = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createCustomDimension(request), expectedError); - const actualRequest = (client.innerApiCalls.createCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCustomDimension with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateCustomDimensionRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createCustomDimension(request), expectedError); - }); - }); - - describe('updateCustomDimension', () => { - it('invokes updateCustomDimension without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateCustomDimensionRequest() - ); - request.customDimension ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateCustomDimensionRequest', ['customDimension', 'name']); - request.customDimension.name = defaultValue1; - const expectedHeaderRequestParams = `custom_dimension.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CustomDimension() - ); - client.innerApiCalls.updateCustomDimension = stubSimpleCall(expectedResponse); - const [response] = await client.updateCustomDimension(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCustomDimension without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateCustomDimensionRequest() - ); - request.customDimension ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateCustomDimensionRequest', ['customDimension', 'name']); - request.customDimension.name = defaultValue1; - const expectedHeaderRequestParams = `custom_dimension.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CustomDimension() - ); - client.innerApiCalls.updateCustomDimension = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateCustomDimension( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.ICustomDimension|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCustomDimension with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateCustomDimensionRequest() - ); - request.customDimension ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateCustomDimensionRequest', ['customDimension', 'name']); - request.customDimension.name = defaultValue1; - const expectedHeaderRequestParams = `custom_dimension.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateCustomDimension = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateCustomDimension(request), expectedError); - const actualRequest = (client.innerApiCalls.updateCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCustomDimension with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateCustomDimensionRequest() - ); - request.customDimension ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateCustomDimensionRequest', ['customDimension', 'name']); - request.customDimension.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateCustomDimension(request), expectedError); - }); - }); - - describe('archiveCustomDimension', () => { - it('invokes archiveCustomDimension without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ArchiveCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ArchiveCustomDimensionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.archiveCustomDimension = stubSimpleCall(expectedResponse); - const [response] = await client.archiveCustomDimension(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.archiveCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.archiveCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes archiveCustomDimension without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ArchiveCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ArchiveCustomDimensionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.archiveCustomDimension = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.archiveCustomDimension( - 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.archiveCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.archiveCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes archiveCustomDimension with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ArchiveCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ArchiveCustomDimensionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.archiveCustomDimension = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.archiveCustomDimension(request), expectedError); - const actualRequest = (client.innerApiCalls.archiveCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.archiveCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes archiveCustomDimension with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ArchiveCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ArchiveCustomDimensionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.archiveCustomDimension(request), expectedError); - }); - }); - - describe('getCustomDimension', () => { - it('invokes getCustomDimension without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetCustomDimensionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CustomDimension() - ); - client.innerApiCalls.getCustomDimension = stubSimpleCall(expectedResponse); - const [response] = await client.getCustomDimension(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCustomDimension without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetCustomDimensionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CustomDimension() - ); - client.innerApiCalls.getCustomDimension = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getCustomDimension( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.ICustomDimension|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCustomDimension with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetCustomDimensionRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getCustomDimension = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getCustomDimension(request), expectedError); - const actualRequest = (client.innerApiCalls.getCustomDimension as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCustomDimension as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCustomDimension with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetCustomDimensionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetCustomDimensionRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getCustomDimension(request), expectedError); - }); - }); - - describe('createCustomMetric', () => { - it('invokes createCustomMetric without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateCustomMetricRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CustomMetric() - ); - client.innerApiCalls.createCustomMetric = stubSimpleCall(expectedResponse); - const [response] = await client.createCustomMetric(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCustomMetric without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateCustomMetricRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CustomMetric() - ); - client.innerApiCalls.createCustomMetric = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createCustomMetric( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.ICustomMetric|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCustomMetric with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateCustomMetricRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createCustomMetric = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createCustomMetric(request), expectedError); - const actualRequest = (client.innerApiCalls.createCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createCustomMetric with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateCustomMetricRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createCustomMetric(request), expectedError); - }); - }); - - describe('updateCustomMetric', () => { - it('invokes updateCustomMetric without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateCustomMetricRequest() - ); - request.customMetric ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateCustomMetricRequest', ['customMetric', 'name']); - request.customMetric.name = defaultValue1; - const expectedHeaderRequestParams = `custom_metric.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CustomMetric() - ); - client.innerApiCalls.updateCustomMetric = stubSimpleCall(expectedResponse); - const [response] = await client.updateCustomMetric(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCustomMetric without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateCustomMetricRequest() - ); - request.customMetric ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateCustomMetricRequest', ['customMetric', 'name']); - request.customMetric.name = defaultValue1; - const expectedHeaderRequestParams = `custom_metric.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CustomMetric() - ); - client.innerApiCalls.updateCustomMetric = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateCustomMetric( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.ICustomMetric|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCustomMetric with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateCustomMetricRequest() - ); - request.customMetric ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateCustomMetricRequest', ['customMetric', 'name']); - request.customMetric.name = defaultValue1; - const expectedHeaderRequestParams = `custom_metric.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateCustomMetric = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateCustomMetric(request), expectedError); - const actualRequest = (client.innerApiCalls.updateCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateCustomMetric with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateCustomMetricRequest() - ); - request.customMetric ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateCustomMetricRequest', ['customMetric', 'name']); - request.customMetric.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateCustomMetric(request), expectedError); - }); - }); - - describe('archiveCustomMetric', () => { - it('invokes archiveCustomMetric without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ArchiveCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ArchiveCustomMetricRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.archiveCustomMetric = stubSimpleCall(expectedResponse); - const [response] = await client.archiveCustomMetric(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.archiveCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.archiveCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes archiveCustomMetric without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ArchiveCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ArchiveCustomMetricRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.archiveCustomMetric = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.archiveCustomMetric( - 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.archiveCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.archiveCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes archiveCustomMetric with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ArchiveCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ArchiveCustomMetricRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.archiveCustomMetric = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.archiveCustomMetric(request), expectedError); - const actualRequest = (client.innerApiCalls.archiveCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.archiveCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes archiveCustomMetric with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ArchiveCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ArchiveCustomMetricRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.archiveCustomMetric(request), expectedError); - }); - }); - - describe('getCustomMetric', () => { - it('invokes getCustomMetric without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetCustomMetricRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CustomMetric() - ); - client.innerApiCalls.getCustomMetric = stubSimpleCall(expectedResponse); - const [response] = await client.getCustomMetric(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCustomMetric without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetCustomMetricRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CustomMetric() - ); - client.innerApiCalls.getCustomMetric = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getCustomMetric( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.ICustomMetric|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCustomMetric with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetCustomMetricRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getCustomMetric = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getCustomMetric(request), expectedError); - const actualRequest = (client.innerApiCalls.getCustomMetric as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getCustomMetric as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getCustomMetric with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetCustomMetricRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetCustomMetricRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getCustomMetric(request), expectedError); - }); - }); - - describe('getDataRetentionSettings', () => { - it('invokes getDataRetentionSettings without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetDataRetentionSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetDataRetentionSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DataRetentionSettings() - ); - client.innerApiCalls.getDataRetentionSettings = stubSimpleCall(expectedResponse); - const [response] = await client.getDataRetentionSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDataRetentionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataRetentionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDataRetentionSettings without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetDataRetentionSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetDataRetentionSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DataRetentionSettings() - ); - client.innerApiCalls.getDataRetentionSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getDataRetentionSettings( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IDataRetentionSettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDataRetentionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataRetentionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDataRetentionSettings with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetDataRetentionSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetDataRetentionSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getDataRetentionSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getDataRetentionSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.getDataRetentionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataRetentionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDataRetentionSettings with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetDataRetentionSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetDataRetentionSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getDataRetentionSettings(request), expectedError); - }); - }); - - describe('updateDataRetentionSettings', () => { - it('invokes updateDataRetentionSettings without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateDataRetentionSettingsRequest() - ); - request.dataRetentionSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateDataRetentionSettingsRequest', ['dataRetentionSettings', 'name']); - request.dataRetentionSettings.name = defaultValue1; - const expectedHeaderRequestParams = `data_retention_settings.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DataRetentionSettings() - ); - client.innerApiCalls.updateDataRetentionSettings = stubSimpleCall(expectedResponse); - const [response] = await client.updateDataRetentionSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDataRetentionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDataRetentionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateDataRetentionSettings without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateDataRetentionSettingsRequest() - ); - request.dataRetentionSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateDataRetentionSettingsRequest', ['dataRetentionSettings', 'name']); - request.dataRetentionSettings.name = defaultValue1; - const expectedHeaderRequestParams = `data_retention_settings.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DataRetentionSettings() - ); - client.innerApiCalls.updateDataRetentionSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateDataRetentionSettings( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IDataRetentionSettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDataRetentionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDataRetentionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateDataRetentionSettings with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateDataRetentionSettingsRequest() - ); - request.dataRetentionSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateDataRetentionSettingsRequest', ['dataRetentionSettings', 'name']); - request.dataRetentionSettings.name = defaultValue1; - const expectedHeaderRequestParams = `data_retention_settings.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateDataRetentionSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateDataRetentionSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.updateDataRetentionSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDataRetentionSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateDataRetentionSettings with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateDataRetentionSettingsRequest() - ); - request.dataRetentionSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateDataRetentionSettingsRequest', ['dataRetentionSettings', 'name']); - request.dataRetentionSettings.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateDataRetentionSettings(request), expectedError); - }); - }); - - describe('createDataStream', () => { - it('invokes createDataStream without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateDataStreamRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DataStream() - ); - client.innerApiCalls.createDataStream = stubSimpleCall(expectedResponse); - const [response] = await client.createDataStream(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createDataStream without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateDataStreamRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DataStream() - ); - client.innerApiCalls.createDataStream = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createDataStream( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IDataStream|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createDataStream with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateDataStreamRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createDataStream = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createDataStream(request), expectedError); - const actualRequest = (client.innerApiCalls.createDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createDataStream with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.CreateDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.CreateDataStreamRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createDataStream(request), expectedError); - }); - }); - - describe('deleteDataStream', () => { - it('invokes deleteDataStream without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteDataStreamRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDataStream = stubSimpleCall(expectedResponse); - const [response] = await client.deleteDataStream(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteDataStream without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteDataStreamRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDataStream = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteDataStream( - 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.deleteDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteDataStream with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteDataStreamRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteDataStream = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteDataStream(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteDataStream with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DeleteDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.DeleteDataStreamRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteDataStream(request), expectedError); - }); - }); - - describe('updateDataStream', () => { - it('invokes updateDataStream without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateDataStreamRequest() - ); - request.dataStream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateDataStreamRequest', ['dataStream', 'name']); - request.dataStream.name = defaultValue1; - const expectedHeaderRequestParams = `data_stream.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DataStream() - ); - client.innerApiCalls.updateDataStream = stubSimpleCall(expectedResponse); - const [response] = await client.updateDataStream(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateDataStream without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateDataStreamRequest() - ); - request.dataStream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateDataStreamRequest', ['dataStream', 'name']); - request.dataStream.name = defaultValue1; - const expectedHeaderRequestParams = `data_stream.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DataStream() - ); - client.innerApiCalls.updateDataStream = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateDataStream( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IDataStream|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateDataStream with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateDataStreamRequest() - ); - request.dataStream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateDataStreamRequest', ['dataStream', 'name']); - request.dataStream.name = defaultValue1; - const expectedHeaderRequestParams = `data_stream.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateDataStream = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateDataStream(request), expectedError); - const actualRequest = (client.innerApiCalls.updateDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes updateDataStream with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.UpdateDataStreamRequest() - ); - request.dataStream ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.UpdateDataStreamRequest', ['dataStream', 'name']); - request.dataStream.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateDataStream(request), expectedError); - }); - }); - - describe('getDataStream', () => { - it('invokes getDataStream without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetDataStreamRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DataStream() - ); - client.innerApiCalls.getDataStream = stubSimpleCall(expectedResponse); - const [response] = await client.getDataStream(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDataStream without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetDataStreamRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.DataStream() - ); - client.innerApiCalls.getDataStream = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getDataStream( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IDataStream|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDataStream with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetDataStreamRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getDataStream = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getDataStream(request), expectedError); - const actualRequest = (client.innerApiCalls.getDataStream as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDataStream as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDataStream with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.GetDataStreamRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.GetDataStreamRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getDataStream(request), expectedError); - }); - }); - - describe('runAccessReport', () => { - it('invokes runAccessReport without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.RunAccessReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.RunAccessReportRequest', ['entity']); - request.entity = defaultValue1; - const expectedHeaderRequestParams = `entity=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.RunAccessReportResponse() - ); - client.innerApiCalls.runAccessReport = stubSimpleCall(expectedResponse); - const [response] = await client.runAccessReport(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.runAccessReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runAccessReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes runAccessReport without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.RunAccessReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.RunAccessReportRequest', ['entity']); - request.entity = defaultValue1; - const expectedHeaderRequestParams = `entity=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.admin.v1beta.RunAccessReportResponse() - ); - client.innerApiCalls.runAccessReport = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.runAccessReport( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IRunAccessReportResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.runAccessReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runAccessReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes runAccessReport with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.RunAccessReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.RunAccessReportRequest', ['entity']); - request.entity = defaultValue1; - const expectedHeaderRequestParams = `entity=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.runAccessReport = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.runAccessReport(request), expectedError); - const actualRequest = (client.innerApiCalls.runAccessReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runAccessReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes runAccessReport with closed client', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.RunAccessReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.RunAccessReportRequest', ['entity']); - request.entity = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.runAccessReport(request), expectedError); - }); - }); - - describe('listAccounts', () => { - it('invokes listAccounts without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListAccountsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.Account()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.Account()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.Account()), - ]; - client.innerApiCalls.listAccounts = stubSimpleCall(expectedResponse); - const [response] = await client.listAccounts(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes listAccounts without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListAccountsRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.Account()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.Account()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.Account()), - ]; - client.innerApiCalls.listAccounts = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listAccounts( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IAccount[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes getAccount with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetAccountRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getAccount = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getAccount(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listAccounts with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListAccountsRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listAccounts = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listAccounts(request), expectedError); - }); - - it('invokes listAccountsStream without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListAccountsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.Account()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.Account()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.Account()), - ]; - client.descriptors.page.listAccounts.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listAccountsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.Account[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.Account) => { - 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.listAccounts.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listAccounts, request)); - }); + it('invokes getAccount with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetAccountRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getAccount(request), expectedError); + }); + }); + + describe('deleteAccount', () => { + it('invokes deleteAccount without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteAccountRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteAccount = stubSimpleCall(expectedResponse); + const [response] = await client.deleteAccount(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listAccountsStream with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListAccountsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listAccounts.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listAccountsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.Account[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.Account) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listAccounts.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listAccounts, request)); - }); + it('invokes deleteAccount without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteAccountRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteAccount = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteAccount( + 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.deleteAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listAccounts without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListAccountsRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.Account()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.Account()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.Account()), - ]; - client.descriptors.page.listAccounts.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1beta.IAccount[] = []; - const iterable = client.listAccountsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes deleteAccount with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteAccountRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteAccount = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteAccount(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteAccount with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteAccountRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteAccountRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteAccount(request), expectedError); + }); + }); + + describe('updateAccount', () => { + it('invokes updateAccount without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateAccountRequest(), + ); + request.account ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateAccountRequest', + ['account', 'name'], + ); + request.account.name = defaultValue1; + const expectedHeaderRequestParams = `account.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.Account(), + ); + client.innerApiCalls.updateAccount = stubSimpleCall(expectedResponse); + const [response] = await client.updateAccount(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateAccount without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateAccountRequest(), + ); + request.account ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateAccountRequest', + ['account', 'name'], + ); + request.account.name = defaultValue1; + const expectedHeaderRequestParams = `account.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.Account(), + ); + client.innerApiCalls.updateAccount = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateAccount( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IAccount | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listAccounts.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listAccounts with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListAccountsRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listAccounts.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listAccountsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1beta.IAccount[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listAccounts.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('invokes updateAccount with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateAccountRequest(), + ); + request.account ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateAccountRequest', + ['account', 'name'], + ); + request.account.name = defaultValue1; + const expectedHeaderRequestParams = `account.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateAccount = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateAccount(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateAccount as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateAccount as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listAccountSummaries', () => { - it('invokes listAccountSummaries without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListAccountSummariesRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.AccountSummary()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.AccountSummary()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.AccountSummary()), - ]; - client.innerApiCalls.listAccountSummaries = stubSimpleCall(expectedResponse); - const [response] = await client.listAccountSummaries(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes listAccountSummaries without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListAccountSummariesRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.AccountSummary()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.AccountSummary()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.AccountSummary()), - ]; - client.innerApiCalls.listAccountSummaries = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listAccountSummaries( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IAccountSummary[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes updateAccount with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateAccountRequest(), + ); + request.account ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateAccountRequest', + ['account', 'name'], + ); + request.account.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateAccount(request), expectedError); + }); + }); + + describe('provisionAccountTicket', () => { + it('invokes provisionAccountTicket without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ProvisionAccountTicketRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ProvisionAccountTicketResponse(), + ); + client.innerApiCalls.provisionAccountTicket = + stubSimpleCall(expectedResponse); + const [response] = await client.provisionAccountTicket(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes listAccountSummaries with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListAccountSummariesRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listAccountSummaries = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listAccountSummaries(request), expectedError); - }); - - it('invokes listAccountSummariesStream without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListAccountSummariesRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.AccountSummary()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.AccountSummary()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.AccountSummary()), - ]; - client.descriptors.page.listAccountSummaries.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listAccountSummariesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.AccountSummary[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.AccountSummary) => { - 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.listAccountSummaries.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listAccountSummaries, request)); - }); + it('invokes provisionAccountTicket without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ProvisionAccountTicketRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ProvisionAccountTicketResponse(), + ); + client.innerApiCalls.provisionAccountTicket = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.provisionAccountTicket( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IProvisionAccountTicketResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes listAccountSummariesStream with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListAccountSummariesRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listAccountSummaries.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listAccountSummariesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.AccountSummary[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.AccountSummary) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listAccountSummaries.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listAccountSummaries, request)); - }); + it('invokes provisionAccountTicket with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ProvisionAccountTicketRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.provisionAccountTicket = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.provisionAccountTicket(request), + expectedError, + ); + }); + + it('invokes provisionAccountTicket with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ProvisionAccountTicketRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.provisionAccountTicket(request), + expectedError, + ); + }); + }); + + describe('getProperty', () => { + it('invokes getProperty without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetPropertyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetPropertyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.Property(), + ); + client.innerApiCalls.getProperty = stubSimpleCall(expectedResponse); + const [response] = await client.getProperty(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getProperty as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getProperty as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getProperty without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetPropertyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetPropertyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.Property(), + ); + client.innerApiCalls.getProperty = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getProperty( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IProperty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getProperty as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getProperty as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getProperty with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetPropertyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetPropertyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getProperty = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getProperty(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getProperty as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getProperty as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getProperty with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetPropertyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetPropertyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getProperty(request), expectedError); + }); + }); + + describe('createProperty', () => { + it('invokes createProperty without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreatePropertyRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.Property(), + ); + client.innerApiCalls.createProperty = stubSimpleCall(expectedResponse); + const [response] = await client.createProperty(request); + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes createProperty without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreatePropertyRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.Property(), + ); + client.innerApiCalls.createProperty = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createProperty( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IProperty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes createProperty with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreatePropertyRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.createProperty = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createProperty(request), expectedError); + }); + + it('invokes createProperty with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreatePropertyRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createProperty(request), expectedError); + }); + }); + + describe('deleteProperty', () => { + it('invokes deleteProperty without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeletePropertyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeletePropertyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.Property(), + ); + client.innerApiCalls.deleteProperty = stubSimpleCall(expectedResponse); + const [response] = await client.deleteProperty(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteProperty as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteProperty as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteProperty without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeletePropertyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeletePropertyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.Property(), + ); + client.innerApiCalls.deleteProperty = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteProperty( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IProperty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteProperty as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteProperty as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteProperty with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeletePropertyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeletePropertyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteProperty = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteProperty(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteProperty as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteProperty as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteProperty with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeletePropertyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeletePropertyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteProperty(request), expectedError); + }); + }); + + describe('updateProperty', () => { + it('invokes updateProperty without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdatePropertyRequest(), + ); + request.property ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdatePropertyRequest', + ['property', 'name'], + ); + request.property.name = defaultValue1; + const expectedHeaderRequestParams = `property.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.Property(), + ); + client.innerApiCalls.updateProperty = stubSimpleCall(expectedResponse); + const [response] = await client.updateProperty(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateProperty as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateProperty as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateProperty without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdatePropertyRequest(), + ); + request.property ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdatePropertyRequest', + ['property', 'name'], + ); + request.property.name = defaultValue1; + const expectedHeaderRequestParams = `property.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.Property(), + ); + client.innerApiCalls.updateProperty = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateProperty( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IProperty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateProperty as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateProperty as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateProperty with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdatePropertyRequest(), + ); + request.property ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdatePropertyRequest', + ['property', 'name'], + ); + request.property.name = defaultValue1; + const expectedHeaderRequestParams = `property.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateProperty = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateProperty(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateProperty as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateProperty as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateProperty with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdatePropertyRequest(), + ); + request.property ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdatePropertyRequest', + ['property', 'name'], + ); + request.property.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateProperty(request), expectedError); + }); + }); + + describe('createFirebaseLink', () => { + it('invokes createFirebaseLink without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateFirebaseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateFirebaseLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.FirebaseLink(), + ); + client.innerApiCalls.createFirebaseLink = + stubSimpleCall(expectedResponse); + const [response] = await client.createFirebaseLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createFirebaseLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createFirebaseLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createFirebaseLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateFirebaseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateFirebaseLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.FirebaseLink(), + ); + client.innerApiCalls.createFirebaseLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createFirebaseLink( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IFirebaseLink | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createFirebaseLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createFirebaseLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createFirebaseLink with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateFirebaseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateFirebaseLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createFirebaseLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createFirebaseLink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createFirebaseLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createFirebaseLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createFirebaseLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateFirebaseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateFirebaseLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createFirebaseLink(request), expectedError); + }); + }); + + describe('deleteFirebaseLink', () => { + it('invokes deleteFirebaseLink without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteFirebaseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteFirebaseLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteFirebaseLink = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteFirebaseLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteFirebaseLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteFirebaseLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteFirebaseLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteFirebaseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteFirebaseLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteFirebaseLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteFirebaseLink( + 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.deleteFirebaseLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteFirebaseLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteFirebaseLink with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteFirebaseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteFirebaseLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteFirebaseLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteFirebaseLink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteFirebaseLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteFirebaseLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteFirebaseLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteFirebaseLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteFirebaseLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteFirebaseLink(request), expectedError); + }); + }); + + describe('createGoogleAdsLink', () => { + it('invokes createGoogleAdsLink without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GoogleAdsLink(), + ); + client.innerApiCalls.createGoogleAdsLink = + stubSimpleCall(expectedResponse); + const [response] = await client.createGoogleAdsLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createGoogleAdsLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createGoogleAdsLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createGoogleAdsLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GoogleAdsLink(), + ); + client.innerApiCalls.createGoogleAdsLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createGoogleAdsLink( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IGoogleAdsLink | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createGoogleAdsLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createGoogleAdsLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createGoogleAdsLink with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createGoogleAdsLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createGoogleAdsLink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createGoogleAdsLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createGoogleAdsLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createGoogleAdsLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createGoogleAdsLink(request), expectedError); + }); + }); + + describe('updateGoogleAdsLink', () => { + it('invokes updateGoogleAdsLink without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest(), + ); + request.googleAdsLink ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest', + ['googleAdsLink', 'name'], + ); + request.googleAdsLink.name = defaultValue1; + const expectedHeaderRequestParams = `google_ads_link.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GoogleAdsLink(), + ); + client.innerApiCalls.updateGoogleAdsLink = + stubSimpleCall(expectedResponse); + const [response] = await client.updateGoogleAdsLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateGoogleAdsLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGoogleAdsLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateGoogleAdsLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest(), + ); + request.googleAdsLink ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest', + ['googleAdsLink', 'name'], + ); + request.googleAdsLink.name = defaultValue1; + const expectedHeaderRequestParams = `google_ads_link.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GoogleAdsLink(), + ); + client.innerApiCalls.updateGoogleAdsLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateGoogleAdsLink( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IGoogleAdsLink | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateGoogleAdsLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGoogleAdsLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateGoogleAdsLink with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest(), + ); + request.googleAdsLink ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest', + ['googleAdsLink', 'name'], + ); + request.googleAdsLink.name = defaultValue1; + const expectedHeaderRequestParams = `google_ads_link.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateGoogleAdsLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateGoogleAdsLink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateGoogleAdsLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateGoogleAdsLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateGoogleAdsLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest(), + ); + request.googleAdsLink ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest', + ['googleAdsLink', 'name'], + ); + request.googleAdsLink.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateGoogleAdsLink(request), expectedError); + }); + }); + + describe('deleteGoogleAdsLink', () => { + it('invokes deleteGoogleAdsLink without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteGoogleAdsLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteGoogleAdsLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteGoogleAdsLink = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteGoogleAdsLink(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteGoogleAdsLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteGoogleAdsLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteGoogleAdsLink without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteGoogleAdsLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteGoogleAdsLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteGoogleAdsLink = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteGoogleAdsLink( + 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.deleteGoogleAdsLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteGoogleAdsLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteGoogleAdsLink with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteGoogleAdsLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteGoogleAdsLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteGoogleAdsLink = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteGoogleAdsLink(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteGoogleAdsLink as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteGoogleAdsLink as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteGoogleAdsLink with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteGoogleAdsLinkRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteGoogleAdsLinkRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteGoogleAdsLink(request), expectedError); + }); + }); + + describe('getDataSharingSettings', () => { + it('invokes getDataSharingSettings without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetDataSharingSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetDataSharingSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataSharingSettings(), + ); + client.innerApiCalls.getDataSharingSettings = + stubSimpleCall(expectedResponse); + const [response] = await client.getDataSharingSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDataSharingSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataSharingSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDataSharingSettings without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetDataSharingSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetDataSharingSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataSharingSettings(), + ); + client.innerApiCalls.getDataSharingSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDataSharingSettings( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IDataSharingSettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDataSharingSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataSharingSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDataSharingSettings with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetDataSharingSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetDataSharingSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDataSharingSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getDataSharingSettings(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getDataSharingSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataSharingSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDataSharingSettings with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetDataSharingSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetDataSharingSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getDataSharingSettings(request), + expectedError, + ); + }); + }); + + describe('getMeasurementProtocolSecret', () => { + it('invokes getMeasurementProtocolSecret without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetMeasurementProtocolSecretRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret(), + ); + client.innerApiCalls.getMeasurementProtocolSecret = + stubSimpleCall(expectedResponse); + const [response] = await client.getMeasurementProtocolSecret(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getMeasurementProtocolSecret without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetMeasurementProtocolSecretRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret(), + ); + client.innerApiCalls.getMeasurementProtocolSecret = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getMeasurementProtocolSecret( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getMeasurementProtocolSecret with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetMeasurementProtocolSecretRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getMeasurementProtocolSecret = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getMeasurementProtocolSecret(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getMeasurementProtocolSecret with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetMeasurementProtocolSecretRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getMeasurementProtocolSecret(request), + expectedError, + ); + }); + }); + + describe('createMeasurementProtocolSecret', () => { + it('invokes createMeasurementProtocolSecret without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateMeasurementProtocolSecretRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret(), + ); + client.innerApiCalls.createMeasurementProtocolSecret = + stubSimpleCall(expectedResponse); + const [response] = await client.createMeasurementProtocolSecret(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createMeasurementProtocolSecret without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateMeasurementProtocolSecretRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret(), + ); + client.innerApiCalls.createMeasurementProtocolSecret = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createMeasurementProtocolSecret( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createMeasurementProtocolSecret with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateMeasurementProtocolSecretRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createMeasurementProtocolSecret = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createMeasurementProtocolSecret(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createMeasurementProtocolSecret with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateMeasurementProtocolSecretRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createMeasurementProtocolSecret(request), + expectedError, + ); + }); + }); + + describe('deleteMeasurementProtocolSecret', () => { + it('invokes deleteMeasurementProtocolSecret without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteMeasurementProtocolSecretRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteMeasurementProtocolSecret = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteMeasurementProtocolSecret(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteMeasurementProtocolSecret without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteMeasurementProtocolSecretRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteMeasurementProtocolSecret = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteMeasurementProtocolSecret( + 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.deleteMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteMeasurementProtocolSecret with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteMeasurementProtocolSecretRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteMeasurementProtocolSecret = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteMeasurementProtocolSecret(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.deleteMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteMeasurementProtocolSecret with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteMeasurementProtocolSecretRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteMeasurementProtocolSecretRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteMeasurementProtocolSecret(request), + expectedError, + ); + }); + }); + + describe('updateMeasurementProtocolSecret', () => { + it('invokes updateMeasurementProtocolSecret without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateMeasurementProtocolSecretRequest(), + ); + request.measurementProtocolSecret ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateMeasurementProtocolSecretRequest', + ['measurementProtocolSecret', 'name'], + ); + request.measurementProtocolSecret.name = defaultValue1; + const expectedHeaderRequestParams = `measurement_protocol_secret.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret(), + ); + client.innerApiCalls.updateMeasurementProtocolSecret = + stubSimpleCall(expectedResponse); + const [response] = await client.updateMeasurementProtocolSecret(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateMeasurementProtocolSecret without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateMeasurementProtocolSecretRequest(), + ); + request.measurementProtocolSecret ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateMeasurementProtocolSecretRequest', + ['measurementProtocolSecret', 'name'], + ); + request.measurementProtocolSecret.name = defaultValue1; + const expectedHeaderRequestParams = `measurement_protocol_secret.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret(), + ); + client.innerApiCalls.updateMeasurementProtocolSecret = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateMeasurementProtocolSecret( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateMeasurementProtocolSecret with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateMeasurementProtocolSecretRequest(), + ); + request.measurementProtocolSecret ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateMeasurementProtocolSecretRequest', + ['measurementProtocolSecret', 'name'], + ); + request.measurementProtocolSecret.name = defaultValue1; + const expectedHeaderRequestParams = `measurement_protocol_secret.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateMeasurementProtocolSecret = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateMeasurementProtocolSecret(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateMeasurementProtocolSecret as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateMeasurementProtocolSecret with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateMeasurementProtocolSecretRequest(), + ); + request.measurementProtocolSecret ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateMeasurementProtocolSecretRequest', + ['measurementProtocolSecret', 'name'], + ); + request.measurementProtocolSecret.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateMeasurementProtocolSecret(request), + expectedError, + ); + }); + }); + + describe('acknowledgeUserDataCollection', () => { + it('invokes acknowledgeUserDataCollection without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.AcknowledgeUserDataCollectionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.AcknowledgeUserDataCollectionRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.AcknowledgeUserDataCollectionResponse(), + ); + client.innerApiCalls.acknowledgeUserDataCollection = + stubSimpleCall(expectedResponse); + const [response] = await client.acknowledgeUserDataCollection(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.acknowledgeUserDataCollection as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.acknowledgeUserDataCollection as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes acknowledgeUserDataCollection without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.AcknowledgeUserDataCollectionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.AcknowledgeUserDataCollectionRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.AcknowledgeUserDataCollectionResponse(), + ); + client.innerApiCalls.acknowledgeUserDataCollection = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.acknowledgeUserDataCollection( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IAcknowledgeUserDataCollectionResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.acknowledgeUserDataCollection as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.acknowledgeUserDataCollection as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes acknowledgeUserDataCollection with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.AcknowledgeUserDataCollectionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.AcknowledgeUserDataCollectionRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.acknowledgeUserDataCollection = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.acknowledgeUserDataCollection(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.acknowledgeUserDataCollection as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.acknowledgeUserDataCollection as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes acknowledgeUserDataCollection with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.AcknowledgeUserDataCollectionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.AcknowledgeUserDataCollectionRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.acknowledgeUserDataCollection(request), + expectedError, + ); + }); + }); + + describe('createConversionEvent', () => { + it('invokes createConversionEvent without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateConversionEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ConversionEvent(), + ); + client.innerApiCalls.createConversionEvent = + stubSimpleCall(expectedResponse); + const [response] = await client.createConversionEvent(request); + assert(stub.calledOnce); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createConversionEvent without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateConversionEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ConversionEvent(), + ); + client.innerApiCalls.createConversionEvent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createConversionEvent( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IConversionEvent | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert(stub.calledOnce); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createConversionEvent with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateConversionEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createConversionEvent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createConversionEvent(request), + expectedError, + ); + assert(stub.calledOnce); + const actualRequest = ( + client.innerApiCalls.createConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createConversionEvent with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateConversionEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createConversionEvent(request), + expectedError, + ); + assert(stub.calledOnce); + }); + }); + + describe('updateConversionEvent', () => { + it('invokes updateConversionEvent without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateConversionEventRequest(), + ); + request.conversionEvent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateConversionEventRequest', + ['conversionEvent', 'name'], + ); + request.conversionEvent.name = defaultValue1; + const expectedHeaderRequestParams = `conversion_event.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ConversionEvent(), + ); + client.innerApiCalls.updateConversionEvent = + stubSimpleCall(expectedResponse); + const [response] = await client.updateConversionEvent(request); + assert(stub.calledOnce); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateConversionEvent without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateConversionEventRequest(), + ); + request.conversionEvent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateConversionEventRequest', + ['conversionEvent', 'name'], + ); + request.conversionEvent.name = defaultValue1; + const expectedHeaderRequestParams = `conversion_event.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ConversionEvent(), + ); + client.innerApiCalls.updateConversionEvent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateConversionEvent( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IConversionEvent | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert(stub.calledOnce); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateConversionEvent with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateConversionEventRequest(), + ); + request.conversionEvent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateConversionEventRequest', + ['conversionEvent', 'name'], + ); + request.conversionEvent.name = defaultValue1; + const expectedHeaderRequestParams = `conversion_event.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateConversionEvent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateConversionEvent(request), + expectedError, + ); + assert(stub.calledOnce); + const actualRequest = ( + client.innerApiCalls.updateConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateConversionEvent with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateConversionEventRequest(), + ); + request.conversionEvent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateConversionEventRequest', + ['conversionEvent', 'name'], + ); + request.conversionEvent.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateConversionEvent(request), + expectedError, + ); + assert(stub.calledOnce); + }); + }); + + describe('getConversionEvent', () => { + it('invokes getConversionEvent without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetConversionEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ConversionEvent(), + ); + client.innerApiCalls.getConversionEvent = + stubSimpleCall(expectedResponse); + const [response] = await client.getConversionEvent(request); + assert(stub.calledOnce); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getConversionEvent without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetConversionEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ConversionEvent(), + ); + client.innerApiCalls.getConversionEvent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getConversionEvent( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IConversionEvent | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert(stub.calledOnce); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getConversionEvent with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetConversionEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getConversionEvent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getConversionEvent(request), expectedError); + assert(stub.calledOnce); + const actualRequest = ( + client.innerApiCalls.getConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getConversionEvent with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetConversionEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getConversionEvent(request), expectedError); + assert(stub.calledOnce); + }); + }); + + describe('deleteConversionEvent', () => { + it('invokes deleteConversionEvent without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteConversionEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteConversionEvent = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteConversionEvent(request); + assert(stub.calledOnce); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteConversionEvent without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteConversionEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteConversionEvent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteConversionEvent( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert(stub.calledOnce); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteConversionEvent with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteConversionEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteConversionEvent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.deleteConversionEvent(request), + expectedError, + ); + assert(stub.calledOnce); + const actualRequest = ( + client.innerApiCalls.deleteConversionEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteConversionEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteConversionEvent with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteConversionEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteConversionEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.deleteConversionEvent(request), + expectedError, + ); + assert(stub.calledOnce); + }); + }); + + describe('createKeyEvent', () => { + it('invokes createKeyEvent without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateKeyEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.KeyEvent(), + ); + client.innerApiCalls.createKeyEvent = stubSimpleCall(expectedResponse); + const [response] = await client.createKeyEvent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createKeyEvent without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateKeyEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.KeyEvent(), + ); + client.innerApiCalls.createKeyEvent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createKeyEvent( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IKeyEvent | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createKeyEvent with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateKeyEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createKeyEvent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createKeyEvent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createKeyEvent with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateKeyEventRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createKeyEvent(request), expectedError); + }); + }); + + describe('updateKeyEvent', () => { + it('invokes updateKeyEvent without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateKeyEventRequest(), + ); + request.keyEvent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateKeyEventRequest', + ['keyEvent', 'name'], + ); + request.keyEvent.name = defaultValue1; + const expectedHeaderRequestParams = `key_event.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.KeyEvent(), + ); + client.innerApiCalls.updateKeyEvent = stubSimpleCall(expectedResponse); + const [response] = await client.updateKeyEvent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateKeyEvent without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateKeyEventRequest(), + ); + request.keyEvent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateKeyEventRequest', + ['keyEvent', 'name'], + ); + request.keyEvent.name = defaultValue1; + const expectedHeaderRequestParams = `key_event.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.KeyEvent(), + ); + client.innerApiCalls.updateKeyEvent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateKeyEvent( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IKeyEvent | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateKeyEvent with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateKeyEventRequest(), + ); + request.keyEvent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateKeyEventRequest', + ['keyEvent', 'name'], + ); + request.keyEvent.name = defaultValue1; + const expectedHeaderRequestParams = `key_event.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateKeyEvent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateKeyEvent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateKeyEvent with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateKeyEventRequest(), + ); + request.keyEvent ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateKeyEventRequest', + ['keyEvent', 'name'], + ); + request.keyEvent.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateKeyEvent(request), expectedError); + }); + }); + + describe('getKeyEvent', () => { + it('invokes getKeyEvent without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetKeyEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.KeyEvent(), + ); + client.innerApiCalls.getKeyEvent = stubSimpleCall(expectedResponse); + const [response] = await client.getKeyEvent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getKeyEvent without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetKeyEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.KeyEvent(), + ); + client.innerApiCalls.getKeyEvent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getKeyEvent( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IKeyEvent | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getKeyEvent with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetKeyEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getKeyEvent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getKeyEvent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getKeyEvent with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetKeyEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getKeyEvent(request), expectedError); + }); + }); + + describe('deleteKeyEvent', () => { + it('invokes deleteKeyEvent without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteKeyEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteKeyEvent = stubSimpleCall(expectedResponse); + const [response] = await client.deleteKeyEvent(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteKeyEvent without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteKeyEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteKeyEvent = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteKeyEvent( + 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.deleteKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteKeyEvent with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteKeyEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteKeyEvent = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteKeyEvent(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteKeyEvent as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteKeyEvent as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteKeyEvent with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteKeyEventRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteKeyEventRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteKeyEvent(request), expectedError); + }); + }); + + describe('createCustomDimension', () => { + it('invokes createCustomDimension without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateCustomDimensionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomDimension(), + ); + client.innerApiCalls.createCustomDimension = + stubSimpleCall(expectedResponse); + const [response] = await client.createCustomDimension(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCustomDimension without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateCustomDimensionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomDimension(), + ); + client.innerApiCalls.createCustomDimension = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createCustomDimension( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.ICustomDimension | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCustomDimension with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateCustomDimensionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createCustomDimension = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createCustomDimension(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCustomDimension with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateCustomDimensionRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createCustomDimension(request), + expectedError, + ); + }); + }); + + describe('updateCustomDimension', () => { + it('invokes updateCustomDimension without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateCustomDimensionRequest(), + ); + request.customDimension ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateCustomDimensionRequest', + ['customDimension', 'name'], + ); + request.customDimension.name = defaultValue1; + const expectedHeaderRequestParams = `custom_dimension.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomDimension(), + ); + client.innerApiCalls.updateCustomDimension = + stubSimpleCall(expectedResponse); + const [response] = await client.updateCustomDimension(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCustomDimension without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateCustomDimensionRequest(), + ); + request.customDimension ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateCustomDimensionRequest', + ['customDimension', 'name'], + ); + request.customDimension.name = defaultValue1; + const expectedHeaderRequestParams = `custom_dimension.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomDimension(), + ); + client.innerApiCalls.updateCustomDimension = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateCustomDimension( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.ICustomDimension | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCustomDimension with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateCustomDimensionRequest(), + ); + request.customDimension ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateCustomDimensionRequest', + ['customDimension', 'name'], + ); + request.customDimension.name = defaultValue1; + const expectedHeaderRequestParams = `custom_dimension.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateCustomDimension = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateCustomDimension(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCustomDimension with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateCustomDimensionRequest(), + ); + request.customDimension ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateCustomDimensionRequest', + ['customDimension', 'name'], + ); + request.customDimension.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateCustomDimension(request), + expectedError, + ); + }); + }); + + describe('archiveCustomDimension', () => { + it('invokes archiveCustomDimension without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ArchiveCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ArchiveCustomDimensionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.archiveCustomDimension = + stubSimpleCall(expectedResponse); + const [response] = await client.archiveCustomDimension(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.archiveCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.archiveCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes archiveCustomDimension without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ArchiveCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ArchiveCustomDimensionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.archiveCustomDimension = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.archiveCustomDimension( + 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.archiveCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.archiveCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes archiveCustomDimension with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ArchiveCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ArchiveCustomDimensionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.archiveCustomDimension = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.archiveCustomDimension(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.archiveCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.archiveCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes archiveCustomDimension with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ArchiveCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ArchiveCustomDimensionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.archiveCustomDimension(request), + expectedError, + ); + }); + }); + + describe('getCustomDimension', () => { + it('invokes getCustomDimension without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetCustomDimensionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomDimension(), + ); + client.innerApiCalls.getCustomDimension = + stubSimpleCall(expectedResponse); + const [response] = await client.getCustomDimension(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCustomDimension without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetCustomDimensionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomDimension(), + ); + client.innerApiCalls.getCustomDimension = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getCustomDimension( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.ICustomDimension | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCustomDimension with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetCustomDimensionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getCustomDimension = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getCustomDimension(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getCustomDimension as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCustomDimension as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCustomDimension with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetCustomDimensionRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetCustomDimensionRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getCustomDimension(request), expectedError); + }); + }); + + describe('createCustomMetric', () => { + it('invokes createCustomMetric without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateCustomMetricRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomMetric(), + ); + client.innerApiCalls.createCustomMetric = + stubSimpleCall(expectedResponse); + const [response] = await client.createCustomMetric(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCustomMetric without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateCustomMetricRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomMetric(), + ); + client.innerApiCalls.createCustomMetric = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createCustomMetric( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.ICustomMetric | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCustomMetric with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateCustomMetricRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createCustomMetric = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createCustomMetric(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createCustomMetric with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateCustomMetricRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createCustomMetric(request), expectedError); + }); + }); + + describe('updateCustomMetric', () => { + it('invokes updateCustomMetric without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateCustomMetricRequest(), + ); + request.customMetric ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateCustomMetricRequest', + ['customMetric', 'name'], + ); + request.customMetric.name = defaultValue1; + const expectedHeaderRequestParams = `custom_metric.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomMetric(), + ); + client.innerApiCalls.updateCustomMetric = + stubSimpleCall(expectedResponse); + const [response] = await client.updateCustomMetric(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCustomMetric without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateCustomMetricRequest(), + ); + request.customMetric ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateCustomMetricRequest', + ['customMetric', 'name'], + ); + request.customMetric.name = defaultValue1; + const expectedHeaderRequestParams = `custom_metric.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomMetric(), + ); + client.innerApiCalls.updateCustomMetric = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateCustomMetric( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.ICustomMetric | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCustomMetric with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateCustomMetricRequest(), + ); + request.customMetric ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateCustomMetricRequest', + ['customMetric', 'name'], + ); + request.customMetric.name = defaultValue1; + const expectedHeaderRequestParams = `custom_metric.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateCustomMetric = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateCustomMetric(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateCustomMetric with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateCustomMetricRequest(), + ); + request.customMetric ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateCustomMetricRequest', + ['customMetric', 'name'], + ); + request.customMetric.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateCustomMetric(request), expectedError); + }); + }); + + describe('archiveCustomMetric', () => { + it('invokes archiveCustomMetric without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ArchiveCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ArchiveCustomMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.archiveCustomMetric = + stubSimpleCall(expectedResponse); + const [response] = await client.archiveCustomMetric(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.archiveCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.archiveCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes archiveCustomMetric without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ArchiveCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ArchiveCustomMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.archiveCustomMetric = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.archiveCustomMetric( + 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.archiveCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.archiveCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes archiveCustomMetric with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ArchiveCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ArchiveCustomMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.archiveCustomMetric = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.archiveCustomMetric(request), expectedError); + const actualRequest = ( + client.innerApiCalls.archiveCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.archiveCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes archiveCustomMetric with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ArchiveCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ArchiveCustomMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.archiveCustomMetric(request), expectedError); + }); + }); + + describe('getCustomMetric', () => { + it('invokes getCustomMetric without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetCustomMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomMetric(), + ); + client.innerApiCalls.getCustomMetric = stubSimpleCall(expectedResponse); + const [response] = await client.getCustomMetric(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCustomMetric without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetCustomMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomMetric(), + ); + client.innerApiCalls.getCustomMetric = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getCustomMetric( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.ICustomMetric | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCustomMetric with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetCustomMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getCustomMetric = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getCustomMetric(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getCustomMetric as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getCustomMetric as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getCustomMetric with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetCustomMetricRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetCustomMetricRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getCustomMetric(request), expectedError); + }); + }); + + describe('getDataRetentionSettings', () => { + it('invokes getDataRetentionSettings without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetDataRetentionSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetDataRetentionSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataRetentionSettings(), + ); + client.innerApiCalls.getDataRetentionSettings = + stubSimpleCall(expectedResponse); + const [response] = await client.getDataRetentionSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDataRetentionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataRetentionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDataRetentionSettings without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetDataRetentionSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetDataRetentionSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataRetentionSettings(), + ); + client.innerApiCalls.getDataRetentionSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDataRetentionSettings( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IDataRetentionSettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDataRetentionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataRetentionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDataRetentionSettings with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetDataRetentionSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetDataRetentionSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDataRetentionSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getDataRetentionSettings(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getDataRetentionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataRetentionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDataRetentionSettings with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetDataRetentionSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetDataRetentionSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getDataRetentionSettings(request), + expectedError, + ); + }); + }); + + describe('updateDataRetentionSettings', () => { + it('invokes updateDataRetentionSettings without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateDataRetentionSettingsRequest(), + ); + request.dataRetentionSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateDataRetentionSettingsRequest', + ['dataRetentionSettings', 'name'], + ); + request.dataRetentionSettings.name = defaultValue1; + const expectedHeaderRequestParams = `data_retention_settings.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataRetentionSettings(), + ); + client.innerApiCalls.updateDataRetentionSettings = + stubSimpleCall(expectedResponse); + const [response] = await client.updateDataRetentionSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDataRetentionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDataRetentionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDataRetentionSettings without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateDataRetentionSettingsRequest(), + ); + request.dataRetentionSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateDataRetentionSettingsRequest', + ['dataRetentionSettings', 'name'], + ); + request.dataRetentionSettings.name = defaultValue1; + const expectedHeaderRequestParams = `data_retention_settings.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataRetentionSettings(), + ); + client.innerApiCalls.updateDataRetentionSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateDataRetentionSettings( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IDataRetentionSettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDataRetentionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDataRetentionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDataRetentionSettings with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateDataRetentionSettingsRequest(), + ); + request.dataRetentionSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateDataRetentionSettingsRequest', + ['dataRetentionSettings', 'name'], + ); + request.dataRetentionSettings.name = defaultValue1; + const expectedHeaderRequestParams = `data_retention_settings.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDataRetentionSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateDataRetentionSettings(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateDataRetentionSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDataRetentionSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDataRetentionSettings with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateDataRetentionSettingsRequest(), + ); + request.dataRetentionSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateDataRetentionSettingsRequest', + ['dataRetentionSettings', 'name'], + ); + request.dataRetentionSettings.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateDataRetentionSettings(request), + expectedError, + ); + }); + }); + + describe('createDataStream', () => { + it('invokes createDataStream without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateDataStreamRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataStream(), + ); + client.innerApiCalls.createDataStream = stubSimpleCall(expectedResponse); + const [response] = await client.createDataStream(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDataStream without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateDataStreamRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataStream(), + ); + client.innerApiCalls.createDataStream = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createDataStream( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IDataStream | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDataStream with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateDataStreamRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createDataStream = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.createDataStream(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDataStream with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.CreateDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.CreateDataStreamRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.createDataStream(request), expectedError); + }); + }); + + describe('deleteDataStream', () => { + it('invokes deleteDataStream without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteDataStreamRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDataStream = stubSimpleCall(expectedResponse); + const [response] = await client.deleteDataStream(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDataStream without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteDataStreamRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty(), + ); + client.innerApiCalls.deleteDataStream = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteDataStream( + 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.deleteDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDataStream with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteDataStreamRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteDataStream = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteDataStream(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDataStream with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DeleteDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.DeleteDataStreamRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.deleteDataStream(request), expectedError); + }); + }); + + describe('updateDataStream', () => { + it('invokes updateDataStream without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateDataStreamRequest(), + ); + request.dataStream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateDataStreamRequest', + ['dataStream', 'name'], + ); + request.dataStream.name = defaultValue1; + const expectedHeaderRequestParams = `data_stream.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataStream(), + ); + client.innerApiCalls.updateDataStream = stubSimpleCall(expectedResponse); + const [response] = await client.updateDataStream(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDataStream without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateDataStreamRequest(), + ); + request.dataStream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateDataStreamRequest', + ['dataStream', 'name'], + ); + request.dataStream.name = defaultValue1; + const expectedHeaderRequestParams = `data_stream.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataStream(), + ); + client.innerApiCalls.updateDataStream = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateDataStream( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IDataStream | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDataStream with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateDataStreamRequest(), + ); + request.dataStream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateDataStreamRequest', + ['dataStream', 'name'], + ); + request.dataStream.name = defaultValue1; + const expectedHeaderRequestParams = `data_stream.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDataStream = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateDataStream(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDataStream with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.UpdateDataStreamRequest(), + ); + request.dataStream ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.UpdateDataStreamRequest', + ['dataStream', 'name'], + ); + request.dataStream.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.updateDataStream(request), expectedError); + }); + }); + + describe('getDataStream', () => { + it('invokes getDataStream without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetDataStreamRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataStream(), + ); + client.innerApiCalls.getDataStream = stubSimpleCall(expectedResponse); + const [response] = await client.getDataStream(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDataStream without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetDataStreamRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataStream(), + ); + client.innerApiCalls.getDataStream = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDataStream( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IDataStream | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDataStream with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetDataStreamRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDataStream = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getDataStream(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getDataStream as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDataStream as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getDataStream with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.GetDataStreamRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.GetDataStreamRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getDataStream(request), expectedError); + }); + }); + + describe('runAccessReport', () => { + it('invokes runAccessReport without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.RunAccessReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.RunAccessReportRequest', + ['entity'], + ); + request.entity = defaultValue1; + const expectedHeaderRequestParams = `entity=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.RunAccessReportResponse(), + ); + client.innerApiCalls.runAccessReport = stubSimpleCall(expectedResponse); + const [response] = await client.runAccessReport(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runAccessReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runAccessReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes runAccessReport without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.RunAccessReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.RunAccessReportRequest', + ['entity'], + ); + request.entity = defaultValue1; + const expectedHeaderRequestParams = `entity=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.admin.v1beta.RunAccessReportResponse(), + ); + client.innerApiCalls.runAccessReport = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.runAccessReport( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IRunAccessReportResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runAccessReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runAccessReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes runAccessReport with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.RunAccessReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.RunAccessReportRequest', + ['entity'], + ); + request.entity = defaultValue1; + const expectedHeaderRequestParams = `entity=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.runAccessReport = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.runAccessReport(request), expectedError); + const actualRequest = ( + client.innerApiCalls.runAccessReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runAccessReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes runAccessReport with closed client', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.RunAccessReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.RunAccessReportRequest', + ['entity'], + ); + request.entity = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.runAccessReport(request), expectedError); + }); + }); + + describe('listAccounts', () => { + it('invokes listAccounts without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListAccountsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Account(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Account(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Account(), + ), + ]; + client.innerApiCalls.listAccounts = stubSimpleCall(expectedResponse); + const [response] = await client.listAccounts(request); + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes listAccounts without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListAccountsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Account(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Account(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Account(), + ), + ]; + client.innerApiCalls.listAccounts = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listAccounts( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IAccount[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes listAccounts with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListAccountsRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listAccounts = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listAccounts(request), expectedError); + }); + + it('invokes listAccountsStream without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListAccountsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Account(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Account(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Account(), + ), + ]; + client.descriptors.page.listAccounts.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listAccountsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.Account[] = []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1beta.Account) => { + 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.listAccounts.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listAccounts, request), + ); + }); + + it('invokes listAccountsStream with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListAccountsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listAccounts.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listAccountsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.Account[] = []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1beta.Account) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listAccounts.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listAccounts, request), + ); + }); + + it('uses async iteration with listAccounts without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListAccountsRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Account(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Account(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Account(), + ), + ]; + client.descriptors.page.listAccounts.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1beta.IAccount[] = []; + const iterable = client.listAccountsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listAccounts.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + + it('uses async iteration with listAccounts with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListAccountsRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listAccounts.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listAccountsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1beta.IAccount[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listAccounts.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('listAccountSummaries', () => { + it('invokes listAccountSummaries without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListAccountSummariesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.AccountSummary(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.AccountSummary(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.AccountSummary(), + ), + ]; + client.innerApiCalls.listAccountSummaries = + stubSimpleCall(expectedResponse); + const [response] = await client.listAccountSummaries(request); + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes listAccountSummaries without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListAccountSummariesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.AccountSummary(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.AccountSummary(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.AccountSummary(), + ), + ]; + client.innerApiCalls.listAccountSummaries = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listAccountSummaries( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1beta.IAccountSummary[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes listAccountSummaries with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListAccountSummariesRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listAccountSummaries = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listAccountSummaries(request), expectedError); + }); + + it('invokes listAccountSummariesStream without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListAccountSummariesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.AccountSummary(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.AccountSummary(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.AccountSummary(), + ), + ]; + client.descriptors.page.listAccountSummaries.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listAccountSummariesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.AccountSummary[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1beta.AccountSummary) => { + 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.listAccountSummaries.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listAccountSummaries, request), + ); + }); + + it('invokes listAccountSummariesStream with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListAccountSummariesRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listAccountSummaries.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listAccountSummariesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.AccountSummary[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1beta.AccountSummary) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listAccountSummaries.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listAccountSummaries, request), + ); + }); + + it('uses async iteration with listAccountSummaries without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListAccountSummariesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.AccountSummary(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.AccountSummary(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.AccountSummary(), + ), + ]; + client.descriptors.page.listAccountSummaries.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1beta.IAccountSummary[] = + []; + const iterable = client.listAccountSummariesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listAccountSummaries.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + + it('uses async iteration with listAccountSummaries with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListAccountSummariesRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listAccountSummaries.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listAccountSummariesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1beta.IAccountSummary[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listAccountSummaries.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('listProperties', () => { + it('invokes listProperties without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListPropertiesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Property(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Property(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Property(), + ), + ]; + client.innerApiCalls.listProperties = stubSimpleCall(expectedResponse); + const [response] = await client.listProperties(request); + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes listProperties without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListPropertiesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Property(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Property(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Property(), + ), + ]; + client.innerApiCalls.listProperties = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listProperties( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IProperty[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); + + it('invokes listProperties with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListPropertiesRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listProperties = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listProperties(request), expectedError); + }); + + it('invokes listPropertiesStream without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListPropertiesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Property(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Property(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Property(), + ), + ]; + client.descriptors.page.listProperties.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listPropertiesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.Property[] = []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1beta.Property) => { + 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.listProperties.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listProperties, request), + ); + }); + + it('invokes listPropertiesStream with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListPropertiesRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listProperties.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listPropertiesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.Property[] = []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1beta.Property) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listProperties.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listProperties, request), + ); + }); + + it('uses async iteration with listProperties without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListPropertiesRequest(), + ); + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Property(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Property(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.Property(), + ), + ]; + client.descriptors.page.listProperties.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1beta.IProperty[] = []; + const iterable = client.listPropertiesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listProperties.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + + it('uses async iteration with listProperties with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListPropertiesRequest(), + ); + const expectedError = new Error('expected'); + client.descriptors.page.listProperties.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listPropertiesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1beta.IProperty[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listProperties.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + }); + }); + + describe('listFirebaseLinks', () => { + it('invokes listFirebaseLinks without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListFirebaseLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListFirebaseLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.FirebaseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.FirebaseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.FirebaseLink(), + ), + ]; + client.innerApiCalls.listFirebaseLinks = stubSimpleCall(expectedResponse); + const [response] = await client.listFirebaseLinks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listFirebaseLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listFirebaseLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listFirebaseLinks without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListFirebaseLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListFirebaseLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.FirebaseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.FirebaseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.FirebaseLink(), + ), + ]; + client.innerApiCalls.listFirebaseLinks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listFirebaseLinks( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1beta.IFirebaseLink[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listFirebaseLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listFirebaseLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listFirebaseLinks with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListFirebaseLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListFirebaseLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listFirebaseLinks = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listFirebaseLinks(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listFirebaseLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listFirebaseLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listFirebaseLinksStream without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListFirebaseLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListFirebaseLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.FirebaseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.FirebaseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.FirebaseLink(), + ), + ]; + client.descriptors.page.listFirebaseLinks.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listFirebaseLinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.FirebaseLink[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1beta.FirebaseLink) => { + 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.listFirebaseLinks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listFirebaseLinks, request), + ); + assert( + (client.descriptors.page.listFirebaseLinks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listFirebaseLinksStream with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListFirebaseLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListFirebaseLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listFirebaseLinks.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listFirebaseLinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.FirebaseLink[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1beta.FirebaseLink) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listFirebaseLinks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listFirebaseLinks, request), + ); + assert( + (client.descriptors.page.listFirebaseLinks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listFirebaseLinks without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListFirebaseLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListFirebaseLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.FirebaseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.FirebaseLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.FirebaseLink(), + ), + ]; + client.descriptors.page.listFirebaseLinks.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1beta.IFirebaseLink[] = + []; + const iterable = client.listFirebaseLinksAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listFirebaseLinks.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listFirebaseLinks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listFirebaseLinks with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListFirebaseLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListFirebaseLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listFirebaseLinks.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listFirebaseLinksAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1beta.IFirebaseLink[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listFirebaseLinks.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listFirebaseLinks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listGoogleAdsLinks', () => { + it('invokes listGoogleAdsLinks without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.GoogleAdsLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.GoogleAdsLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.GoogleAdsLink(), + ), + ]; + client.innerApiCalls.listGoogleAdsLinks = + stubSimpleCall(expectedResponse); + const [response] = await client.listGoogleAdsLinks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listGoogleAdsLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGoogleAdsLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listGoogleAdsLinks without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.GoogleAdsLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.GoogleAdsLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.GoogleAdsLink(), + ), + ]; + client.innerApiCalls.listGoogleAdsLinks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listGoogleAdsLinks( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1beta.IGoogleAdsLink[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listGoogleAdsLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGoogleAdsLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listGoogleAdsLinks with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listGoogleAdsLinks = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listGoogleAdsLinks(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listGoogleAdsLinks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listGoogleAdsLinks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listGoogleAdsLinksStream without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.GoogleAdsLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.GoogleAdsLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.GoogleAdsLink(), + ), + ]; + client.descriptors.page.listGoogleAdsLinks.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listGoogleAdsLinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.GoogleAdsLink[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1beta.GoogleAdsLink) => { + 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.listGoogleAdsLinks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listGoogleAdsLinks, request), + ); + assert( + (client.descriptors.page.listGoogleAdsLinks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listGoogleAdsLinksStream with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listGoogleAdsLinks.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listGoogleAdsLinksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.GoogleAdsLink[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1beta.GoogleAdsLink) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listGoogleAdsLinks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listGoogleAdsLinks, request), + ); + assert( + (client.descriptors.page.listGoogleAdsLinks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listGoogleAdsLinks without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.GoogleAdsLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.GoogleAdsLink(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.GoogleAdsLink(), + ), + ]; + client.descriptors.page.listGoogleAdsLinks.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1beta.IGoogleAdsLink[] = + []; + const iterable = client.listGoogleAdsLinksAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listGoogleAdsLinks.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listGoogleAdsLinks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listGoogleAdsLinks with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listGoogleAdsLinks.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listGoogleAdsLinksAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1beta.IGoogleAdsLink[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listGoogleAdsLinks.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listGoogleAdsLinks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listMeasurementProtocolSecrets', () => { + it('invokes listMeasurementProtocolSecrets without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret(), + ), + ]; + client.innerApiCalls.listMeasurementProtocolSecrets = + stubSimpleCall(expectedResponse); + const [response] = await client.listMeasurementProtocolSecrets(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listMeasurementProtocolSecrets without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret(), + ), + ]; + client.innerApiCalls.listMeasurementProtocolSecrets = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listMeasurementProtocolSecrets( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listMeasurementProtocolSecrets with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listMeasurementProtocolSecrets = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listMeasurementProtocolSecrets(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listMeasurementProtocolSecretsStream without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret(), + ), + ]; + client.descriptors.page.listMeasurementProtocolSecrets.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listMeasurementProtocolSecretsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.MeasurementProtocolSecret[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1beta.MeasurementProtocolSecret, + ) => { + 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.listMeasurementProtocolSecrets + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listMeasurementProtocolSecrets, + request, + ), + ); + assert( + ( + client.descriptors.page.listMeasurementProtocolSecrets + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('invokes listMeasurementProtocolSecretsStream with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listMeasurementProtocolSecrets.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listMeasurementProtocolSecretsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.MeasurementProtocolSecret[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1beta.MeasurementProtocolSecret, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listMeasurementProtocolSecrets + .createStream as SinonStub + ) + .getCall(0) + .calledWith( + client.innerApiCalls.listMeasurementProtocolSecrets, + request, + ), + ); + assert( + ( + client.descriptors.page.listMeasurementProtocolSecrets + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listMeasurementProtocolSecrets without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret(), + ), + ]; + client.descriptors.page.listMeasurementProtocolSecrets.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret[] = + []; + const iterable = client.listMeasurementProtocolSecretsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listMeasurementProtocolSecrets + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listMeasurementProtocolSecrets + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listMeasurementProtocolSecrets with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listMeasurementProtocolSecrets.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listMeasurementProtocolSecretsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listMeasurementProtocolSecrets + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listMeasurementProtocolSecrets + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('searchChangeHistoryEvents', () => { + it('invokes searchChangeHistoryEvents without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest', + ['account'], + ); + request.account = defaultValue1; + const expectedHeaderRequestParams = `account=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ChangeHistoryEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ChangeHistoryEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ChangeHistoryEvent(), + ), + ]; + client.innerApiCalls.searchChangeHistoryEvents = + stubSimpleCall(expectedResponse); + const [response] = await client.searchChangeHistoryEvents(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.searchChangeHistoryEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchChangeHistoryEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listAccountSummaries without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListAccountSummariesRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.AccountSummary()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.AccountSummary()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.AccountSummary()), - ]; - client.descriptors.page.listAccountSummaries.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1beta.IAccountSummary[] = []; - const iterable = client.listAccountSummariesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes searchChangeHistoryEvents without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest', + ['account'], + ); + request.account = defaultValue1; + const expectedHeaderRequestParams = `account=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ChangeHistoryEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ChangeHistoryEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ChangeHistoryEvent(), + ), + ]; + client.innerApiCalls.searchChangeHistoryEvents = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.searchChangeHistoryEvents( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1beta.IChangeHistoryEvent[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listAccountSummaries.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.searchChangeHistoryEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchChangeHistoryEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listAccountSummaries with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListAccountSummariesRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listAccountSummaries.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listAccountSummariesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1beta.IAccountSummary[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listAccountSummaries.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('invokes searchChangeHistoryEvents with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest', + ['account'], + ); + request.account = defaultValue1; + const expectedHeaderRequestParams = `account=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.searchChangeHistoryEvents = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.searchChangeHistoryEvents(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.searchChangeHistoryEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.searchChangeHistoryEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listProperties', () => { - it('invokes listProperties without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListPropertiesRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.Property()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.Property()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.Property()), - ]; - client.innerApiCalls.listProperties = stubSimpleCall(expectedResponse); - const [response] = await client.listProperties(request); - assert.deepStrictEqual(response, expectedResponse); - }); - - it('invokes listProperties without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListPropertiesRequest() - );const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.Property()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.Property()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.Property()), - ]; - client.innerApiCalls.listProperties = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listProperties( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IProperty[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes searchChangeHistoryEventsStream without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest', + ['account'], + ); + request.account = defaultValue1; + const expectedHeaderRequestParams = `account=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ChangeHistoryEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ChangeHistoryEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ChangeHistoryEvent(), + ), + ]; + client.descriptors.page.searchChangeHistoryEvents.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.searchChangeHistoryEventsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.ChangeHistoryEvent[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1beta.ChangeHistoryEvent, + ) => { + 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.searchChangeHistoryEvents + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.searchChangeHistoryEvents, request), + ); + assert( + ( + client.descriptors.page.searchChangeHistoryEvents + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listProperties with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListPropertiesRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listProperties = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listProperties(request), expectedError); - }); - - it('invokes listPropertiesStream without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListPropertiesRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.Property()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.Property()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.Property()), - ]; - client.descriptors.page.listProperties.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listPropertiesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.Property[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.Property) => { - 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.listProperties.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listProperties, request)); - }); + it('invokes searchChangeHistoryEventsStream with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest', + ['account'], + ); + request.account = defaultValue1; + const expectedHeaderRequestParams = `account=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.searchChangeHistoryEvents.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.searchChangeHistoryEventsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.ChangeHistoryEvent[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.admin.v1beta.ChangeHistoryEvent, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.searchChangeHistoryEvents + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.searchChangeHistoryEvents, request), + ); + assert( + ( + client.descriptors.page.searchChangeHistoryEvents + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('invokes listPropertiesStream with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListPropertiesRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listProperties.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listPropertiesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.Property[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.Property) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listProperties.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listProperties, request)); - }); + it('uses async iteration with searchChangeHistoryEvents without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest', + ['account'], + ); + request.account = defaultValue1; + const expectedHeaderRequestParams = `account=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ChangeHistoryEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ChangeHistoryEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ChangeHistoryEvent(), + ), + ]; + client.descriptors.page.searchChangeHistoryEvents.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1beta.IChangeHistoryEvent[] = + []; + const iterable = client.searchChangeHistoryEventsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.searchChangeHistoryEvents + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.searchChangeHistoryEvents + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); - it('uses async iteration with listProperties without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListPropertiesRequest() - ); - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.Property()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.Property()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.Property()), - ]; - client.descriptors.page.listProperties.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1beta.IProperty[] = []; - const iterable = client.listPropertiesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('uses async iteration with searchChangeHistoryEvents with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest', + ['account'], + ); + request.account = defaultValue1; + const expectedHeaderRequestParams = `account=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.searchChangeHistoryEvents.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.searchChangeHistoryEventsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1beta.IChangeHistoryEvent[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.searchChangeHistoryEvents + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.searchChangeHistoryEvents + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listConversionEvents', () => { + it('invokes listConversionEvents without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListConversionEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListConversionEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ConversionEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ConversionEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ConversionEvent(), + ), + ]; + client.innerApiCalls.listConversionEvents = + stubSimpleCall(expectedResponse); + const [response] = await client.listConversionEvents(request); + assert(stub.calledOnce); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listConversionEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listConversionEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listConversionEvents without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListConversionEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListConversionEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ConversionEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ConversionEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ConversionEvent(), + ), + ]; + client.innerApiCalls.listConversionEvents = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listConversionEvents( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1beta.IConversionEvent[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listProperties.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + }, + ); + }); + const response = await promise; + assert(stub.calledOnce); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listConversionEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listConversionEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listProperties with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListPropertiesRequest() - ); - const expectedError = new Error('expected'); - client.descriptors.page.listProperties.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listPropertiesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1beta.IProperty[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listProperties.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + it('invokes listConversionEvents with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListConversionEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListConversionEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listConversionEvents = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listConversionEvents(request), expectedError); + assert(stub.calledOnce); + const actualRequest = ( + client.innerApiCalls.listConversionEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listConversionEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listFirebaseLinks', () => { - it('invokes listFirebaseLinks without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListFirebaseLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListFirebaseLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.FirebaseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.FirebaseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.FirebaseLink()), - ]; - client.innerApiCalls.listFirebaseLinks = stubSimpleCall(expectedResponse); - const [response] = await client.listFirebaseLinks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listFirebaseLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listFirebaseLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listFirebaseLinks without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListFirebaseLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListFirebaseLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.FirebaseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.FirebaseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.FirebaseLink()), - ]; - client.innerApiCalls.listFirebaseLinks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listFirebaseLinks( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IFirebaseLink[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listFirebaseLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listFirebaseLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listFirebaseLinks with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListFirebaseLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListFirebaseLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listFirebaseLinks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listFirebaseLinks(request), expectedError); - const actualRequest = (client.innerApiCalls.listFirebaseLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listFirebaseLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listFirebaseLinksStream without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListFirebaseLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListFirebaseLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.FirebaseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.FirebaseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.FirebaseLink()), - ]; - client.descriptors.page.listFirebaseLinks.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listFirebaseLinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.FirebaseLink[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.FirebaseLink) => { - 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.listFirebaseLinks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listFirebaseLinks, request)); - assert( - (client.descriptors.page.listFirebaseLinks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('invokes listFirebaseLinksStream with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListFirebaseLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListFirebaseLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listFirebaseLinks.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listFirebaseLinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.FirebaseLink[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.FirebaseLink) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listFirebaseLinks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listFirebaseLinks, request)); - assert( - (client.descriptors.page.listFirebaseLinks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listFirebaseLinks without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListFirebaseLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListFirebaseLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.FirebaseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.FirebaseLink()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.FirebaseLink()), - ]; - client.descriptors.page.listFirebaseLinks.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1beta.IFirebaseLink[] = []; - const iterable = client.listFirebaseLinksAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listFirebaseLinks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listFirebaseLinks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listFirebaseLinks with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListFirebaseLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListFirebaseLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listFirebaseLinks.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listFirebaseLinksAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1beta.IFirebaseLink[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listFirebaseLinks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listFirebaseLinks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - }); - - describe('listGoogleAdsLinks', () => { - it('invokes listGoogleAdsLinks without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.GoogleAdsLink()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.GoogleAdsLink()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.GoogleAdsLink()), - ]; - client.innerApiCalls.listGoogleAdsLinks = stubSimpleCall(expectedResponse); - const [response] = await client.listGoogleAdsLinks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listGoogleAdsLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGoogleAdsLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listGoogleAdsLinks without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.GoogleAdsLink()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.GoogleAdsLink()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.GoogleAdsLink()), - ]; - client.innerApiCalls.listGoogleAdsLinks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listGoogleAdsLinks( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IGoogleAdsLink[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listGoogleAdsLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGoogleAdsLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listGoogleAdsLinks with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listGoogleAdsLinks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listGoogleAdsLinks(request), expectedError); - const actualRequest = (client.innerApiCalls.listGoogleAdsLinks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listGoogleAdsLinks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listGoogleAdsLinksStream without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.GoogleAdsLink()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.GoogleAdsLink()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.GoogleAdsLink()), - ]; - client.descriptors.page.listGoogleAdsLinks.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listGoogleAdsLinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.GoogleAdsLink[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.GoogleAdsLink) => { - 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.listGoogleAdsLinks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listGoogleAdsLinks, request)); - assert( - (client.descriptors.page.listGoogleAdsLinks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('invokes listGoogleAdsLinksStream with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listGoogleAdsLinks.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listGoogleAdsLinksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.GoogleAdsLink[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.GoogleAdsLink) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listGoogleAdsLinks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listGoogleAdsLinks, request)); - assert( - (client.descriptors.page.listGoogleAdsLinks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listGoogleAdsLinks without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.GoogleAdsLink()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.GoogleAdsLink()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.GoogleAdsLink()), - ]; - client.descriptors.page.listGoogleAdsLinks.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1beta.IGoogleAdsLink[] = []; - const iterable = client.listGoogleAdsLinksAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listGoogleAdsLinks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listGoogleAdsLinks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listGoogleAdsLinks with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListGoogleAdsLinksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listGoogleAdsLinks.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listGoogleAdsLinksAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1beta.IGoogleAdsLink[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listGoogleAdsLinks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listGoogleAdsLinks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - }); - - describe('listMeasurementProtocolSecrets', () => { - it('invokes listMeasurementProtocolSecrets without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret()), - ]; - client.innerApiCalls.listMeasurementProtocolSecrets = stubSimpleCall(expectedResponse); - const [response] = await client.listMeasurementProtocolSecrets(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listMeasurementProtocolSecrets without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret()), - ]; - client.innerApiCalls.listMeasurementProtocolSecrets = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listMeasurementProtocolSecrets( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listMeasurementProtocolSecrets with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listMeasurementProtocolSecrets = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listMeasurementProtocolSecrets(request), expectedError); - const actualRequest = (client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listMeasurementProtocolSecrets as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listMeasurementProtocolSecretsStream without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret()), - ]; - client.descriptors.page.listMeasurementProtocolSecrets.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listMeasurementProtocolSecretsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.MeasurementProtocolSecret[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.MeasurementProtocolSecret) => { - 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.listMeasurementProtocolSecrets.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listMeasurementProtocolSecrets, request)); - assert( - (client.descriptors.page.listMeasurementProtocolSecrets.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('invokes listMeasurementProtocolSecretsStream with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listMeasurementProtocolSecrets.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listMeasurementProtocolSecretsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.MeasurementProtocolSecret[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.MeasurementProtocolSecret) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listMeasurementProtocolSecrets.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listMeasurementProtocolSecrets, request)); - assert( - (client.descriptors.page.listMeasurementProtocolSecrets.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listMeasurementProtocolSecrets without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.MeasurementProtocolSecret()), - ]; - client.descriptors.page.listMeasurementProtocolSecrets.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret[] = []; - const iterable = client.listMeasurementProtocolSecretsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listMeasurementProtocolSecrets.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listMeasurementProtocolSecrets.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listMeasurementProtocolSecrets with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListMeasurementProtocolSecretsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listMeasurementProtocolSecrets.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listMeasurementProtocolSecretsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1beta.IMeasurementProtocolSecret[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listMeasurementProtocolSecrets.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listMeasurementProtocolSecrets.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - }); - - describe('searchChangeHistoryEvents', () => { - it('invokes searchChangeHistoryEvents without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest', ['account']); - request.account = defaultValue1; - const expectedHeaderRequestParams = `account=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.ChangeHistoryEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.ChangeHistoryEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.ChangeHistoryEvent()), - ]; - client.innerApiCalls.searchChangeHistoryEvents = stubSimpleCall(expectedResponse); - const [response] = await client.searchChangeHistoryEvents(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.searchChangeHistoryEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchChangeHistoryEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes searchChangeHistoryEvents without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest', ['account']); - request.account = defaultValue1; - const expectedHeaderRequestParams = `account=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.ChangeHistoryEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.ChangeHistoryEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.ChangeHistoryEvent()), - ]; - client.innerApiCalls.searchChangeHistoryEvents = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.searchChangeHistoryEvents( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IChangeHistoryEvent[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.searchChangeHistoryEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchChangeHistoryEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes searchChangeHistoryEvents with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest', ['account']); - request.account = defaultValue1; - const expectedHeaderRequestParams = `account=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.searchChangeHistoryEvents = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.searchChangeHistoryEvents(request), expectedError); - const actualRequest = (client.innerApiCalls.searchChangeHistoryEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.searchChangeHistoryEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes searchChangeHistoryEventsStream without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest', ['account']); - request.account = defaultValue1; - const expectedHeaderRequestParams = `account=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.ChangeHistoryEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.ChangeHistoryEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.ChangeHistoryEvent()), - ]; - client.descriptors.page.searchChangeHistoryEvents.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.searchChangeHistoryEventsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.ChangeHistoryEvent[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.ChangeHistoryEvent) => { - 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.searchChangeHistoryEvents.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.searchChangeHistoryEvents, request)); - assert( - (client.descriptors.page.searchChangeHistoryEvents.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('invokes searchChangeHistoryEventsStream with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest', ['account']); - request.account = defaultValue1; - const expectedHeaderRequestParams = `account=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.searchChangeHistoryEvents.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.searchChangeHistoryEventsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.ChangeHistoryEvent[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.ChangeHistoryEvent) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.searchChangeHistoryEvents.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.searchChangeHistoryEvents, request)); - assert( - (client.descriptors.page.searchChangeHistoryEvents.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with searchChangeHistoryEvents without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest', ['account']); - request.account = defaultValue1; - const expectedHeaderRequestParams = `account=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.ChangeHistoryEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.ChangeHistoryEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.ChangeHistoryEvent()), - ]; - client.descriptors.page.searchChangeHistoryEvents.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1beta.IChangeHistoryEvent[] = []; - const iterable = client.searchChangeHistoryEventsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.searchChangeHistoryEvents.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.searchChangeHistoryEvents.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with searchChangeHistoryEvents with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.SearchChangeHistoryEventsRequest', ['account']); - request.account = defaultValue1; - const expectedHeaderRequestParams = `account=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.searchChangeHistoryEvents.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.searchChangeHistoryEventsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1beta.IChangeHistoryEvent[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.searchChangeHistoryEvents.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.searchChangeHistoryEvents.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - }); - - describe('listConversionEvents', () => { - it('invokes listConversionEvents without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListConversionEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListConversionEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.ConversionEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.ConversionEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.ConversionEvent()), - ]; - client.innerApiCalls.listConversionEvents = stubSimpleCall(expectedResponse); - const [response] = await client.listConversionEvents(request); - assert(stub.calledOnce); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listConversionEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listConversionEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listConversionEvents without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListConversionEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListConversionEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.ConversionEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.ConversionEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.ConversionEvent()), - ]; - client.innerApiCalls.listConversionEvents = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listConversionEvents( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IConversionEvent[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert(stub.calledOnce); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listConversionEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listConversionEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listConversionEvents with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListConversionEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListConversionEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listConversionEvents = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listConversionEvents(request), expectedError); - assert(stub.calledOnce); - const actualRequest = (client.innerApiCalls.listConversionEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listConversionEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listConversionEventsStream without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListConversionEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListConversionEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.ConversionEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.ConversionEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.ConversionEvent()), - ]; - client.descriptors.page.listConversionEvents.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listConversionEventsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.ConversionEvent[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.ConversionEvent) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert(stub.calledOnce); - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listConversionEvents.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listConversionEvents, request)); - assert( - (client.descriptors.page.listConversionEvents.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('invokes listConversionEventsStream with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListConversionEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListConversionEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listConversionEvents.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listConversionEventsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.ConversionEvent[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.ConversionEvent) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert(stub.calledOnce); - assert((client.descriptors.page.listConversionEvents.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listConversionEvents, request)); - assert( - (client.descriptors.page.listConversionEvents.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listConversionEvents without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListConversionEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListConversionEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.ConversionEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.ConversionEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.ConversionEvent()), - ]; - client.descriptors.page.listConversionEvents.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1beta.IConversionEvent[] = []; - const iterable = client.listConversionEventsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert(stub.calledOnce); - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listConversionEvents.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listConversionEvents.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listConversionEvents with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const stub = sinon.stub(client, 'warn'); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListConversionEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListConversionEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listConversionEvents.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listConversionEventsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1beta.IConversionEvent[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert(stub.calledOnce); - assert.deepStrictEqual( - (client.descriptors.page.listConversionEvents.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listConversionEvents.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - }); - - describe('listKeyEvents', () => { - it('invokes listKeyEvents without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListKeyEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListKeyEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.KeyEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.KeyEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.KeyEvent()), - ]; - client.innerApiCalls.listKeyEvents = stubSimpleCall(expectedResponse); - const [response] = await client.listKeyEvents(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listKeyEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listKeyEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listKeyEvents without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListKeyEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListKeyEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.KeyEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.KeyEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.KeyEvent()), - ]; - client.innerApiCalls.listKeyEvents = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listKeyEvents( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IKeyEvent[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listKeyEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listKeyEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listKeyEvents with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListKeyEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListKeyEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listKeyEvents = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listKeyEvents(request), expectedError); - const actualRequest = (client.innerApiCalls.listKeyEvents as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listKeyEvents as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listKeyEventsStream without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListKeyEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListKeyEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.KeyEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.KeyEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.KeyEvent()), - ]; - client.descriptors.page.listKeyEvents.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listKeyEventsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.KeyEvent[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.KeyEvent) => { - 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.listKeyEvents.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listKeyEvents, request)); - assert( - (client.descriptors.page.listKeyEvents.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('invokes listKeyEventsStream with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListKeyEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListKeyEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listKeyEvents.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listKeyEventsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.KeyEvent[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.KeyEvent) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listKeyEvents.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listKeyEvents, request)); - assert( - (client.descriptors.page.listKeyEvents.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listKeyEvents without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListKeyEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListKeyEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.KeyEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.KeyEvent()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.KeyEvent()), - ]; - client.descriptors.page.listKeyEvents.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1beta.IKeyEvent[] = []; - const iterable = client.listKeyEventsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listKeyEvents.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listKeyEvents.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listKeyEvents with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListKeyEventsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListKeyEventsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listKeyEvents.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listKeyEventsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1beta.IKeyEvent[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listKeyEvents.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listKeyEvents.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - }); - - describe('listCustomDimensions', () => { - it('invokes listCustomDimensions without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListCustomDimensionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListCustomDimensionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomDimension()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomDimension()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomDimension()), - ]; - client.innerApiCalls.listCustomDimensions = stubSimpleCall(expectedResponse); - const [response] = await client.listCustomDimensions(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCustomDimensions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCustomDimensions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCustomDimensions without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListCustomDimensionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListCustomDimensionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomDimension()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomDimension()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomDimension()), - ]; - client.innerApiCalls.listCustomDimensions = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listCustomDimensions( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.ICustomDimension[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCustomDimensions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCustomDimensions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCustomDimensions with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListCustomDimensionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListCustomDimensionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listCustomDimensions = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listCustomDimensions(request), expectedError); - const actualRequest = (client.innerApiCalls.listCustomDimensions as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCustomDimensions as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCustomDimensionsStream without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListCustomDimensionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListCustomDimensionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomDimension()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomDimension()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomDimension()), - ]; - client.descriptors.page.listCustomDimensions.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listCustomDimensionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.CustomDimension[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.CustomDimension) => { - 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.listCustomDimensions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCustomDimensions, request)); - assert( - (client.descriptors.page.listCustomDimensions.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('invokes listCustomDimensionsStream with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListCustomDimensionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListCustomDimensionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCustomDimensions.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listCustomDimensionsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.CustomDimension[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.CustomDimension) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listCustomDimensions.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCustomDimensions, request)); - assert( - (client.descriptors.page.listCustomDimensions.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listCustomDimensions without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListCustomDimensionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListCustomDimensionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomDimension()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomDimension()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomDimension()), - ]; - client.descriptors.page.listCustomDimensions.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1beta.ICustomDimension[] = []; - const iterable = client.listCustomDimensionsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listCustomDimensions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCustomDimensions.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listCustomDimensions with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListCustomDimensionsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListCustomDimensionsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCustomDimensions.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listCustomDimensionsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1beta.ICustomDimension[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listCustomDimensions.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCustomDimensions.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - }); - - describe('listCustomMetrics', () => { - it('invokes listCustomMetrics without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListCustomMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListCustomMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomMetric()), - ]; - client.innerApiCalls.listCustomMetrics = stubSimpleCall(expectedResponse); - const [response] = await client.listCustomMetrics(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCustomMetrics as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCustomMetrics as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCustomMetrics without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListCustomMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListCustomMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomMetric()), - ]; - client.innerApiCalls.listCustomMetrics = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listCustomMetrics( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.ICustomMetric[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCustomMetrics as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCustomMetrics as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCustomMetrics with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListCustomMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListCustomMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listCustomMetrics = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listCustomMetrics(request), expectedError); - const actualRequest = (client.innerApiCalls.listCustomMetrics as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCustomMetrics as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCustomMetricsStream without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListCustomMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListCustomMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomMetric()), - ]; - client.descriptors.page.listCustomMetrics.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listCustomMetricsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.CustomMetric[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.CustomMetric) => { - 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.listCustomMetrics.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCustomMetrics, request)); - assert( - (client.descriptors.page.listCustomMetrics.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('invokes listCustomMetricsStream with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListCustomMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListCustomMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCustomMetrics.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listCustomMetricsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.CustomMetric[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.CustomMetric) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listCustomMetrics.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCustomMetrics, request)); - assert( - (client.descriptors.page.listCustomMetrics.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listCustomMetrics without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListCustomMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListCustomMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomMetric()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.CustomMetric()), - ]; - client.descriptors.page.listCustomMetrics.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1beta.ICustomMetric[] = []; - const iterable = client.listCustomMetricsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listCustomMetrics.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCustomMetrics.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listCustomMetrics with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListCustomMetricsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListCustomMetricsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCustomMetrics.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listCustomMetricsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1beta.ICustomMetric[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listCustomMetrics.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCustomMetrics.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - }); - - describe('listDataStreams', () => { - it('invokes listDataStreams without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListDataStreamsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListDataStreamsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.DataStream()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.DataStream()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.DataStream()), - ]; - client.innerApiCalls.listDataStreams = stubSimpleCall(expectedResponse); - const [response] = await client.listDataStreams(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDataStreams as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDataStreams as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listDataStreams without error using callback', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListDataStreamsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListDataStreamsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.DataStream()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.DataStream()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.DataStream()), - ]; - client.innerApiCalls.listDataStreams = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listDataStreams( - request, - (err?: Error|null, result?: protos.google.analytics.admin.v1beta.IDataStream[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDataStreams as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDataStreams as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listDataStreams with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListDataStreamsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListDataStreamsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listDataStreams = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listDataStreams(request), expectedError); - const actualRequest = (client.innerApiCalls.listDataStreams as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDataStreams as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listDataStreamsStream without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListDataStreamsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListDataStreamsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.DataStream()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.DataStream()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.DataStream()), - ]; - client.descriptors.page.listDataStreams.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listDataStreamsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.DataStream[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.DataStream) => { - 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.listDataStreams.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listDataStreams, request)); - assert( - (client.descriptors.page.listDataStreams.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('invokes listDataStreamsStream with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListDataStreamsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListDataStreamsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listDataStreams.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listDataStreamsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.admin.v1beta.DataStream[] = []; - stream.on('data', (response: protos.google.analytics.admin.v1beta.DataStream) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listDataStreams.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listDataStreams, request)); - assert( - (client.descriptors.page.listDataStreams.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listDataStreams without error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListDataStreamsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListDataStreamsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.admin.v1beta.DataStream()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.DataStream()), - generateSampleMessage(new protos.google.analytics.admin.v1beta.DataStream()), - ]; - client.descriptors.page.listDataStreams.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.admin.v1beta.IDataStream[] = []; - const iterable = client.listDataStreamsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listConversionEventsStream without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListConversionEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListConversionEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ConversionEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ConversionEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ConversionEvent(), + ), + ]; + client.descriptors.page.listConversionEvents.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listConversionEventsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.ConversionEvent[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1beta.ConversionEvent) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert(stub.calledOnce); + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listConversionEvents.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listConversionEvents, request), + ); + assert( + (client.descriptors.page.listConversionEvents.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listConversionEventsStream with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListConversionEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListConversionEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listConversionEvents.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listConversionEventsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.ConversionEvent[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1beta.ConversionEvent) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert(stub.calledOnce); + assert( + (client.descriptors.page.listConversionEvents.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listConversionEvents, request), + ); + assert( + (client.descriptors.page.listConversionEvents.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listConversionEvents without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListConversionEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListConversionEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ConversionEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ConversionEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.ConversionEvent(), + ), + ]; + client.descriptors.page.listConversionEvents.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1beta.IConversionEvent[] = + []; + const iterable = client.listConversionEventsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert(stub.calledOnce); + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listConversionEvents.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listConversionEvents.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listConversionEvents with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + const stub = sinon.stub(client, 'warn'); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListConversionEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListConversionEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listConversionEvents.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listConversionEventsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1beta.IConversionEvent[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert(stub.calledOnce); + assert.deepStrictEqual( + ( + client.descriptors.page.listConversionEvents.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listConversionEvents.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listKeyEvents', () => { + it('invokes listKeyEvents without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListKeyEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListKeyEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.KeyEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.KeyEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.KeyEvent(), + ), + ]; + client.innerApiCalls.listKeyEvents = stubSimpleCall(expectedResponse); + const [response] = await client.listKeyEvents(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listKeyEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listKeyEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listKeyEvents without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListKeyEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListKeyEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.KeyEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.KeyEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.KeyEvent(), + ), + ]; + client.innerApiCalls.listKeyEvents = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listKeyEvents( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IKeyEvent[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listDataStreams.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listDataStreams.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listDataStreams with error', async () => { - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.admin.v1beta.ListDataStreamsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.admin.v1beta.ListDataStreamsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listDataStreams.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listDataStreamsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.admin.v1beta.IDataStream[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listDataStreams.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listDataStreams.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - }); - - describe('Path templates', () => { - - describe('account', async () => { - const fakePath = "/rendered/path/account"; - const expectedParameters = { - account: "accountValue", - }; - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.accountPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.accountPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('accountPath', () => { - const result = client.accountPath("accountValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.accountPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listKeyEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listKeyEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchAccountFromAccountName', () => { - const result = client.matchAccountFromAccountName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.accountPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes listKeyEvents with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListKeyEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListKeyEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listKeyEvents = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listKeyEvents(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listKeyEvents as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listKeyEvents as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('accountSummary', async () => { - const fakePath = "/rendered/path/accountSummary"; - const expectedParameters = { - account_summary: "accountSummaryValue", - }; - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.accountSummaryPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.accountSummaryPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('accountSummaryPath', () => { - const result = client.accountSummaryPath("accountSummaryValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.accountSummaryPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes listKeyEventsStream without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListKeyEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListKeyEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.KeyEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.KeyEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.KeyEvent(), + ), + ]; + client.descriptors.page.listKeyEvents.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listKeyEventsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.KeyEvent[] = []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1beta.KeyEvent) => { + 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.listKeyEvents.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listKeyEvents, request), + ); + assert( + (client.descriptors.page.listKeyEvents.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('matchAccountSummaryFromAccountSummaryName', () => { - const result = client.matchAccountSummaryFromAccountSummaryName(fakePath); - assert.strictEqual(result, "accountSummaryValue"); - assert((client.pathTemplates.accountSummaryPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes listKeyEventsStream with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListKeyEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListKeyEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listKeyEvents.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listKeyEventsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.KeyEvent[] = []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1beta.KeyEvent) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listKeyEvents.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listKeyEvents, request), + ); + assert( + (client.descriptors.page.listKeyEvents.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('conversionEvent', async () => { - const fakePath = "/rendered/path/conversionEvent"; - const expectedParameters = { - property: "propertyValue", - conversion_event: "conversionEventValue", - }; - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.conversionEventPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.conversionEventPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('conversionEventPath', () => { - const result = client.conversionEventPath("propertyValue", "conversionEventValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.conversionEventPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('uses async iteration with listKeyEvents without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListKeyEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListKeyEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.KeyEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.KeyEvent(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.KeyEvent(), + ), + ]; + client.descriptors.page.listKeyEvents.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1beta.IKeyEvent[] = []; + const iterable = client.listKeyEventsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listKeyEvents.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listKeyEvents.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('matchPropertyFromConversionEventName', () => { - const result = client.matchPropertyFromConversionEventName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.conversionEventPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('uses async iteration with listKeyEvents with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListKeyEventsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListKeyEventsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listKeyEvents.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listKeyEventsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1beta.IKeyEvent[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listKeyEvents.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listKeyEvents.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listCustomDimensions', () => { + it('invokes listCustomDimensions without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListCustomDimensionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListCustomDimensionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomDimension(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomDimension(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomDimension(), + ), + ]; + client.innerApiCalls.listCustomDimensions = + stubSimpleCall(expectedResponse); + const [response] = await client.listCustomDimensions(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCustomDimensions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCustomDimensions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchConversionEventFromConversionEventName', () => { - const result = client.matchConversionEventFromConversionEventName(fakePath); - assert.strictEqual(result, "conversionEventValue"); - assert((client.pathTemplates.conversionEventPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes listCustomDimensions without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListCustomDimensionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListCustomDimensionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomDimension(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomDimension(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomDimension(), + ), + ]; + client.innerApiCalls.listCustomDimensions = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listCustomDimensions( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1beta.ICustomDimension[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCustomDimensions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCustomDimensions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('customDimension', async () => { - const fakePath = "/rendered/path/customDimension"; - const expectedParameters = { - property: "propertyValue", - custom_dimension: "customDimensionValue", - }; - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.customDimensionPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.customDimensionPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('customDimensionPath', () => { - const result = client.customDimensionPath("propertyValue", "customDimensionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.customDimensionPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes listCustomDimensions with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListCustomDimensionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListCustomDimensionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listCustomDimensions = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listCustomDimensions(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listCustomDimensions as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCustomDimensions as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchPropertyFromCustomDimensionName', () => { - const result = client.matchPropertyFromCustomDimensionName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.customDimensionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listCustomDimensionsStream without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListCustomDimensionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListCustomDimensionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomDimension(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomDimension(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomDimension(), + ), + ]; + client.descriptors.page.listCustomDimensions.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listCustomDimensionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.CustomDimension[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1beta.CustomDimension) => { + 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.listCustomDimensions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCustomDimensions, request), + ); + assert( + (client.descriptors.page.listCustomDimensions.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('matchCustomDimensionFromCustomDimensionName', () => { - const result = client.matchCustomDimensionFromCustomDimensionName(fakePath); - assert.strictEqual(result, "customDimensionValue"); - assert((client.pathTemplates.customDimensionPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes listCustomDimensionsStream with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListCustomDimensionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListCustomDimensionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCustomDimensions.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listCustomDimensionsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.CustomDimension[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1beta.CustomDimension) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listCustomDimensions.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCustomDimensions, request), + ); + assert( + (client.descriptors.page.listCustomDimensions.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('customMetric', async () => { - const fakePath = "/rendered/path/customMetric"; - const expectedParameters = { - property: "propertyValue", - custom_metric: "customMetricValue", - }; - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.customMetricPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.customMetricPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('customMetricPath', () => { - const result = client.customMetricPath("propertyValue", "customMetricValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.customMetricPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('uses async iteration with listCustomDimensions without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListCustomDimensionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListCustomDimensionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomDimension(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomDimension(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomDimension(), + ), + ]; + client.descriptors.page.listCustomDimensions.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1beta.ICustomDimension[] = + []; + const iterable = client.listCustomDimensionsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listCustomDimensions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listCustomDimensions.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('matchPropertyFromCustomMetricName', () => { - const result = client.matchPropertyFromCustomMetricName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.customMetricPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('uses async iteration with listCustomDimensions with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListCustomDimensionsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListCustomDimensionsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCustomDimensions.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listCustomDimensionsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1beta.ICustomDimension[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listCustomDimensions.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listCustomDimensions.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listCustomMetrics', () => { + it('invokes listCustomMetrics without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListCustomMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListCustomMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomMetric(), + ), + ]; + client.innerApiCalls.listCustomMetrics = stubSimpleCall(expectedResponse); + const [response] = await client.listCustomMetrics(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCustomMetrics as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCustomMetrics as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchCustomMetricFromCustomMetricName', () => { - const result = client.matchCustomMetricFromCustomMetricName(fakePath); - assert.strictEqual(result, "customMetricValue"); - assert((client.pathTemplates.customMetricPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes listCustomMetrics without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListCustomMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListCustomMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomMetric(), + ), + ]; + client.innerApiCalls.listCustomMetrics = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listCustomMetrics( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.admin.v1beta.ICustomMetric[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCustomMetrics as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCustomMetrics as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('dataRetentionSettings', async () => { - const fakePath = "/rendered/path/dataRetentionSettings"; - const expectedParameters = { - property: "propertyValue", - }; - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.dataRetentionSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.dataRetentionSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('dataRetentionSettingsPath', () => { - const result = client.dataRetentionSettingsPath("propertyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.dataRetentionSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes listCustomMetrics with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListCustomMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListCustomMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listCustomMetrics = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listCustomMetrics(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listCustomMetrics as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCustomMetrics as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchPropertyFromDataRetentionSettingsName', () => { - const result = client.matchPropertyFromDataRetentionSettingsName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.dataRetentionSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes listCustomMetricsStream without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListCustomMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListCustomMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomMetric(), + ), + ]; + client.descriptors.page.listCustomMetrics.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listCustomMetricsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.CustomMetric[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1beta.CustomMetric) => { + 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.listCustomMetrics.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCustomMetrics, request), + ); + assert( + (client.descriptors.page.listCustomMetrics.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('dataSharingSettings', async () => { - const fakePath = "/rendered/path/dataSharingSettings"; - const expectedParameters = { - account: "accountValue", - }; - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.dataSharingSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.dataSharingSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('dataSharingSettingsPath', () => { - const result = client.dataSharingSettingsPath("accountValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.dataSharingSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes listCustomMetricsStream with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListCustomMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListCustomMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCustomMetrics.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listCustomMetricsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.CustomMetric[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1beta.CustomMetric) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listCustomMetrics.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCustomMetrics, request), + ); + assert( + (client.descriptors.page.listCustomMetrics.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('matchAccountFromDataSharingSettingsName', () => { - const result = client.matchAccountFromDataSharingSettingsName(fakePath); - assert.strictEqual(result, "accountValue"); - assert((client.pathTemplates.dataSharingSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listCustomMetrics without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListCustomMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListCustomMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomMetric(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.CustomMetric(), + ), + ]; + client.descriptors.page.listCustomMetrics.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1beta.ICustomMetric[] = + []; + const iterable = client.listCustomMetricsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listCustomMetrics.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listCustomMetrics.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('dataStream', async () => { - const fakePath = "/rendered/path/dataStream"; - const expectedParameters = { - property: "propertyValue", - data_stream: "dataStreamValue", - }; - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.dataStreamPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.dataStreamPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('dataStreamPath', () => { - const result = client.dataStreamPath("propertyValue", "dataStreamValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.dataStreamPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('uses async iteration with listCustomMetrics with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListCustomMetricsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListCustomMetricsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCustomMetrics.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listCustomMetricsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1beta.ICustomMetric[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listCustomMetrics.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listCustomMetrics.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listDataStreams', () => { + it('invokes listDataStreams without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListDataStreamsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListDataStreamsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataStream(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataStream(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataStream(), + ), + ]; + client.innerApiCalls.listDataStreams = stubSimpleCall(expectedResponse); + const [response] = await client.listDataStreams(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDataStreams as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDataStreams as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchPropertyFromDataStreamName', () => { - const result = client.matchPropertyFromDataStreamName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.dataStreamPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listDataStreams without error using callback', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListDataStreamsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListDataStreamsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataStream(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataStream(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataStream(), + ), + ]; + client.innerApiCalls.listDataStreams = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listDataStreams( + request, + ( + err?: Error | null, + result?: protos.google.analytics.admin.v1beta.IDataStream[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDataStreams as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDataStreams as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchDataStreamFromDataStreamName', () => { - const result = client.matchDataStreamFromDataStreamName(fakePath); - assert.strictEqual(result, "dataStreamValue"); - assert((client.pathTemplates.dataStreamPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes listDataStreams with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListDataStreamsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListDataStreamsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listDataStreams = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listDataStreams(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listDataStreams as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDataStreams as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('firebaseLink', async () => { - const fakePath = "/rendered/path/firebaseLink"; - const expectedParameters = { - property: "propertyValue", - firebase_link: "firebaseLinkValue", - }; - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.firebaseLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.firebaseLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('firebaseLinkPath', () => { - const result = client.firebaseLinkPath("propertyValue", "firebaseLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.firebaseLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes listDataStreamsStream without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListDataStreamsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListDataStreamsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataStream(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataStream(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataStream(), + ), + ]; + client.descriptors.page.listDataStreams.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listDataStreamsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.DataStream[] = []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1beta.DataStream) => { + 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.listDataStreams.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listDataStreams, request), + ); + assert( + (client.descriptors.page.listDataStreams.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('matchPropertyFromFirebaseLinkName', () => { - const result = client.matchPropertyFromFirebaseLinkName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.firebaseLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes listDataStreamsStream with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListDataStreamsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListDataStreamsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDataStreams.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listDataStreamsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.admin.v1beta.DataStream[] = []; + stream.on( + 'data', + (response: protos.google.analytics.admin.v1beta.DataStream) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listDataStreams.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listDataStreams, request), + ); + assert( + (client.descriptors.page.listDataStreams.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('matchFirebaseLinkFromFirebaseLinkName', () => { - const result = client.matchFirebaseLinkFromFirebaseLinkName(fakePath); - assert.strictEqual(result, "firebaseLinkValue"); - assert((client.pathTemplates.firebaseLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listDataStreams without error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListDataStreamsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListDataStreamsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataStream(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataStream(), + ), + generateSampleMessage( + new protos.google.analytics.admin.v1beta.DataStream(), + ), + ]; + client.descriptors.page.listDataStreams.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.admin.v1beta.IDataStream[] = []; + const iterable = client.listDataStreamsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listDataStreams.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listDataStreams.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - describe('googleAdsLink', async () => { - const fakePath = "/rendered/path/googleAdsLink"; - const expectedParameters = { - property: "propertyValue", - google_ads_link: "googleAdsLinkValue", - }; - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.googleAdsLinkPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.googleAdsLinkPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('googleAdsLinkPath', () => { - const result = client.googleAdsLinkPath("propertyValue", "googleAdsLinkValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.googleAdsLinkPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('uses async iteration with listDataStreams with error', async () => { + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.admin.v1beta.ListDataStreamsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.admin.v1beta.ListDataStreamsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDataStreams.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listDataStreamsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.admin.v1beta.IDataStream[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listDataStreams.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listDataStreams.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('account', async () => { + const fakePath = '/rendered/path/account'; + const expectedParameters = { + account: 'accountValue', + }; + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.accountPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.accountPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('accountPath', () => { + const result = client.accountPath('accountValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.accountPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountFromAccountName', () => { + const result = client.matchAccountFromAccountName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + (client.pathTemplates.accountPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchPropertyFromGoogleAdsLinkName', () => { - const result = client.matchPropertyFromGoogleAdsLinkName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.googleAdsLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('accountSummary', async () => { + const fakePath = '/rendered/path/accountSummary'; + const expectedParameters = { + account_summary: 'accountSummaryValue', + }; + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.accountSummaryPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.accountSummaryPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('accountSummaryPath', () => { + const result = client.accountSummaryPath('accountSummaryValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.accountSummaryPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountSummaryFromAccountSummaryName', () => { + const result = + client.matchAccountSummaryFromAccountSummaryName(fakePath); + assert.strictEqual(result, 'accountSummaryValue'); + assert( + (client.pathTemplates.accountSummaryPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchGoogleAdsLinkFromGoogleAdsLinkName', () => { - const result = client.matchGoogleAdsLinkFromGoogleAdsLinkName(fakePath); - assert.strictEqual(result, "googleAdsLinkValue"); - assert((client.pathTemplates.googleAdsLinkPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('conversionEvent', async () => { + const fakePath = '/rendered/path/conversionEvent'; + const expectedParameters = { + property: 'propertyValue', + conversion_event: 'conversionEventValue', + }; + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.conversionEventPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.conversionEventPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('conversionEventPath', () => { + const result = client.conversionEventPath( + 'propertyValue', + 'conversionEventValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.conversionEventPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromConversionEventName', () => { + const result = client.matchPropertyFromConversionEventName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.conversionEventPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchConversionEventFromConversionEventName', () => { + const result = + client.matchConversionEventFromConversionEventName(fakePath); + assert.strictEqual(result, 'conversionEventValue'); + assert( + (client.pathTemplates.conversionEventPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('keyEvent', async () => { - const fakePath = "/rendered/path/keyEvent"; - const expectedParameters = { - property: "propertyValue", - key_event: "keyEventValue", - }; - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.keyEventPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.keyEventPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('keyEventPath', () => { - const result = client.keyEventPath("propertyValue", "keyEventValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.keyEventPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('customDimension', async () => { + const fakePath = '/rendered/path/customDimension'; + const expectedParameters = { + property: 'propertyValue', + custom_dimension: 'customDimensionValue', + }; + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.customDimensionPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.customDimensionPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('customDimensionPath', () => { + const result = client.customDimensionPath( + 'propertyValue', + 'customDimensionValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.customDimensionPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromCustomDimensionName', () => { + const result = client.matchPropertyFromCustomDimensionName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.customDimensionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCustomDimensionFromCustomDimensionName', () => { + const result = + client.matchCustomDimensionFromCustomDimensionName(fakePath); + assert.strictEqual(result, 'customDimensionValue'); + assert( + (client.pathTemplates.customDimensionPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchPropertyFromKeyEventName', () => { - const result = client.matchPropertyFromKeyEventName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.keyEventPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('customMetric', async () => { + const fakePath = '/rendered/path/customMetric'; + const expectedParameters = { + property: 'propertyValue', + custom_metric: 'customMetricValue', + }; + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.customMetricPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.customMetricPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('customMetricPath', () => { + const result = client.customMetricPath( + 'propertyValue', + 'customMetricValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.customMetricPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromCustomMetricName', () => { + const result = client.matchPropertyFromCustomMetricName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.customMetricPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchCustomMetricFromCustomMetricName', () => { + const result = client.matchCustomMetricFromCustomMetricName(fakePath); + assert.strictEqual(result, 'customMetricValue'); + assert( + (client.pathTemplates.customMetricPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchKeyEventFromKeyEventName', () => { - const result = client.matchKeyEventFromKeyEventName(fakePath); - assert.strictEqual(result, "keyEventValue"); - assert((client.pathTemplates.keyEventPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('dataRetentionSettings', async () => { + const fakePath = '/rendered/path/dataRetentionSettings'; + const expectedParameters = { + property: 'propertyValue', + }; + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.dataRetentionSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.dataRetentionSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('dataRetentionSettingsPath', () => { + const result = client.dataRetentionSettingsPath('propertyValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.dataRetentionSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromDataRetentionSettingsName', () => { + const result = + client.matchPropertyFromDataRetentionSettingsName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + ( + client.pathTemplates.dataRetentionSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('measurementProtocolSecret', async () => { - const fakePath = "/rendered/path/measurementProtocolSecret"; - const expectedParameters = { - property: "propertyValue", - data_stream: "dataStreamValue", - measurement_protocol_secret: "measurementProtocolSecretValue", - }; - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.measurementProtocolSecretPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.measurementProtocolSecretPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('measurementProtocolSecretPath', () => { - const result = client.measurementProtocolSecretPath("propertyValue", "dataStreamValue", "measurementProtocolSecretValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.measurementProtocolSecretPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('dataSharingSettings', async () => { + const fakePath = '/rendered/path/dataSharingSettings'; + const expectedParameters = { + account: 'accountValue', + }; + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.dataSharingSettingsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.dataSharingSettingsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('dataSharingSettingsPath', () => { + const result = client.dataSharingSettingsPath('accountValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.dataSharingSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchAccountFromDataSharingSettingsName', () => { + const result = client.matchAccountFromDataSharingSettingsName(fakePath); + assert.strictEqual(result, 'accountValue'); + assert( + ( + client.pathTemplates.dataSharingSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchPropertyFromMeasurementProtocolSecretName', () => { - const result = client.matchPropertyFromMeasurementProtocolSecretName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.measurementProtocolSecretPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('dataStream', async () => { + const fakePath = '/rendered/path/dataStream'; + const expectedParameters = { + property: 'propertyValue', + data_stream: 'dataStreamValue', + }; + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.dataStreamPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.dataStreamPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('dataStreamPath', () => { + const result = client.dataStreamPath( + 'propertyValue', + 'dataStreamValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.dataStreamPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromDataStreamName', () => { + const result = client.matchPropertyFromDataStreamName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.dataStreamPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDataStreamFromDataStreamName', () => { + const result = client.matchDataStreamFromDataStreamName(fakePath); + assert.strictEqual(result, 'dataStreamValue'); + assert( + (client.pathTemplates.dataStreamPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchDataStreamFromMeasurementProtocolSecretName', () => { - const result = client.matchDataStreamFromMeasurementProtocolSecretName(fakePath); - assert.strictEqual(result, "dataStreamValue"); - assert((client.pathTemplates.measurementProtocolSecretPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + describe('firebaseLink', async () => { + const fakePath = '/rendered/path/firebaseLink'; + const expectedParameters = { + property: 'propertyValue', + firebase_link: 'firebaseLinkValue', + }; + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.firebaseLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.firebaseLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('firebaseLinkPath', () => { + const result = client.firebaseLinkPath( + 'propertyValue', + 'firebaseLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.firebaseLinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromFirebaseLinkName', () => { + const result = client.matchPropertyFromFirebaseLinkName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.firebaseLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchFirebaseLinkFromFirebaseLinkName', () => { + const result = client.matchFirebaseLinkFromFirebaseLinkName(fakePath); + assert.strictEqual(result, 'firebaseLinkValue'); + assert( + (client.pathTemplates.firebaseLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchMeasurementProtocolSecretFromMeasurementProtocolSecretName', () => { - const result = client.matchMeasurementProtocolSecretFromMeasurementProtocolSecretName(fakePath); - assert.strictEqual(result, "measurementProtocolSecretValue"); - assert((client.pathTemplates.measurementProtocolSecretPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('googleAdsLink', async () => { + const fakePath = '/rendered/path/googleAdsLink'; + const expectedParameters = { + property: 'propertyValue', + google_ads_link: 'googleAdsLinkValue', + }; + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.googleAdsLinkPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.googleAdsLinkPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('googleAdsLinkPath', () => { + const result = client.googleAdsLinkPath( + 'propertyValue', + 'googleAdsLinkValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.googleAdsLinkPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromGoogleAdsLinkName', () => { + const result = client.matchPropertyFromGoogleAdsLinkName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.googleAdsLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchGoogleAdsLinkFromGoogleAdsLinkName', () => { + const result = client.matchGoogleAdsLinkFromGoogleAdsLinkName(fakePath); + assert.strictEqual(result, 'googleAdsLinkValue'); + assert( + (client.pathTemplates.googleAdsLinkPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('property', async () => { - const fakePath = "/rendered/path/property"; - const expectedParameters = { - property: "propertyValue", - }; - const client = new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.propertyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.propertyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('propertyPath', () => { - const result = client.propertyPath("propertyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.propertyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('keyEvent', async () => { + const fakePath = '/rendered/path/keyEvent'; + const expectedParameters = { + property: 'propertyValue', + key_event: 'keyEventValue', + }; + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.keyEventPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.keyEventPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('keyEventPath', () => { + const result = client.keyEventPath('propertyValue', 'keyEventValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.keyEventPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromKeyEventName', () => { + const result = client.matchPropertyFromKeyEventName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.keyEventPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchKeyEventFromKeyEventName', () => { + const result = client.matchKeyEventFromKeyEventName(fakePath); + assert.strictEqual(result, 'keyEventValue'); + assert( + (client.pathTemplates.keyEventPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchPropertyFromPropertyName', () => { - const result = client.matchPropertyFromPropertyName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.propertyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('measurementProtocolSecret', async () => { + const fakePath = '/rendered/path/measurementProtocolSecret'; + const expectedParameters = { + property: 'propertyValue', + data_stream: 'dataStreamValue', + measurement_protocol_secret: 'measurementProtocolSecretValue', + }; + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.measurementProtocolSecretPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.measurementProtocolSecretPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('measurementProtocolSecretPath', () => { + const result = client.measurementProtocolSecretPath( + 'propertyValue', + 'dataStreamValue', + 'measurementProtocolSecretValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.measurementProtocolSecretPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromMeasurementProtocolSecretName', () => { + const result = + client.matchPropertyFromMeasurementProtocolSecretName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + ( + client.pathTemplates.measurementProtocolSecretPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchDataStreamFromMeasurementProtocolSecretName', () => { + const result = + client.matchDataStreamFromMeasurementProtocolSecretName(fakePath); + assert.strictEqual(result, 'dataStreamValue'); + assert( + ( + client.pathTemplates.measurementProtocolSecretPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchMeasurementProtocolSecretFromMeasurementProtocolSecretName', () => { + const result = + client.matchMeasurementProtocolSecretFromMeasurementProtocolSecretName( + fakePath, + ); + assert.strictEqual(result, 'measurementProtocolSecretValue'); + assert( + ( + client.pathTemplates.measurementProtocolSecretPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('property', async () => { + const fakePath = '/rendered/path/property'; + const expectedParameters = { + property: 'propertyValue', + }; + const client = + new analyticsadminserviceModule.v1beta.AnalyticsAdminServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.propertyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.propertyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('propertyPath', () => { + const result = client.propertyPath('propertyValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.propertyPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromPropertyName', () => { + const result = client.matchPropertyFromPropertyName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.propertyPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-analytics-admin/webpack.config.js b/packages/google-analytics-admin/webpack.config.js index 400540304f09..0e336a8bddc6 100644 --- a/packages/google-analytics-admin/webpack.config.js +++ b/packages/google-analytics-admin/webpack.config.js @@ -1,4 +1,4 @@ -// Copyright 2026 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/packages/google-analytics-data/README.md b/packages/google-analytics-data/README.md index 281ad5361204..99f507b213ed 100644 --- a/packages/google-analytics-data/README.md +++ b/packages/google-analytics-data/README.md @@ -118,7 +118,7 @@ More Information: [Google Cloud Platform Launch Stages][launch_stages] ## Contributing -Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-analytics-data/CONTRIBUTING.md). +Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/google-cloud-node/blob/main/CONTRIBUTING.md). Please note that this `README.md` and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`) @@ -128,7 +128,7 @@ are generated from a central template. Apache Version 2.0 -See [LICENSE](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-analytics-data/LICENSE) +See [LICENSE](https://github.com/googleapis/google-cloud-node/blob/main/LICENSE) [shell_img]: https://gstatic.com/cloudssh/images/open-btn.png [projects]: https://console.cloud.google.com/project diff --git a/packages/google-analytics-data/protos/protos.d.ts b/packages/google-analytics-data/protos/protos.d.ts index 5f7a160e8a0d..6a9dbfcb4cc9 100644 --- a/packages/google-analytics-data/protos/protos.d.ts +++ b/packages/google-analytics-data/protos/protos.d.ts @@ -223,6 +223,7 @@ export namespace google { /** Edition enum. */ enum Edition { EDITION_UNKNOWN = 0, + EDITION_LEGACY = 900, EDITION_PROTO2 = 998, EDITION_PROTO3 = 999, EDITION_2023 = 1000, @@ -253,6 +254,9 @@ export namespace google { /** FileDescriptorProto weakDependency */ weakDependency?: (number[]|null); + /** FileDescriptorProto optionDependency */ + optionDependency?: (string[]|null); + /** FileDescriptorProto messageType */ messageType?: (google.protobuf.IDescriptorProto[]|null); @@ -302,6 +306,9 @@ export namespace google { /** FileDescriptorProto weakDependency. */ public weakDependency: number[]; + /** FileDescriptorProto optionDependency. */ + public optionDependency: string[]; + /** FileDescriptorProto messageType. */ public messageType: google.protobuf.IDescriptorProto[]; @@ -436,6 +443,9 @@ export namespace google { /** DescriptorProto reservedName */ reservedName?: (string[]|null); + + /** DescriptorProto visibility */ + visibility?: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility|null); } /** Represents a DescriptorProto. */ @@ -477,6 +487,9 @@ export namespace google { /** DescriptorProto reservedName. */ public reservedName: string[]; + /** DescriptorProto visibility. */ + public visibility: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility); + /** * Creates a new DescriptorProto instance using the specified properties. * @param [properties] Properties to set @@ -1324,6 +1337,9 @@ export namespace google { /** EnumDescriptorProto reservedName */ reservedName?: (string[]|null); + + /** EnumDescriptorProto visibility */ + visibility?: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility|null); } /** Represents an EnumDescriptorProto. */ @@ -1350,6 +1366,9 @@ export namespace google { /** EnumDescriptorProto reservedName. */ public reservedName: string[]; + /** EnumDescriptorProto visibility. */ + public visibility: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility); + /** * Creates a new EnumDescriptorProto instance using the specified properties. * @param [properties] Properties to set @@ -2284,6 +2303,9 @@ 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); @@ -2339,6 +2361,9 @@ 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[]; @@ -2559,6 +2584,121 @@ export namespace google { */ public static getTypeUrl(typeUrlPrefix?: string): string; } + + /** Properties of a FeatureSupport. */ + interface IFeatureSupport { + + /** FeatureSupport editionIntroduced */ + editionIntroduced?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + + /** FeatureSupport editionDeprecated */ + editionDeprecated?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + + /** FeatureSupport deprecationWarning */ + deprecationWarning?: (string|null); + + /** FeatureSupport editionRemoved */ + editionRemoved?: (google.protobuf.Edition|keyof typeof 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|keyof typeof google.protobuf.Edition); + + /** FeatureSupport editionDeprecated. */ + public editionDeprecated: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** FeatureSupport deprecationWarning. */ + public deprecationWarning: string; + + /** FeatureSupport editionRemoved. */ + public editionRemoved: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** + * Creates a new FeatureSupport instance using the specified properties. + * @param [properties] Properties to set + * @returns FeatureSupport instance + */ + public static create(properties?: google.protobuf.FieldOptions.IFeatureSupport): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Encodes the specified FeatureSupport message. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @param message FeatureSupport message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.FieldOptions.IFeatureSupport, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FeatureSupport message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @param message FeatureSupport message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.FieldOptions.IFeatureSupport, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Verifies a FeatureSupport message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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. */ @@ -2797,6 +2937,9 @@ export namespace google { /** EnumValueOptions debugRedact */ debugRedact?: (boolean|null); + /** EnumValueOptions featureSupport */ + featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); + /** EnumValueOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } @@ -2819,6 +2962,9 @@ export namespace google { /** EnumValueOptions debugRedact. */ public debugRedact: boolean; + /** EnumValueOptions featureSupport. */ + public featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); + /** EnumValueOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -3411,6 +3557,12 @@ export namespace google { /** FeatureSet jsonFormat */ jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|keyof typeof google.protobuf.FeatureSet.JsonFormat|null); + + /** FeatureSet enforceNamingStyle */ + enforceNamingStyle?: (google.protobuf.FeatureSet.EnforceNamingStyle|keyof typeof google.protobuf.FeatureSet.EnforceNamingStyle|null); + + /** FeatureSet defaultSymbolVisibility */ + defaultSymbolVisibility?: (google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|keyof typeof google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|null); } /** Represents a FeatureSet. */ @@ -3440,6 +3592,12 @@ export namespace google { /** FeatureSet jsonFormat. */ public jsonFormat: (google.protobuf.FeatureSet.JsonFormat|keyof typeof google.protobuf.FeatureSet.JsonFormat); + /** FeatureSet enforceNamingStyle. */ + public enforceNamingStyle: (google.protobuf.FeatureSet.EnforceNamingStyle|keyof typeof google.protobuf.FeatureSet.EnforceNamingStyle); + + /** FeatureSet defaultSymbolVisibility. */ + public defaultSymbolVisibility: (google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|keyof typeof google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility); + /** * Creates a new FeatureSet instance using the specified properties. * @param [properties] Properties to set @@ -3562,6 +3720,116 @@ export namespace google { ALLOW = 1, LEGACY_BEST_EFFORT = 2 } + + /** EnforceNamingStyle enum. */ + enum EnforceNamingStyle { + ENFORCE_NAMING_STYLE_UNKNOWN = 0, + STYLE2024 = 1, + STYLE_LEGACY = 2 + } + + /** Properties of a VisibilityFeature. */ + interface IVisibilityFeature { + } + + /** Represents a VisibilityFeature. */ + class VisibilityFeature implements IVisibilityFeature { + + /** + * Constructs a new VisibilityFeature. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FeatureSet.IVisibilityFeature); + + /** + * Creates a new VisibilityFeature instance using the specified properties. + * @param [properties] Properties to set + * @returns VisibilityFeature instance + */ + public static create(properties?: google.protobuf.FeatureSet.IVisibilityFeature): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Encodes the specified VisibilityFeature message. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @param message VisibilityFeature message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.FeatureSet.IVisibilityFeature, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified VisibilityFeature message, length delimited. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @param message VisibilityFeature message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.FeatureSet.IVisibilityFeature, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Verifies a VisibilityFeature message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a VisibilityFeature message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns VisibilityFeature + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Creates a plain object from a VisibilityFeature message. Also converts values to other types if specified. + * @param message VisibilityFeature + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet.VisibilityFeature, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this VisibilityFeature to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for VisibilityFeature + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace VisibilityFeature { + + /** DefaultSymbolVisibility enum. */ + enum DefaultSymbolVisibility { + DEFAULT_SYMBOL_VISIBILITY_UNKNOWN = 0, + EXPORT_ALL = 1, + EXPORT_TOP_LEVEL = 2, + LOCAL_ALL = 3, + STRICT = 4 + } + } } /** Properties of a FeatureSetDefaults. */ @@ -3681,8 +3949,11 @@ export namespace google { /** FeatureSetEditionDefault edition */ edition?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); - /** FeatureSetEditionDefault features */ - features?: (google.protobuf.IFeatureSet|null); + /** FeatureSetEditionDefault overridableFeatures */ + overridableFeatures?: (google.protobuf.IFeatureSet|null); + + /** FeatureSetEditionDefault fixedFeatures */ + fixedFeatures?: (google.protobuf.IFeatureSet|null); } /** Represents a FeatureSetEditionDefault. */ @@ -3697,8 +3968,11 @@ export namespace google { /** FeatureSetEditionDefault edition. */ public edition: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); - /** FeatureSetEditionDefault features. */ - public features?: (google.protobuf.IFeatureSet|null); + /** FeatureSetEditionDefault overridableFeatures. */ + public overridableFeatures?: (google.protobuf.IFeatureSet|null); + + /** FeatureSetEditionDefault fixedFeatures. */ + public fixedFeatures?: (google.protobuf.IFeatureSet|null); /** * Creates a new FeatureSetEditionDefault instance using the specified properties. @@ -4231,6 +4505,13 @@ export namespace google { } } + /** SymbolVisibility enum. */ + enum SymbolVisibility { + VISIBILITY_UNSET = 0, + VISIBILITY_LOCAL = 1, + VISIBILITY_EXPORT = 2 + } + /** Properties of an Any. */ interface IAny { @@ -25863,6 +26144,9 @@ export namespace google { /** CommonLanguageSettings destinations */ destinations?: (google.api.ClientLibraryDestination[]|null); + + /** CommonLanguageSettings selectiveGapicGeneration */ + selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); } /** Represents a CommonLanguageSettings. */ @@ -25880,6 +26164,9 @@ export namespace google { /** CommonLanguageSettings destinations. */ public destinations: google.api.ClientLibraryDestination[]; + /** CommonLanguageSettings selectiveGapicGeneration. */ + public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + /** * Creates a new CommonLanguageSettings instance using the specified properties. * @param [properties] Properties to set @@ -26580,6 +26867,9 @@ export namespace google { /** PythonSettings common */ common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures */ + experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); } /** Represents a PythonSettings. */ @@ -26594,6 +26884,9 @@ export namespace google { /** PythonSettings common. */ public common?: (google.api.ICommonLanguageSettings|null); + /** PythonSettings experimentalFeatures. */ + public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + /** * Creates a new PythonSettings instance using the specified properties. * @param [properties] Properties to set @@ -26672,6 +26965,118 @@ 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); + + /** ExperimentalFeatures unversionedPackageDisabled */ + unversionedPackageDisabled?: (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; + + /** ExperimentalFeatures unversionedPackageDisabled. */ + public unversionedPackageDisabled: boolean; + + /** + * Creates a new ExperimentalFeatures instance using the specified properties. + * @param [properties] Properties to set + * @returns ExperimentalFeatures instance + */ + public static create(properties?: google.api.PythonSettings.IExperimentalFeatures): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Encodes the specified ExperimentalFeatures message. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @param message ExperimentalFeatures message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.PythonSettings.IExperimentalFeatures, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExperimentalFeatures message, length delimited. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @param message ExperimentalFeatures message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.PythonSettings.IExperimentalFeatures, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Verifies an ExperimentalFeatures message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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 { @@ -26998,6 +27403,9 @@ export namespace google { /** GoSettings common */ common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); } /** Represents a GoSettings. */ @@ -27012,6 +27420,9 @@ export namespace google { /** GoSettings common. */ public common?: (google.api.ICommonLanguageSettings|null); + /** GoSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + /** * Creates a new GoSettings instance using the specified properties. * @param [properties] Properties to set @@ -27336,6 +27747,109 @@ export namespace google { PACKAGE_MANAGER = 20 } + /** 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 new SelectiveGapicGeneration instance using the specified properties. + * @param [properties] Properties to set + * @returns SelectiveGapicGeneration instance + */ + public static create(properties?: google.api.ISelectiveGapicGeneration): google.api.SelectiveGapicGeneration; + + /** + * Encodes the specified SelectiveGapicGeneration message. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @param message SelectiveGapicGeneration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.ISelectiveGapicGeneration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SelectiveGapicGeneration message, length delimited. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @param message SelectiveGapicGeneration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.ISelectiveGapicGeneration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.SelectiveGapicGeneration; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.SelectiveGapicGeneration; + + /** + * Verifies a SelectiveGapicGeneration message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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. */ enum LaunchStage { LAUNCH_STAGE_UNSPECIFIED = 0, diff --git a/packages/google-analytics-data/protos/protos.js b/packages/google-analytics-data/protos/protos.js index c5814ccb74ed..c9ae9640b110 100644 --- a/packages/google-analytics-data/protos/protos.js +++ b/packages/google-analytics-data/protos/protos.js @@ -522,6 +522,7 @@ * @name google.protobuf.Edition * @enum {number} * @property {number} EDITION_UNKNOWN=0 EDITION_UNKNOWN value + * @property {number} EDITION_LEGACY=900 EDITION_LEGACY value * @property {number} EDITION_PROTO2=998 EDITION_PROTO2 value * @property {number} EDITION_PROTO3=999 EDITION_PROTO3 value * @property {number} EDITION_2023=1000 EDITION_2023 value @@ -536,6 +537,7 @@ protobuf.Edition = (function() { var valuesById = {}, values = Object.create(valuesById); values[valuesById[0] = "EDITION_UNKNOWN"] = 0; + values[valuesById[900] = "EDITION_LEGACY"] = 900; values[valuesById[998] = "EDITION_PROTO2"] = 998; values[valuesById[999] = "EDITION_PROTO3"] = 999; values[valuesById[1000] = "EDITION_2023"] = 1000; @@ -560,6 +562,7 @@ * @property {Array.|null} [dependency] FileDescriptorProto dependency * @property {Array.|null} [publicDependency] FileDescriptorProto publicDependency * @property {Array.|null} [weakDependency] FileDescriptorProto weakDependency + * @property {Array.|null} [optionDependency] FileDescriptorProto optionDependency * @property {Array.|null} [messageType] FileDescriptorProto messageType * @property {Array.|null} [enumType] FileDescriptorProto enumType * @property {Array.|null} [service] FileDescriptorProto service @@ -582,6 +585,7 @@ this.dependency = []; this.publicDependency = []; this.weakDependency = []; + this.optionDependency = []; this.messageType = []; this.enumType = []; this.service = []; @@ -632,6 +636,14 @@ */ FileDescriptorProto.prototype.weakDependency = $util.emptyArray; + /** + * FileDescriptorProto optionDependency. + * @member {Array.} optionDependency + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.optionDependency = $util.emptyArray; + /** * FileDescriptorProto messageType. * @member {Array.} messageType @@ -753,6 +765,9 @@ writer.uint32(/* id 12, wireType 2 =*/98).string(message.syntax); if (message.edition != null && Object.hasOwnProperty.call(message, "edition")) writer.uint32(/* id 14, wireType 0 =*/112).int32(message.edition); + if (message.optionDependency != null && message.optionDependency.length) + for (var i = 0; i < message.optionDependency.length; ++i) + writer.uint32(/* id 15, wireType 2 =*/122).string(message.optionDependency[i]); return writer; }; @@ -825,6 +840,12 @@ message.weakDependency.push(reader.int32()); break; } + case 15: { + if (!(message.optionDependency && message.optionDependency.length)) + message.optionDependency = []; + message.optionDependency.push(reader.string()); + break; + } case 4: { if (!(message.messageType && message.messageType.length)) message.messageType = []; @@ -927,6 +948,13 @@ if (!$util.isInteger(message.weakDependency[i])) return "weakDependency: integer[] expected"; } + if (message.optionDependency != null && message.hasOwnProperty("optionDependency")) { + if (!Array.isArray(message.optionDependency)) + return "optionDependency: array expected"; + for (var i = 0; i < message.optionDependency.length; ++i) + if (!$util.isString(message.optionDependency[i])) + return "optionDependency: string[] expected"; + } if (message.messageType != null && message.hasOwnProperty("messageType")) { if (!Array.isArray(message.messageType)) return "messageType: array expected"; @@ -981,6 +1009,7 @@ default: return "edition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -1033,6 +1062,13 @@ for (var i = 0; i < object.weakDependency.length; ++i) message.weakDependency[i] = object.weakDependency[i] | 0; } + if (object.optionDependency) { + if (!Array.isArray(object.optionDependency)) + throw TypeError(".google.protobuf.FileDescriptorProto.optionDependency: array expected"); + message.optionDependency = []; + for (var i = 0; i < object.optionDependency.length; ++i) + message.optionDependency[i] = String(object.optionDependency[i]); + } if (object.messageType) { if (!Array.isArray(object.messageType)) throw TypeError(".google.protobuf.FileDescriptorProto.messageType: array expected"); @@ -1096,6 +1132,10 @@ case 0: message.edition = 0; break; + case "EDITION_LEGACY": + case 900: + message.edition = 900; + break; case "EDITION_PROTO2": case 998: message.edition = 998; @@ -1161,6 +1201,7 @@ object.extension = []; object.publicDependency = []; object.weakDependency = []; + object.optionDependency = []; } if (options.defaults) { object.name = ""; @@ -1217,6 +1258,11 @@ 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; + if (message.optionDependency && message.optionDependency.length) { + object.optionDependency = []; + for (var j = 0; j < message.optionDependency.length; ++j) + object.optionDependency[j] = message.optionDependency[j]; + } return object; }; @@ -1265,6 +1311,7 @@ * @property {google.protobuf.IMessageOptions|null} [options] DescriptorProto options * @property {Array.|null} [reservedRange] DescriptorProto reservedRange * @property {Array.|null} [reservedName] DescriptorProto reservedName + * @property {google.protobuf.SymbolVisibility|null} [visibility] DescriptorProto visibility */ /** @@ -1370,6 +1417,14 @@ */ DescriptorProto.prototype.reservedName = $util.emptyArray; + /** + * DescriptorProto visibility. + * @member {google.protobuf.SymbolVisibility} visibility + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.visibility = 0; + /** * Creates a new DescriptorProto instance using the specified properties. * @function create @@ -1422,6 +1477,8 @@ if (message.reservedName != null && message.reservedName.length) for (var i = 0; i < message.reservedName.length; ++i) writer.uint32(/* id 10, wireType 2 =*/82).string(message.reservedName[i]); + if (message.visibility != null && Object.hasOwnProperty.call(message, "visibility")) + writer.uint32(/* id 11, wireType 0 =*/88).int32(message.visibility); return writer; }; @@ -1514,6 +1571,10 @@ message.reservedName.push(reader.string()); break; } + case 11: { + message.visibility = reader.int32(); + break; + } default: reader.skipType(tag & 7); break; @@ -1627,6 +1688,15 @@ if (!$util.isString(message.reservedName[i])) return "reservedName: string[] expected"; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + switch (message.visibility) { + default: + return "visibility: enum value expected"; + case 0: + case 1: + case 2: + break; + } return null; }; @@ -1726,6 +1796,26 @@ for (var i = 0; i < object.reservedName.length; ++i) message.reservedName[i] = String(object.reservedName[i]); } + switch (object.visibility) { + default: + if (typeof object.visibility === "number") { + message.visibility = object.visibility; + break; + } + break; + case "VISIBILITY_UNSET": + case 0: + message.visibility = 0; + break; + case "VISIBILITY_LOCAL": + case 1: + message.visibility = 1; + break; + case "VISIBILITY_EXPORT": + case 2: + message.visibility = 2; + break; + } return message; }; @@ -1755,6 +1845,7 @@ if (options.defaults) { object.name = ""; object.options = null; + object.visibility = options.enums === String ? "VISIBILITY_UNSET" : 0; } if (message.name != null && message.hasOwnProperty("name")) object.name = message.name; @@ -1800,6 +1891,8 @@ for (var j = 0; j < message.reservedName.length; ++j) object.reservedName[j] = message.reservedName[j]; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + object.visibility = options.enums === String ? $root.google.protobuf.SymbolVisibility[message.visibility] === undefined ? message.visibility : $root.google.protobuf.SymbolVisibility[message.visibility] : message.visibility; return object; }; @@ -3844,6 +3937,7 @@ * @property {google.protobuf.IEnumOptions|null} [options] EnumDescriptorProto options * @property {Array.|null} [reservedRange] EnumDescriptorProto reservedRange * @property {Array.|null} [reservedName] EnumDescriptorProto reservedName + * @property {google.protobuf.SymbolVisibility|null} [visibility] EnumDescriptorProto visibility */ /** @@ -3904,6 +3998,14 @@ */ EnumDescriptorProto.prototype.reservedName = $util.emptyArray; + /** + * EnumDescriptorProto visibility. + * @member {google.protobuf.SymbolVisibility} visibility + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.visibility = 0; + /** * Creates a new EnumDescriptorProto instance using the specified properties. * @function create @@ -3941,6 +4043,8 @@ if (message.reservedName != null && message.reservedName.length) for (var i = 0; i < message.reservedName.length; ++i) writer.uint32(/* id 5, wireType 2 =*/42).string(message.reservedName[i]); + if (message.visibility != null && Object.hasOwnProperty.call(message, "visibility")) + writer.uint32(/* id 6, wireType 0 =*/48).int32(message.visibility); return writer; }; @@ -4003,6 +4107,10 @@ message.reservedName.push(reader.string()); break; } + case 6: { + message.visibility = reader.int32(); + break; + } default: reader.skipType(tag & 7); break; @@ -4071,6 +4179,15 @@ if (!$util.isString(message.reservedName[i])) return "reservedName: string[] expected"; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + switch (message.visibility) { + default: + return "visibility: enum value expected"; + case 0: + case 1: + case 2: + break; + } return null; }; @@ -4120,6 +4237,26 @@ for (var i = 0; i < object.reservedName.length; ++i) message.reservedName[i] = String(object.reservedName[i]); } + switch (object.visibility) { + default: + if (typeof object.visibility === "number") { + message.visibility = object.visibility; + break; + } + break; + case "VISIBILITY_UNSET": + case 0: + message.visibility = 0; + break; + case "VISIBILITY_LOCAL": + case 1: + message.visibility = 1; + break; + case "VISIBILITY_EXPORT": + case 2: + message.visibility = 2; + break; + } return message; }; @@ -4144,6 +4281,7 @@ if (options.defaults) { object.name = ""; object.options = null; + object.visibility = options.enums === String ? "VISIBILITY_UNSET" : 0; } if (message.name != null && message.hasOwnProperty("name")) object.name = message.name; @@ -4164,6 +4302,8 @@ for (var j = 0; j < message.reservedName.length; ++j) object.reservedName[j] = message.reservedName[j]; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + object.visibility = options.enums === String ? $root.google.protobuf.SymbolVisibility[message.visibility] === undefined ? message.visibility : $root.google.protobuf.SymbolVisibility[message.visibility] : message.visibility; return object; }; @@ -6482,6 +6622,7 @@ * @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 @@ -6602,6 +6743,14 @@ */ 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 @@ -6676,6 +6825,8 @@ $root.google.protobuf.FieldOptions.EditionDefault.encode(message.editionDefaults[i], writer.uint32(/* id 20, wireType 2 =*/162).fork()).ldelim(); if (message.features != null && Object.hasOwnProperty.call(message, "features")) $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 21, wireType 2 =*/170).fork()).ldelim(); + if (message.featureSupport != null && Object.hasOwnProperty.call(message, "featureSupport")) + $root.google.protobuf.FieldOptions.FeatureSupport.encode(message.featureSupport, writer.uint32(/* id 22, wireType 2 =*/178).fork()).ldelim(); if (message.uninterpretedOption != null && message.uninterpretedOption.length) for (var i = 0; i < message.uninterpretedOption.length; ++i) $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); @@ -6777,6 +6928,10 @@ message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); break; } + case 22: { + message.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.decode(reader, reader.uint32()); + break; + } case 999: { if (!(message.uninterpretedOption && message.uninterpretedOption.length)) message.uninterpretedOption = []; @@ -6912,6 +7067,11 @@ if (error) return "features." + error; } + if (message.featureSupport != null && message.hasOwnProperty("featureSupport")) { + var error = $root.google.protobuf.FieldOptions.FeatureSupport.verify(message.featureSupport); + if (error) + return "featureSupport." + error; + } if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { if (!Array.isArray(message.uninterpretedOption)) return "uninterpretedOption: array expected"; @@ -7100,6 +7260,11 @@ 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"); @@ -7197,6 +7362,7 @@ 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")) @@ -7229,6 +7395,8 @@ } 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) @@ -7501,6 +7669,7 @@ default: return "edition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -7542,6 +7711,10 @@ case 0: message.edition = 0; break; + case "EDITION_LEGACY": + case 900: + message.edition = 900; + break; case "EDITION_PROTO2": case 998: message.edition = 998; @@ -7641,6 +7814,488 @@ 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 new FeatureSupport instance using the specified properties. + * @function create + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport=} [properties] Properties to set + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport instance + */ + FeatureSupport.create = function create(properties) { + return new FeatureSupport(properties); + }; + + /** + * Encodes the specified FeatureSupport message. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport} message FeatureSupport message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FeatureSupport.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.editionIntroduced != null && Object.hasOwnProperty.call(message, "editionIntroduced")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.editionIntroduced); + if (message.editionDeprecated != null && Object.hasOwnProperty.call(message, "editionDeprecated")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.editionDeprecated); + if (message.deprecationWarning != null && Object.hasOwnProperty.call(message, "deprecationWarning")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.deprecationWarning); + if (message.editionRemoved != null && Object.hasOwnProperty.call(message, "editionRemoved")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.editionRemoved); + return writer; + }; + + /** + * Encodes the specified FeatureSupport message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport} message FeatureSupport message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FeatureSupport.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FeatureSupport.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FieldOptions.FeatureSupport(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.editionIntroduced = reader.int32(); + break; + } + case 2: { + message.editionDeprecated = reader.int32(); + break; + } + case 3: { + message.deprecationWarning = reader.string(); + break; + } + case 4: { + message.editionRemoved = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FeatureSupport.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FeatureSupport message. + * @function verify + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FeatureSupport.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.editionIntroduced != null && message.hasOwnProperty("editionIntroduced")) + switch (message.editionIntroduced) { + default: + return "editionIntroduced: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + if (message.editionDeprecated != null && message.hasOwnProperty("editionDeprecated")) + switch (message.editionDeprecated) { + default: + return "editionDeprecated: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + if (message.deprecationWarning != null && message.hasOwnProperty("deprecationWarning")) + if (!$util.isString(message.deprecationWarning)) + return "deprecationWarning: string expected"; + if (message.editionRemoved != null && message.hasOwnProperty("editionRemoved")) + switch (message.editionRemoved) { + default: + return "editionRemoved: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + return null; + }; + + /** + * 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; })(); @@ -8233,6 +8888,7 @@ * @property {boolean|null} [deprecated] EnumValueOptions deprecated * @property {google.protobuf.IFeatureSet|null} [features] EnumValueOptions features * @property {boolean|null} [debugRedact] EnumValueOptions debugRedact + * @property {google.protobuf.FieldOptions.IFeatureSupport|null} [featureSupport] EnumValueOptions featureSupport * @property {Array.|null} [uninterpretedOption] EnumValueOptions uninterpretedOption */ @@ -8276,6 +8932,14 @@ */ EnumValueOptions.prototype.debugRedact = false; + /** + * EnumValueOptions featureSupport. + * @member {google.protobuf.FieldOptions.IFeatureSupport|null|undefined} featureSupport + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.featureSupport = null; + /** * EnumValueOptions uninterpretedOption. * @member {Array.} uninterpretedOption @@ -8314,6 +8978,8 @@ $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); if (message.debugRedact != null && Object.hasOwnProperty.call(message, "debugRedact")) writer.uint32(/* id 3, wireType 0 =*/24).bool(message.debugRedact); + if (message.featureSupport != null && Object.hasOwnProperty.call(message, "featureSupport")) + $root.google.protobuf.FieldOptions.FeatureSupport.encode(message.featureSupport, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); if (message.uninterpretedOption != null && message.uninterpretedOption.length) for (var i = 0; i < message.uninterpretedOption.length; ++i) $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); @@ -8365,6 +9031,10 @@ message.debugRedact = reader.bool(); break; } + case 4: { + message.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.decode(reader, reader.uint32()); + break; + } case 999: { if (!(message.uninterpretedOption && message.uninterpretedOption.length)) message.uninterpretedOption = []; @@ -8417,6 +9087,11 @@ if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) if (typeof message.debugRedact !== "boolean") return "debugRedact: boolean expected"; + if (message.featureSupport != null && message.hasOwnProperty("featureSupport")) { + var error = $root.google.protobuf.FieldOptions.FeatureSupport.verify(message.featureSupport); + if (error) + return "featureSupport." + error; + } if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { if (!Array.isArray(message.uninterpretedOption)) return "uninterpretedOption: array expected"; @@ -8450,6 +9125,11 @@ } if (object.debugRedact != null) message.debugRedact = Boolean(object.debugRedact); + if (object.featureSupport != null) { + if (typeof object.featureSupport !== "object") + throw TypeError(".google.protobuf.EnumValueOptions.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.EnumValueOptions.uninterpretedOption: array expected"); @@ -8482,6 +9162,7 @@ object.deprecated = false; object.features = null; object.debugRedact = false; + object.featureSupport = null; } if (message.deprecated != null && message.hasOwnProperty("deprecated")) object.deprecated = message.deprecated; @@ -8489,6 +9170,8 @@ object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) object.debugRedact = message.debugRedact; + 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) @@ -9956,6 +10639,8 @@ * @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 + * @property {google.protobuf.FeatureSet.EnforceNamingStyle|null} [enforceNamingStyle] FeatureSet enforceNamingStyle + * @property {google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|null} [defaultSymbolVisibility] FeatureSet defaultSymbolVisibility */ /** @@ -10021,6 +10706,22 @@ */ FeatureSet.prototype.jsonFormat = 0; + /** + * FeatureSet enforceNamingStyle. + * @member {google.protobuf.FeatureSet.EnforceNamingStyle} enforceNamingStyle + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.enforceNamingStyle = 0; + + /** + * FeatureSet defaultSymbolVisibility. + * @member {google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility} defaultSymbolVisibility + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.defaultSymbolVisibility = 0; + /** * Creates a new FeatureSet instance using the specified properties. * @function create @@ -10057,6 +10758,10 @@ writer.uint32(/* id 5, wireType 0 =*/40).int32(message.messageEncoding); if (message.jsonFormat != null && Object.hasOwnProperty.call(message, "jsonFormat")) writer.uint32(/* id 6, wireType 0 =*/48).int32(message.jsonFormat); + if (message.enforceNamingStyle != null && Object.hasOwnProperty.call(message, "enforceNamingStyle")) + writer.uint32(/* id 7, wireType 0 =*/56).int32(message.enforceNamingStyle); + if (message.defaultSymbolVisibility != null && Object.hasOwnProperty.call(message, "defaultSymbolVisibility")) + writer.uint32(/* id 8, wireType 0 =*/64).int32(message.defaultSymbolVisibility); return writer; }; @@ -10117,6 +10822,14 @@ message.jsonFormat = reader.int32(); break; } + case 7: { + message.enforceNamingStyle = reader.int32(); + break; + } + case 8: { + message.defaultSymbolVisibility = reader.int32(); + break; + } default: reader.skipType(tag & 7); break; @@ -10207,6 +10920,26 @@ case 2: break; } + if (message.enforceNamingStyle != null && message.hasOwnProperty("enforceNamingStyle")) + switch (message.enforceNamingStyle) { + default: + return "enforceNamingStyle: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.defaultSymbolVisibility != null && message.hasOwnProperty("defaultSymbolVisibility")) + switch (message.defaultSymbolVisibility) { + default: + return "defaultSymbolVisibility: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + break; + } return null; }; @@ -10346,6 +11079,54 @@ message.jsonFormat = 2; break; } + switch (object.enforceNamingStyle) { + default: + if (typeof object.enforceNamingStyle === "number") { + message.enforceNamingStyle = object.enforceNamingStyle; + break; + } + break; + case "ENFORCE_NAMING_STYLE_UNKNOWN": + case 0: + message.enforceNamingStyle = 0; + break; + case "STYLE2024": + case 1: + message.enforceNamingStyle = 1; + break; + case "STYLE_LEGACY": + case 2: + message.enforceNamingStyle = 2; + break; + } + switch (object.defaultSymbolVisibility) { + default: + if (typeof object.defaultSymbolVisibility === "number") { + message.defaultSymbolVisibility = object.defaultSymbolVisibility; + break; + } + break; + case "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN": + case 0: + message.defaultSymbolVisibility = 0; + break; + case "EXPORT_ALL": + case 1: + message.defaultSymbolVisibility = 1; + break; + case "EXPORT_TOP_LEVEL": + case 2: + message.defaultSymbolVisibility = 2; + break; + case "LOCAL_ALL": + case 3: + message.defaultSymbolVisibility = 3; + break; + case "STRICT": + case 4: + message.defaultSymbolVisibility = 4; + break; + } return message; }; @@ -10369,6 +11150,8 @@ 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; + object.enforceNamingStyle = options.enums === String ? "ENFORCE_NAMING_STYLE_UNKNOWN" : 0; + object.defaultSymbolVisibility = options.enums === String ? "DEFAULT_SYMBOL_VISIBILITY_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; @@ -10382,6 +11165,10 @@ 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; + if (message.enforceNamingStyle != null && message.hasOwnProperty("enforceNamingStyle")) + object.enforceNamingStyle = options.enums === String ? $root.google.protobuf.FeatureSet.EnforceNamingStyle[message.enforceNamingStyle] === undefined ? message.enforceNamingStyle : $root.google.protobuf.FeatureSet.EnforceNamingStyle[message.enforceNamingStyle] : message.enforceNamingStyle; + if (message.defaultSymbolVisibility != null && message.hasOwnProperty("defaultSymbolVisibility")) + object.defaultSymbolVisibility = options.enums === String ? $root.google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility[message.defaultSymbolVisibility] === undefined ? message.defaultSymbolVisibility : $root.google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility[message.defaultSymbolVisibility] : message.defaultSymbolVisibility; return object; }; @@ -10509,6 +11296,219 @@ return values; })(); + /** + * EnforceNamingStyle enum. + * @name google.protobuf.FeatureSet.EnforceNamingStyle + * @enum {number} + * @property {number} ENFORCE_NAMING_STYLE_UNKNOWN=0 ENFORCE_NAMING_STYLE_UNKNOWN value + * @property {number} STYLE2024=1 STYLE2024 value + * @property {number} STYLE_LEGACY=2 STYLE_LEGACY value + */ + FeatureSet.EnforceNamingStyle = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ENFORCE_NAMING_STYLE_UNKNOWN"] = 0; + values[valuesById[1] = "STYLE2024"] = 1; + values[valuesById[2] = "STYLE_LEGACY"] = 2; + return values; + })(); + + FeatureSet.VisibilityFeature = (function() { + + /** + * Properties of a VisibilityFeature. + * @memberof google.protobuf.FeatureSet + * @interface IVisibilityFeature + */ + + /** + * Constructs a new VisibilityFeature. + * @memberof google.protobuf.FeatureSet + * @classdesc Represents a VisibilityFeature. + * @implements IVisibilityFeature + * @constructor + * @param {google.protobuf.FeatureSet.IVisibilityFeature=} [properties] Properties to set + */ + function VisibilityFeature(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 new VisibilityFeature instance using the specified properties. + * @function create + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature=} [properties] Properties to set + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature instance + */ + VisibilityFeature.create = function create(properties) { + return new VisibilityFeature(properties); + }; + + /** + * Encodes the specified VisibilityFeature message. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature} message VisibilityFeature message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + VisibilityFeature.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + return writer; + }; + + /** + * Encodes the specified VisibilityFeature message, length delimited. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature} message VisibilityFeature message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + VisibilityFeature.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + VisibilityFeature.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FeatureSet.VisibilityFeature(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + VisibilityFeature.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a VisibilityFeature message. + * @function verify + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + VisibilityFeature.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + return null; + }; + + /** + * Creates a VisibilityFeature message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + */ + VisibilityFeature.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FeatureSet.VisibilityFeature) + return object; + return new $root.google.protobuf.FeatureSet.VisibilityFeature(); + }; + + /** + * Creates a plain object from a VisibilityFeature message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.VisibilityFeature} message VisibilityFeature + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + VisibilityFeature.toObject = function toObject() { + return {}; + }; + + /** + * Converts this VisibilityFeature to JSON. + * @function toJSON + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @instance + * @returns {Object.} JSON object + */ + VisibilityFeature.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for VisibilityFeature + * @function getTypeUrl + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + VisibilityFeature.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FeatureSet.VisibilityFeature"; + }; + + /** + * DefaultSymbolVisibility enum. + * @name google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility + * @enum {number} + * @property {number} DEFAULT_SYMBOL_VISIBILITY_UNKNOWN=0 DEFAULT_SYMBOL_VISIBILITY_UNKNOWN value + * @property {number} EXPORT_ALL=1 EXPORT_ALL value + * @property {number} EXPORT_TOP_LEVEL=2 EXPORT_TOP_LEVEL value + * @property {number} LOCAL_ALL=3 LOCAL_ALL value + * @property {number} STRICT=4 STRICT value + */ + VisibilityFeature.DefaultSymbolVisibility = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN"] = 0; + values[valuesById[1] = "EXPORT_ALL"] = 1; + values[valuesById[2] = "EXPORT_TOP_LEVEL"] = 2; + values[valuesById[3] = "LOCAL_ALL"] = 3; + values[valuesById[4] = "STRICT"] = 4; + return values; + })(); + + return VisibilityFeature; + })(); + return FeatureSet; })(); @@ -10693,6 +11693,7 @@ default: return "minimumEdition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -10710,6 +11711,7 @@ default: return "maximumEdition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -10758,6 +11760,10 @@ case 0: message.minimumEdition = 0; break; + case "EDITION_LEGACY": + case 900: + message.minimumEdition = 900; + break; case "EDITION_PROTO2": case 998: message.minimumEdition = 998; @@ -10810,6 +11816,10 @@ case 0: message.maximumEdition = 0; break; + case "EDITION_LEGACY": + case 900: + message.maximumEdition = 900; + break; case "EDITION_PROTO2": case 998: message.maximumEdition = 998; @@ -10918,7 +11928,8 @@ * @memberof google.protobuf.FeatureSetDefaults * @interface IFeatureSetEditionDefault * @property {google.protobuf.Edition|null} [edition] FeatureSetEditionDefault edition - * @property {google.protobuf.IFeatureSet|null} [features] FeatureSetEditionDefault features + * @property {google.protobuf.IFeatureSet|null} [overridableFeatures] FeatureSetEditionDefault overridableFeatures + * @property {google.protobuf.IFeatureSet|null} [fixedFeatures] FeatureSetEditionDefault fixedFeatures */ /** @@ -10945,12 +11956,20 @@ FeatureSetEditionDefault.prototype.edition = 0; /** - * FeatureSetEditionDefault features. - * @member {google.protobuf.IFeatureSet|null|undefined} features + * 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 * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault * @instance */ - FeatureSetEditionDefault.prototype.features = null; + FeatureSetEditionDefault.prototype.fixedFeatures = null; /** * Creates a new FeatureSetEditionDefault instance using the specified properties. @@ -10976,10 +11995,12 @@ FeatureSetEditionDefault.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); - if (message.features != null && Object.hasOwnProperty.call(message, "features")) - $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); if (message.edition != null && Object.hasOwnProperty.call(message, "edition")) writer.uint32(/* id 3, wireType 0 =*/24).int32(message.edition); + if (message.overridableFeatures != null && Object.hasOwnProperty.call(message, "overridableFeatures")) + $root.google.protobuf.FeatureSet.encode(message.overridableFeatures, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.fixedFeatures != null && Object.hasOwnProperty.call(message, "fixedFeatures")) + $root.google.protobuf.FeatureSet.encode(message.fixedFeatures, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); return writer; }; @@ -11020,8 +12041,12 @@ message.edition = reader.int32(); break; } - case 2: { - message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + case 4: { + message.overridableFeatures = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + break; + } + case 5: { + message.fixedFeatures = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); break; } default: @@ -11064,6 +12089,7 @@ default: return "edition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -11076,10 +12102,15 @@ case 2147483647: break; } - if (message.features != null && message.hasOwnProperty("features")) { - var error = $root.google.protobuf.FeatureSet.verify(message.features); + if (message.overridableFeatures != null && message.hasOwnProperty("overridableFeatures")) { + var error = $root.google.protobuf.FeatureSet.verify(message.overridableFeatures); + if (error) + return "overridableFeatures." + error; + } + if (message.fixedFeatures != null && message.hasOwnProperty("fixedFeatures")) { + var error = $root.google.protobuf.FeatureSet.verify(message.fixedFeatures); if (error) - return "features." + error; + return "fixedFeatures." + error; } return null; }; @@ -11107,6 +12138,10 @@ case 0: message.edition = 0; break; + case "EDITION_LEGACY": + case 900: + message.edition = 900; + break; case "EDITION_PROTO2": case 998: message.edition = 998; @@ -11148,10 +12183,15 @@ message.edition = 2147483647; break; } - 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); + 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); } return message; }; @@ -11170,13 +12210,16 @@ 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; }; @@ -12391,6 +13434,22 @@ return GeneratedCodeInfo; })(); + /** + * SymbolVisibility enum. + * @name google.protobuf.SymbolVisibility + * @enum {number} + * @property {number} VISIBILITY_UNSET=0 VISIBILITY_UNSET value + * @property {number} VISIBILITY_LOCAL=1 VISIBILITY_LOCAL value + * @property {number} VISIBILITY_EXPORT=2 VISIBILITY_EXPORT value + */ + protobuf.SymbolVisibility = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "VISIBILITY_UNSET"] = 0; + values[valuesById[1] = "VISIBILITY_LOCAL"] = 1; + values[valuesById[2] = "VISIBILITY_EXPORT"] = 2; + return values; + })(); + protobuf.Any = (function() { /** @@ -68849,6 +69908,7 @@ * @interface ICommonLanguageSettings * @property {string|null} [referenceDocsUri] CommonLanguageSettings referenceDocsUri * @property {Array.|null} [destinations] CommonLanguageSettings destinations + * @property {google.api.ISelectiveGapicGeneration|null} [selectiveGapicGeneration] CommonLanguageSettings selectiveGapicGeneration */ /** @@ -68883,6 +69943,14 @@ */ 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 new CommonLanguageSettings instance using the specified properties. * @function create @@ -68915,6 +69983,8 @@ writer.int32(message.destinations[i]); writer.ldelim(); } + if (message.selectiveGapicGeneration != null && Object.hasOwnProperty.call(message, "selectiveGapicGeneration")) + $root.google.api.SelectiveGapicGeneration.encode(message.selectiveGapicGeneration, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); return writer; }; @@ -68966,6 +70036,10 @@ message.destinations.push(reader.int32()); break; } + case 3: { + message.selectiveGapicGeneration = $root.google.api.SelectiveGapicGeneration.decode(reader, reader.uint32()); + break; + } default: reader.skipType(tag & 7); break; @@ -69017,6 +70091,11 @@ break; } } + if (message.selectiveGapicGeneration != null && message.hasOwnProperty("selectiveGapicGeneration")) { + var error = $root.google.api.SelectiveGapicGeneration.verify(message.selectiveGapicGeneration); + if (error) + return "selectiveGapicGeneration." + error; + } return null; }; @@ -69059,6 +70138,11 @@ 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; }; @@ -69077,8 +70161,10 @@ 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) { @@ -69086,6 +70172,8 @@ 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; }; @@ -70908,6 +71996,7 @@ * @memberof google.api * @interface IPythonSettings * @property {google.api.ICommonLanguageSettings|null} [common] PythonSettings common + * @property {google.api.PythonSettings.IExperimentalFeatures|null} [experimentalFeatures] PythonSettings experimentalFeatures */ /** @@ -70933,6 +72022,14 @@ */ 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 new PythonSettings instance using the specified properties. * @function create @@ -70959,6 +72056,8 @@ writer = $Writer.create(); if (message.common != null && Object.hasOwnProperty.call(message, "common")) $root.google.api.CommonLanguageSettings.encode(message.common, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.experimentalFeatures != null && Object.hasOwnProperty.call(message, "experimentalFeatures")) + $root.google.api.PythonSettings.ExperimentalFeatures.encode(message.experimentalFeatures, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); return writer; }; @@ -70999,6 +72098,10 @@ message.common = $root.google.api.CommonLanguageSettings.decode(reader, reader.uint32()); break; } + case 2: { + message.experimentalFeatures = $root.google.api.PythonSettings.ExperimentalFeatures.decode(reader, reader.uint32()); + break; + } default: reader.skipType(tag & 7); break; @@ -71039,6 +72142,11 @@ if (error) return "common." + error; } + if (message.experimentalFeatures != null && message.hasOwnProperty("experimentalFeatures")) { + var error = $root.google.api.PythonSettings.ExperimentalFeatures.verify(message.experimentalFeatures); + if (error) + return "experimentalFeatures." + error; + } return null; }; @@ -71059,6 +72167,11 @@ 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; }; @@ -71075,10 +72188,14 @@ 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; }; @@ -71108,6 +72225,258 @@ 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 + * @property {boolean|null} [unversionedPackageDisabled] ExperimentalFeatures unversionedPackageDisabled + */ + + /** + * 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; + + /** + * ExperimentalFeatures unversionedPackageDisabled. + * @member {boolean} unversionedPackageDisabled + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @instance + */ + ExperimentalFeatures.prototype.unversionedPackageDisabled = false; + + /** + * Creates a new ExperimentalFeatures instance using the specified properties. + * @function create + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures=} [properties] Properties to set + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures instance + */ + ExperimentalFeatures.create = function create(properties) { + return new ExperimentalFeatures(properties); + }; + + /** + * Encodes the specified ExperimentalFeatures message. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @function encode + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures} message ExperimentalFeatures message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExperimentalFeatures.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.restAsyncIoEnabled != null && Object.hasOwnProperty.call(message, "restAsyncIoEnabled")) + writer.uint32(/* id 1, wireType 0 =*/8).bool(message.restAsyncIoEnabled); + if (message.protobufPythonicTypesEnabled != null && Object.hasOwnProperty.call(message, "protobufPythonicTypesEnabled")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.protobufPythonicTypesEnabled); + if (message.unversionedPackageDisabled != null && Object.hasOwnProperty.call(message, "unversionedPackageDisabled")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.unversionedPackageDisabled); + return writer; + }; + + /** + * Encodes the specified ExperimentalFeatures message, length delimited. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures} message ExperimentalFeatures message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExperimentalFeatures.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer. + * @function decode + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExperimentalFeatures.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.PythonSettings.ExperimentalFeatures(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.restAsyncIoEnabled = reader.bool(); + break; + } + case 2: { + message.protobufPythonicTypesEnabled = reader.bool(); + break; + } + case 3: { + message.unversionedPackageDisabled = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExperimentalFeatures.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ExperimentalFeatures message. + * @function verify + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExperimentalFeatures.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.restAsyncIoEnabled != null && message.hasOwnProperty("restAsyncIoEnabled")) + if (typeof message.restAsyncIoEnabled !== "boolean") + return "restAsyncIoEnabled: boolean expected"; + if (message.protobufPythonicTypesEnabled != null && message.hasOwnProperty("protobufPythonicTypesEnabled")) + if (typeof message.protobufPythonicTypesEnabled !== "boolean") + return "protobufPythonicTypesEnabled: boolean expected"; + if (message.unversionedPackageDisabled != null && message.hasOwnProperty("unversionedPackageDisabled")) + if (typeof message.unversionedPackageDisabled !== "boolean") + return "unversionedPackageDisabled: boolean expected"; + return null; + }; + + /** + * 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); + if (object.unversionedPackageDisabled != null) + message.unversionedPackageDisabled = Boolean(object.unversionedPackageDisabled); + 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; + object.unversionedPackageDisabled = false; + } + if (message.restAsyncIoEnabled != null && message.hasOwnProperty("restAsyncIoEnabled")) + object.restAsyncIoEnabled = message.restAsyncIoEnabled; + if (message.protobufPythonicTypesEnabled != null && message.hasOwnProperty("protobufPythonicTypesEnabled")) + object.protobufPythonicTypesEnabled = message.protobufPythonicTypesEnabled; + if (message.unversionedPackageDisabled != null && message.hasOwnProperty("unversionedPackageDisabled")) + object.unversionedPackageDisabled = message.unversionedPackageDisabled; + 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; })(); @@ -71984,6 +73353,7 @@ * @memberof google.api * @interface IGoSettings * @property {google.api.ICommonLanguageSettings|null} [common] GoSettings common + * @property {Object.|null} [renamedServices] GoSettings renamedServices */ /** @@ -71995,6 +73365,7 @@ * @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) @@ -72009,6 +73380,14 @@ */ GoSettings.prototype.common = null; + /** + * GoSettings renamedServices. + * @member {Object.} renamedServices + * @memberof google.api.GoSettings + * @instance + */ + GoSettings.prototype.renamedServices = $util.emptyObject; + /** * Creates a new GoSettings instance using the specified properties. * @function create @@ -72035,6 +73414,9 @@ writer = $Writer.create(); if (message.common != null && Object.hasOwnProperty.call(message, "common")) $root.google.api.CommonLanguageSettings.encode(message.common, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.renamedServices != null && Object.hasOwnProperty.call(message, "renamedServices")) + for (var keys = Object.keys(message.renamedServices), i = 0; i < keys.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.renamedServices[keys[i]]).ldelim(); return writer; }; @@ -72065,7 +73447,7 @@ GoSettings.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.GoSettings(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.GoSettings(), key, value; while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -72075,6 +73457,29 @@ message.common = $root.google.api.CommonLanguageSettings.decode(reader, reader.uint32()); break; } + case 2: { + if (message.renamedServices === $util.emptyObject) + message.renamedServices = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.renamedServices[key] = value; + break; + } default: reader.skipType(tag & 7); break; @@ -72115,6 +73520,14 @@ if (error) return "common." + error; } + if (message.renamedServices != null && message.hasOwnProperty("renamedServices")) { + if (!$util.isObject(message.renamedServices)) + return "renamedServices: object expected"; + var key = Object.keys(message.renamedServices); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.renamedServices[key[i]])) + return "renamedServices: string{k:string} expected"; + } return null; }; @@ -72135,6 +73548,13 @@ 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; }; @@ -72151,10 +73571,18 @@ 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; }; @@ -72793,6 +74221,251 @@ 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 new SelectiveGapicGeneration instance using the specified properties. + * @function create + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration=} [properties] Properties to set + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration instance + */ + SelectiveGapicGeneration.create = function create(properties) { + return new SelectiveGapicGeneration(properties); + }; + + /** + * Encodes the specified SelectiveGapicGeneration message. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @function encode + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration} message SelectiveGapicGeneration message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SelectiveGapicGeneration.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.methods != null && message.methods.length) + for (var i = 0; i < message.methods.length; ++i) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.methods[i]); + if (message.generateOmittedAsInternal != null && Object.hasOwnProperty.call(message, "generateOmittedAsInternal")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.generateOmittedAsInternal); + return writer; + }; + + /** + * Encodes the specified SelectiveGapicGeneration message, length delimited. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration} message SelectiveGapicGeneration message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SelectiveGapicGeneration.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer. + * @function decode + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SelectiveGapicGeneration.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.SelectiveGapicGeneration(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.methods && message.methods.length)) + message.methods = []; + message.methods.push(reader.string()); + break; + } + case 2: { + message.generateOmittedAsInternal = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SelectiveGapicGeneration.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SelectiveGapicGeneration message. + * @function verify + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SelectiveGapicGeneration.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.methods != null && message.hasOwnProperty("methods")) { + if (!Array.isArray(message.methods)) + return "methods: array expected"; + for (var i = 0; i < message.methods.length; ++i) + if (!$util.isString(message.methods[i])) + return "methods: string[] expected"; + } + if (message.generateOmittedAsInternal != null && message.hasOwnProperty("generateOmittedAsInternal")) + if (typeof message.generateOmittedAsInternal !== "boolean") + return "generateOmittedAsInternal: boolean expected"; + return null; + }; + + /** + * 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 diff --git a/packages/google-analytics-data/protos/protos.json b/packages/google-analytics-data/protos/protos.json index 1fbae0bb7ac9..ef3f57d32c5b 100644 --- a/packages/google-analytics-data/protos/protos.json +++ b/packages/google-analytics-data/protos/protos.json @@ -33,12 +33,19 @@ "type": "FileDescriptorProto", "id": 1 } - } + }, + "extensions": [ + [ + 536000000, + 536000000 + ] + ] }, "Edition": { "edition": "proto2", "values": { "EDITION_UNKNOWN": 0, + "EDITION_LEGACY": 900, "EDITION_PROTO2": 998, "EDITION_PROTO3": 999, "EDITION_2023": 1000, @@ -77,6 +84,11 @@ "type": "int32", "id": 11 }, + "optionDependency": { + "rule": "repeated", + "type": "string", + "id": 15 + }, "messageType": { "rule": "repeated", "type": "DescriptorProto", @@ -165,6 +177,10 @@ "rule": "repeated", "type": "string", "id": 10 + }, + "visibility": { + "type": "SymbolVisibility", + "id": 11 } }, "nested": { @@ -390,6 +406,10 @@ "rule": "repeated", "type": "string", "id": 5 + }, + "visibility": { + "type": "SymbolVisibility", + "id": 6 } }, "nested": { @@ -440,7 +460,14 @@ "type": "ServiceOptions", "id": 3 } - } + }, + "reserved": [ + [ + 4, + 4 + ], + "stream" + ] }, "MethodDescriptorProto": { "edition": "proto2", @@ -604,6 +631,7 @@ 42, 42 ], + "php_generic_services", [ 38, 38 @@ -739,7 +767,8 @@ "type": "bool", "id": 10, "options": { - "default": false + "default": false, + "deprecated": true } }, "debugRedact": { @@ -767,6 +796,10 @@ "type": "FeatureSet", "id": 21 }, + "featureSupport": { + "type": "FeatureSupport", + "id": 22 + }, "uninterpretedOption": { "rule": "repeated", "type": "UninterpretedOption", @@ -836,6 +869,26 @@ "id": 2 } } + }, + "FeatureSupport": { + "fields": { + "editionIntroduced": { + "type": "Edition", + "id": 1 + }, + "editionDeprecated": { + "type": "Edition", + "id": 2 + }, + "deprecationWarning": { + "type": "string", + "id": 3 + }, + "editionRemoved": { + "type": "Edition", + "id": 4 + } + } } } }, @@ -924,6 +977,10 @@ "default": false } }, + "featureSupport": { + "type": "FieldOptions.FeatureSupport", + "id": 4 + }, "uninterpretedOption": { "rule": "repeated", "type": "UninterpretedOption", @@ -1066,6 +1123,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_2023", "edition_defaults.value": "EXPLICIT" } @@ -1076,6 +1134,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "OPEN" } @@ -1086,6 +1145,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "PACKED" } @@ -1096,6 +1156,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "VERIFY" } @@ -1106,7 +1167,8 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", - "edition_defaults.edition": "EDITION_PROTO2", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_LEGACY", "edition_defaults.value": "LENGTH_PREFIXED" } }, @@ -1116,27 +1178,38 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "ALLOW" } + }, + "enforceNamingStyle": { + "type": "EnforceNamingStyle", + "id": 7, + "options": { + "retention": "RETENTION_SOURCE", + "targets": "TARGET_TYPE_METHOD", + "feature_support.edition_introduced": "EDITION_2024", + "edition_defaults.edition": "EDITION_2024", + "edition_defaults.value": "STYLE2024" + } + }, + "defaultSymbolVisibility": { + "type": "VisibilityFeature.DefaultSymbolVisibility", + "id": 8, + "options": { + "retention": "RETENTION_SOURCE", + "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2024", + "edition_defaults.edition": "EDITION_2024", + "edition_defaults.value": "EXPORT_TOP_LEVEL" + } } }, "extensions": [ [ 1000, - 1000 - ], - [ - 1001, - 1001 - ], - [ - 1002, - 1002 - ], - [ - 9990, - 9990 + 9994 ], [ 9995, @@ -1181,7 +1254,13 @@ "UTF8_VALIDATION_UNKNOWN": 0, "VERIFY": 2, "NONE": 3 - } + }, + "reserved": [ + [ + 1, + 1 + ] + ] }, "MessageEncoding": { "values": { @@ -1196,6 +1275,33 @@ "ALLOW": 1, "LEGACY_BEST_EFFORT": 2 } + }, + "EnforceNamingStyle": { + "values": { + "ENFORCE_NAMING_STYLE_UNKNOWN": 0, + "STYLE2024": 1, + "STYLE_LEGACY": 2 + } + }, + "VisibilityFeature": { + "fields": {}, + "reserved": [ + [ + 1, + 536870911 + ] + ], + "nested": { + "DefaultSymbolVisibility": { + "values": { + "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN": 0, + "EXPORT_ALL": 1, + "EXPORT_TOP_LEVEL": 2, + "LOCAL_ALL": 3, + "STRICT": 4 + } + } + } } } }, @@ -1223,11 +1329,26 @@ "type": "Edition", "id": 3 }, - "features": { + "overridableFeatures": { "type": "FeatureSet", - "id": 2 + "id": 4 + }, + "fixedFeatures": { + "type": "FeatureSet", + "id": 5 } - } + }, + "reserved": [ + [ + 1, + 1 + ], + [ + 2, + 2 + ], + "features" + ] } } }, @@ -1240,6 +1361,12 @@ "id": 1 } }, + "extensions": [ + [ + 536000000, + 536000000 + ] + ], "nested": { "Location": { "fields": { @@ -1325,6 +1452,14 @@ } } }, + "SymbolVisibility": { + "edition": "proto2", + "values": { + "VISIBILITY_UNSET": 0, + "VISIBILITY_LOCAL": 1, + "VISIBILITY_EXPORT": 2 + } + }, "Any": { "fields": { "type_url": { @@ -6539,8 +6674,7 @@ "java_multiple_files": true, "java_outer_classname": "ResourceProto", "java_package": "com.google.api", - "objc_class_prefix": "GAPI", - "cc_enable_arenas": true + "objc_class_prefix": "GAPI" }, "nested": { "http": { @@ -6664,6 +6798,10 @@ "rule": "repeated", "type": "ClientLibraryDestination", "id": 2 + }, + "selectiveGapicGeneration": { + "type": "SelectiveGapicGeneration", + "id": 3 } } }, @@ -6804,6 +6942,28 @@ "common": { "type": "CommonLanguageSettings", "id": 1 + }, + "experimentalFeatures": { + "type": "ExperimentalFeatures", + "id": 2 + } + }, + "nested": { + "ExperimentalFeatures": { + "fields": { + "restAsyncIoEnabled": { + "type": "bool", + "id": 1 + }, + "protobufPythonicTypesEnabled": { + "type": "bool", + "id": 2 + }, + "unversionedPackageDisabled": { + "type": "bool", + "id": 3 + } + } } } }, @@ -6861,6 +7021,11 @@ "common": { "type": "CommonLanguageSettings", "id": 1 + }, + "renamedServices": { + "keyType": "string", + "type": "string", + "id": 2 } } }, @@ -6922,6 +7087,19 @@ "PACKAGE_MANAGER": 20 } }, + "SelectiveGapicGeneration": { + "fields": { + "methods": { + "rule": "repeated", + "type": "string", + "id": 1 + }, + "generateOmittedAsInternal": { + "type": "bool", + "id": 2 + } + } + }, "LaunchStage": { "values": { "LAUNCH_STAGE_UNSPECIFIED": 0, @@ -7043,6 +7221,7 @@ "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/packages/google-analytics-data/src/index.ts b/packages/google-analytics-data/src/index.ts index 2d76b05e1e8e..f43adab04927 100644 --- a/packages/google-analytics-data/src/index.ts +++ b/packages/google-analytics-data/src/index.ts @@ -1,4 +1,4 @@ -// Copyright 2025 Google LLC +// Copyright 2026 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/packages/google-analytics-data/src/v1alpha/alpha_analytics_data_client.ts b/packages/google-analytics-data/src/v1alpha/alpha_analytics_data_client.ts index b2010ffa7be5..70c9c91d593e 100644 --- a/packages/google-analytics-data/src/v1alpha/alpha_analytics_data_client.ts +++ b/packages/google-analytics-data/src/v1alpha/alpha_analytics_data_client.ts @@ -18,11 +18,20 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +53,7 @@ export class AlphaAnalyticsDataClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('data'); @@ -57,10 +66,10 @@ export class AlphaAnalyticsDataClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - alphaAnalyticsDataStub?: Promise<{[name: string]: Function}>; + alphaAnalyticsDataStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of AlphaAnalyticsDataClient. @@ -101,21 +110,42 @@ export class AlphaAnalyticsDataClient { * const client = new AlphaAnalyticsDataClient({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 AlphaAnalyticsDataClient; - 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 = 'analyticsdata.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -140,7 +170,7 @@ export class AlphaAnalyticsDataClient { 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; @@ -154,10 +184,7 @@ export class AlphaAnalyticsDataClient { } // 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 { @@ -179,22 +206,22 @@ export class AlphaAnalyticsDataClient { // Create useful helper objects for these. this.pathTemplates = { audienceListPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/audienceLists/{audience_list}' + 'properties/{property}/audienceLists/{audience_list}', ), metadataPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/metadata' + 'properties/{property}/metadata', ), propertyPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}' + 'properties/{property}', ), propertyQuotasSnapshotPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/propertyQuotasSnapshot' + 'properties/{property}/propertyQuotasSnapshot', ), recurringAudienceListPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/recurringAudienceLists/{recurring_audience_list}' + 'properties/{property}/recurringAudienceLists/{recurring_audience_list}', ), reportTaskPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/reportTasks/{report_task}' + 'properties/{property}/reportTasks/{report_task}', ), }; @@ -202,12 +229,21 @@ export class AlphaAnalyticsDataClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listAudienceLists: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'audienceLists'), - listRecurringAudienceLists: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'recurringAudienceLists'), - listReportTasks: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'reportTasks') + listAudienceLists: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'audienceLists', + ), + listRecurringAudienceLists: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'recurringAudienceLists', + ), + listReportTasks: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'reportTasks', + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -216,37 +252,48 @@ export class AlphaAnalyticsDataClient { // 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 = []; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const createAudienceListResponse = protoFilesRoot.lookup( - '.google.analytics.data.v1alpha.AudienceList') as gax.protobuf.Type; + '.google.analytics.data.v1alpha.AudienceList', + ) as gax.protobuf.Type; const createAudienceListMetadata = protoFilesRoot.lookup( - '.google.analytics.data.v1alpha.AudienceListMetadata') as gax.protobuf.Type; + '.google.analytics.data.v1alpha.AudienceListMetadata', + ) as gax.protobuf.Type; const createReportTaskResponse = protoFilesRoot.lookup( - '.google.analytics.data.v1alpha.ReportTask') as gax.protobuf.Type; + '.google.analytics.data.v1alpha.ReportTask', + ) as gax.protobuf.Type; const createReportTaskMetadata = protoFilesRoot.lookup( - '.google.analytics.data.v1alpha.ReportTaskMetadata') as gax.protobuf.Type; + '.google.analytics.data.v1alpha.ReportTaskMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { createAudienceList: new this._gaxModule.LongrunningDescriptor( this.operationsClient, createAudienceListResponse.decode.bind(createAudienceListResponse), - createAudienceListMetadata.decode.bind(createAudienceListMetadata)), + createAudienceListMetadata.decode.bind(createAudienceListMetadata), + ), createReportTask: new this._gaxModule.LongrunningDescriptor( this.operationsClient, createReportTaskResponse.decode.bind(createReportTaskResponse), - createReportTaskMetadata.decode.bind(createReportTaskMetadata)) + createReportTaskMetadata.decode.bind(createReportTaskMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.analytics.data.v1alpha.AlphaAnalyticsData', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.analytics.data.v1alpha.AlphaAnalyticsData', + 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 @@ -277,28 +324,50 @@ export class AlphaAnalyticsDataClient { // Put together the "service stub" for // google.analytics.data.v1alpha.AlphaAnalyticsData. this.alphaAnalyticsDataStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.analytics.data.v1alpha.AlphaAnalyticsData') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.analytics.data.v1alpha.AlphaAnalyticsData, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.analytics.data.v1alpha.AlphaAnalyticsData', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.analytics.data.v1alpha + .AlphaAnalyticsData, + 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 alphaAnalyticsDataStubMethods = - ['runFunnelReport', 'createAudienceList', 'queryAudienceList', 'getAudienceList', 'listAudienceLists', 'createRecurringAudienceList', 'getRecurringAudienceList', 'listRecurringAudienceLists', 'getPropertyQuotasSnapshot', 'createReportTask', 'queryReportTask', 'getReportTask', 'listReportTasks', 'runReport', 'getMetadata']; + const alphaAnalyticsDataStubMethods = [ + 'runFunnelReport', + 'createAudienceList', + 'queryAudienceList', + 'getAudienceList', + 'listAudienceLists', + 'createRecurringAudienceList', + 'getRecurringAudienceList', + 'listRecurringAudienceLists', + 'getPropertyQuotasSnapshot', + 'createReportTask', + 'queryReportTask', + 'getReportTask', + 'listReportTasks', + 'runReport', + 'getMetadata', + ]; for (const methodName of alphaAnalyticsDataStubMethods) { const callPromise = this.alphaAnalyticsDataStub.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] || @@ -308,7 +377,7 @@ export class AlphaAnalyticsDataClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -323,8 +392,14 @@ export class AlphaAnalyticsDataClient { * @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 'analyticsdata.googleapis.com'; } @@ -335,8 +410,14 @@ export class AlphaAnalyticsDataClient { * @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 'analyticsdata.googleapis.com'; } @@ -369,7 +450,7 @@ export class AlphaAnalyticsDataClient { static get scopes() { return [ 'https://www.googleapis.com/auth/analytics', - 'https://www.googleapis.com/auth/analytics.readonly' + 'https://www.googleapis.com/auth/analytics.readonly', ]; } @@ -379,8 +460,9 @@ export class AlphaAnalyticsDataClient { * 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; @@ -391,1607 +473,2198 @@ export class AlphaAnalyticsDataClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Returns a customized funnel report of your Google Analytics event data. The - * data returned from the API is as a table with columns for the requested - * dimensions and metrics. - * - * Funnel exploration lets you visualize the steps your users take to complete - * a task and quickly see how well they are succeeding or failing at each - * step. For example, how do prospects become shoppers and then become buyers? - * How do one time buyers become repeat buyers? With this information, you can - * improve inefficient or abandoned customer journeys. To learn more, see [GA4 - * Funnel Explorations](https://support.google.com/analytics/answer/9327974). - * - * This method is introduced at alpha stability with the intention of - * gathering feedback on syntax and capabilities before entering beta. To give - * your feedback on this API, complete the [Google Analytics Data API Funnel - * Reporting - * Feedback](https://docs.google.com/forms/d/e/1FAIpQLSdwOlQDJAUoBiIgUZZ3S_Lwi8gr7Bb0k1jhvc-DEg7Rol3UjA/viewform). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} [request.property] - * Optional. A Google Analytics property identifier whose events are tracked. - * Specified in the URL path and not the body. To learn more, see [where to - * find your Property - * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id). - * Within a batch request, this property should either be unspecified or - * consistent with the batch-level property. - * - * Example: properties/1234 - * @param {number[]} [request.dateRanges] - * Optional. Date ranges of data to read. If multiple date ranges are - * requested, each response row will contain a zero based date range index. If - * two date ranges overlap, the event data for the overlapping days is - * included in the response rows for both date ranges. - * @param {google.analytics.data.v1alpha.Funnel} [request.funnel] - * Optional. The configuration of this request's funnel. This funnel - * configuration is required. - * @param {google.analytics.data.v1alpha.FunnelBreakdown} [request.funnelBreakdown] - * Optional. If specified, this breakdown adds a dimension to the funnel table - * sub report response. This breakdown dimension expands each funnel step to - * the unique values of the breakdown dimension. For example, a breakdown by - * the `deviceCategory` dimension will create rows for `mobile`, `tablet`, - * `desktop`, and the total. - * @param {google.analytics.data.v1alpha.FunnelNextAction} [request.funnelNextAction] - * Optional. If specified, next action adds a dimension to the funnel - * visualization sub report response. This next action dimension expands each - * funnel step to the unique values of the next action. For example a next - * action of the `eventName` dimension will create rows for several events - * (for example `session_start` & `click`) and the total. - * - * Next action only supports `eventName` and most Page / Screen dimensions - * like `pageTitle` and `pagePath`. - * @param {google.analytics.data.v1alpha.RunFunnelReportRequest.FunnelVisualizationType} [request.funnelVisualizationType] - * Optional. The funnel visualization type controls the dimensions present in - * the funnel visualization sub report response. If not specified, - * `STANDARD_FUNNEL` is used. - * @param {number[]} [request.segments] - * Optional. The configurations of segments. Segments are subsets of a - * property's data. In a funnel report with segments, the funnel is evaluated - * in each segment. - * - * Each segment specified in this request - * produces a separate row in the response; in the response, each segment - * identified by its name. - * - * The segments parameter is optional. Requests are limited to 4 segments. - * @param {number} [request.limit] - * Optional. The number of rows to return. If unspecified, 10,000 rows are - * returned. The API returns a maximum of 250,000 rows per request, no matter - * how many you ask for. `limit` must be positive. - * - * The API can also return fewer rows than the requested `limit`, if there - * aren't as many dimension values as the `limit`. - * @param {google.analytics.data.v1alpha.FilterExpression} [request.dimensionFilter] - * Optional. Dimension filters allow you to ask for only specific dimension - * values in the report. To learn more, see [Creating a Report: Dimension - * Filters](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#dimension_filters) - * for examples. Metrics cannot be used in this filter. - * @param {boolean} [request.returnPropertyQuota] - * Optional. Toggles whether to return the current state of this Analytics - * Property's quota. Quota is returned in [PropertyQuota](#PropertyQuota). - * @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.analytics.data.v1alpha.RunFunnelReportResponse|RunFunnelReportResponse}. - * 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/v1alpha/alpha_analytics_data.run_funnel_report.js - * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_RunFunnelReport_async - */ + /** + * Returns a customized funnel report of your Google Analytics event data. The + * data returned from the API is as a table with columns for the requested + * dimensions and metrics. + * + * Funnel exploration lets you visualize the steps your users take to complete + * a task and quickly see how well they are succeeding or failing at each + * step. For example, how do prospects become shoppers and then become buyers? + * How do one time buyers become repeat buyers? With this information, you can + * improve inefficient or abandoned customer journeys. To learn more, see [GA4 + * Funnel Explorations](https://support.google.com/analytics/answer/9327974). + * + * This method is introduced at alpha stability with the intention of + * gathering feedback on syntax and capabilities before entering beta. To give + * your feedback on this API, complete the [Google Analytics Data API Funnel + * Reporting + * Feedback](https://docs.google.com/forms/d/e/1FAIpQLSdwOlQDJAUoBiIgUZZ3S_Lwi8gr7Bb0k1jhvc-DEg7Rol3UjA/viewform). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} [request.property] + * Optional. A Google Analytics property identifier whose events are tracked. + * Specified in the URL path and not the body. To learn more, see [where to + * find your Property + * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id). + * Within a batch request, this property should either be unspecified or + * consistent with the batch-level property. + * + * Example: properties/1234 + * @param {number[]} [request.dateRanges] + * Optional. Date ranges of data to read. If multiple date ranges are + * requested, each response row will contain a zero based date range index. If + * two date ranges overlap, the event data for the overlapping days is + * included in the response rows for both date ranges. + * @param {google.analytics.data.v1alpha.Funnel} [request.funnel] + * Optional. The configuration of this request's funnel. This funnel + * configuration is required. + * @param {google.analytics.data.v1alpha.FunnelBreakdown} [request.funnelBreakdown] + * Optional. If specified, this breakdown adds a dimension to the funnel table + * sub report response. This breakdown dimension expands each funnel step to + * the unique values of the breakdown dimension. For example, a breakdown by + * the `deviceCategory` dimension will create rows for `mobile`, `tablet`, + * `desktop`, and the total. + * @param {google.analytics.data.v1alpha.FunnelNextAction} [request.funnelNextAction] + * Optional. If specified, next action adds a dimension to the funnel + * visualization sub report response. This next action dimension expands each + * funnel step to the unique values of the next action. For example a next + * action of the `eventName` dimension will create rows for several events + * (for example `session_start` & `click`) and the total. + * + * Next action only supports `eventName` and most Page / Screen dimensions + * like `pageTitle` and `pagePath`. + * @param {google.analytics.data.v1alpha.RunFunnelReportRequest.FunnelVisualizationType} [request.funnelVisualizationType] + * Optional. The funnel visualization type controls the dimensions present in + * the funnel visualization sub report response. If not specified, + * `STANDARD_FUNNEL` is used. + * @param {number[]} [request.segments] + * Optional. The configurations of segments. Segments are subsets of a + * property's data. In a funnel report with segments, the funnel is evaluated + * in each segment. + * + * Each segment specified in this request + * produces a separate row in the response; in the response, each segment + * identified by its name. + * + * The segments parameter is optional. Requests are limited to 4 segments. + * @param {number} [request.limit] + * Optional. The number of rows to return. If unspecified, 10,000 rows are + * returned. The API returns a maximum of 250,000 rows per request, no matter + * how many you ask for. `limit` must be positive. + * + * The API can also return fewer rows than the requested `limit`, if there + * aren't as many dimension values as the `limit`. + * @param {google.analytics.data.v1alpha.FilterExpression} [request.dimensionFilter] + * Optional. Dimension filters allow you to ask for only specific dimension + * values in the report. To learn more, see [Creating a Report: Dimension + * Filters](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#dimension_filters) + * for examples. Metrics cannot be used in this filter. + * @param {boolean} [request.returnPropertyQuota] + * Optional. Toggles whether to return the current state of this Analytics + * Property's quota. Quota is returned in [PropertyQuota](#PropertyQuota). + * @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.analytics.data.v1alpha.RunFunnelReportResponse|RunFunnelReportResponse}. + * 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/v1alpha/alpha_analytics_data.run_funnel_report.js + * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_RunFunnelReport_async + */ runFunnelReport( - request?: protos.google.analytics.data.v1alpha.IRunFunnelReportRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.data.v1alpha.IRunFunnelReportResponse, - protos.google.analytics.data.v1alpha.IRunFunnelReportRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.data.v1alpha.IRunFunnelReportRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IRunFunnelReportResponse, + protos.google.analytics.data.v1alpha.IRunFunnelReportRequest | undefined, + {} | undefined, + ] + >; runFunnelReport( - request: protos.google.analytics.data.v1alpha.IRunFunnelReportRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.data.v1alpha.IRunFunnelReportResponse, - protos.google.analytics.data.v1alpha.IRunFunnelReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.IRunFunnelReportRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.data.v1alpha.IRunFunnelReportResponse, + | protos.google.analytics.data.v1alpha.IRunFunnelReportRequest + | null + | undefined, + {} | null | undefined + >, + ): void; runFunnelReport( - request: protos.google.analytics.data.v1alpha.IRunFunnelReportRequest, - callback: Callback< - protos.google.analytics.data.v1alpha.IRunFunnelReportResponse, - protos.google.analytics.data.v1alpha.IRunFunnelReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.IRunFunnelReportRequest, + callback: Callback< + protos.google.analytics.data.v1alpha.IRunFunnelReportResponse, + | protos.google.analytics.data.v1alpha.IRunFunnelReportRequest + | null + | undefined, + {} | null | undefined + >, + ): void; runFunnelReport( - request?: protos.google.analytics.data.v1alpha.IRunFunnelReportRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.data.v1alpha.IRunFunnelReportResponse, - protos.google.analytics.data.v1alpha.IRunFunnelReportRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.data.v1alpha.IRunFunnelReportRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.data.v1alpha.IRunFunnelReportResponse, - protos.google.analytics.data.v1alpha.IRunFunnelReportRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.data.v1alpha.IRunFunnelReportResponse, - protos.google.analytics.data.v1alpha.IRunFunnelReportRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.data.v1alpha.IRunFunnelReportRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.data.v1alpha.IRunFunnelReportResponse, + | protos.google.analytics.data.v1alpha.IRunFunnelReportRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IRunFunnelReportResponse, + protos.google.analytics.data.v1alpha.IRunFunnelReportRequest | 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({ - 'property': request.property ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + property: request.property ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('runFunnelReport request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.data.v1alpha.IRunFunnelReportResponse, - protos.google.analytics.data.v1alpha.IRunFunnelReportRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.data.v1alpha.IRunFunnelReportResponse, + | protos.google.analytics.data.v1alpha.IRunFunnelReportRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('runFunnelReport response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.runFunnelReport(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.data.v1alpha.IRunFunnelReportResponse, - protos.google.analytics.data.v1alpha.IRunFunnelReportRequest|undefined, - {}|undefined - ]) => { - this._log.info('runFunnelReport response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .runFunnelReport(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.data.v1alpha.IRunFunnelReportResponse, + ( + | protos.google.analytics.data.v1alpha.IRunFunnelReportRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('runFunnelReport response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieves an audience list of users. After creating an audience, the users - * are not immediately available for listing. First, a request to - * `CreateAudienceList` is necessary to create an audience list of users, and - * then second, this method is used to retrieve the users in the audience - * list. - * - * See [Creating an Audience - * List](https://developers.google.com/analytics/devguides/reporting/data/v1/audience-list-basics) - * for an introduction to Audience Lists with examples. - * - * Audiences in Google Analytics 4 allow you to segment your users in the ways - * that are important to your business. To learn more, see - * https://support.google.com/analytics/answer/9267572. - * - * This method is available at beta stability at - * [audienceExports.query](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties.audienceExports/query). - * To give your feedback on this API, complete the [Google Analytics Audience - * Export API Feedback](https://forms.gle/EeA5u5LW6PEggtCEA) form. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the audience list to retrieve users from. - * Format: `properties/{property}/audienceLists/{audience_list}` - * @param {number} [request.offset] - * Optional. The row count of the start row. The first row is counted as row - * 0. - * - * When paging, the first request does not specify offset; or equivalently, - * sets offset to 0; the first request returns the first `limit` of rows. The - * second request sets offset to the `limit` of the first request; the second - * request returns the second `limit` of rows. - * - * To learn more about this pagination parameter, see - * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). - * @param {number} [request.limit] - * Optional. The number of rows to return. If unspecified, 10,000 rows are - * returned. The API returns a maximum of 250,000 rows per request, no matter - * how many you ask for. `limit` must be positive. - * - * The API can also return fewer rows than the requested `limit`, if there - * aren't as many dimension values as the `limit`. - * - * To learn more about this pagination parameter, see - * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). - * @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.analytics.data.v1alpha.QueryAudienceListResponse|QueryAudienceListResponse}. - * 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/v1alpha/alpha_analytics_data.query_audience_list.js - * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_QueryAudienceList_async - */ + /** + * Retrieves an audience list of users. After creating an audience, the users + * are not immediately available for listing. First, a request to + * `CreateAudienceList` is necessary to create an audience list of users, and + * then second, this method is used to retrieve the users in the audience + * list. + * + * See [Creating an Audience + * List](https://developers.google.com/analytics/devguides/reporting/data/v1/audience-list-basics) + * for an introduction to Audience Lists with examples. + * + * Audiences in Google Analytics 4 allow you to segment your users in the ways + * that are important to your business. To learn more, see + * https://support.google.com/analytics/answer/9267572. + * + * This method is available at beta stability at + * [audienceExports.query](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties.audienceExports/query). + * To give your feedback on this API, complete the [Google Analytics Audience + * Export API Feedback](https://forms.gle/EeA5u5LW6PEggtCEA) form. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the audience list to retrieve users from. + * Format: `properties/{property}/audienceLists/{audience_list}` + * @param {number} [request.offset] + * Optional. The row count of the start row. The first row is counted as row + * 0. + * + * When paging, the first request does not specify offset; or equivalently, + * sets offset to 0; the first request returns the first `limit` of rows. The + * second request sets offset to the `limit` of the first request; the second + * request returns the second `limit` of rows. + * + * To learn more about this pagination parameter, see + * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). + * @param {number} [request.limit] + * Optional. The number of rows to return. If unspecified, 10,000 rows are + * returned. The API returns a maximum of 250,000 rows per request, no matter + * how many you ask for. `limit` must be positive. + * + * The API can also return fewer rows than the requested `limit`, if there + * aren't as many dimension values as the `limit`. + * + * To learn more about this pagination parameter, see + * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). + * @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.analytics.data.v1alpha.QueryAudienceListResponse|QueryAudienceListResponse}. + * 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/v1alpha/alpha_analytics_data.query_audience_list.js + * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_QueryAudienceList_async + */ queryAudienceList( - request?: protos.google.analytics.data.v1alpha.IQueryAudienceListRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.data.v1alpha.IQueryAudienceListResponse, - protos.google.analytics.data.v1alpha.IQueryAudienceListRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.data.v1alpha.IQueryAudienceListRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IQueryAudienceListResponse, + ( + | protos.google.analytics.data.v1alpha.IQueryAudienceListRequest + | undefined + ), + {} | undefined, + ] + >; queryAudienceList( - request: protos.google.analytics.data.v1alpha.IQueryAudienceListRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.data.v1alpha.IQueryAudienceListResponse, - protos.google.analytics.data.v1alpha.IQueryAudienceListRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.IQueryAudienceListRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.data.v1alpha.IQueryAudienceListResponse, + | protos.google.analytics.data.v1alpha.IQueryAudienceListRequest + | null + | undefined, + {} | null | undefined + >, + ): void; queryAudienceList( - request: protos.google.analytics.data.v1alpha.IQueryAudienceListRequest, - callback: Callback< - protos.google.analytics.data.v1alpha.IQueryAudienceListResponse, - protos.google.analytics.data.v1alpha.IQueryAudienceListRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.IQueryAudienceListRequest, + callback: Callback< + protos.google.analytics.data.v1alpha.IQueryAudienceListResponse, + | protos.google.analytics.data.v1alpha.IQueryAudienceListRequest + | null + | undefined, + {} | null | undefined + >, + ): void; queryAudienceList( - request?: protos.google.analytics.data.v1alpha.IQueryAudienceListRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.data.v1alpha.IQueryAudienceListResponse, - protos.google.analytics.data.v1alpha.IQueryAudienceListRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.data.v1alpha.IQueryAudienceListRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.data.v1alpha.IQueryAudienceListResponse, - protos.google.analytics.data.v1alpha.IQueryAudienceListRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.data.v1alpha.IQueryAudienceListResponse, - protos.google.analytics.data.v1alpha.IQueryAudienceListRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.data.v1alpha.IQueryAudienceListRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.data.v1alpha.IQueryAudienceListResponse, + | protos.google.analytics.data.v1alpha.IQueryAudienceListRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IQueryAudienceListResponse, + ( + | protos.google.analytics.data.v1alpha.IQueryAudienceListRequest + | 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('queryAudienceList request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.data.v1alpha.IQueryAudienceListResponse, - protos.google.analytics.data.v1alpha.IQueryAudienceListRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.data.v1alpha.IQueryAudienceListResponse, + | protos.google.analytics.data.v1alpha.IQueryAudienceListRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('queryAudienceList response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.queryAudienceList(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.data.v1alpha.IQueryAudienceListResponse, - protos.google.analytics.data.v1alpha.IQueryAudienceListRequest|undefined, - {}|undefined - ]) => { - this._log.info('queryAudienceList response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .queryAudienceList(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.data.v1alpha.IQueryAudienceListResponse, + ( + | protos.google.analytics.data.v1alpha.IQueryAudienceListRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('queryAudienceList response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets configuration metadata about a specific audience list. This method - * can be used to understand an audience list after it has been created. - * - * See [Creating an Audience - * List](https://developers.google.com/analytics/devguides/reporting/data/v1/audience-list-basics) - * for an introduction to Audience Lists with examples. - * - * This method is available at beta stability at - * [audienceExports.get](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties.audienceExports/get). - * To give your feedback on this API, complete the - * [Google Analytics Audience Export API - * Feedback](https://forms.gle/EeA5u5LW6PEggtCEA) form. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The audience list resource name. - * Format: `properties/{property}/audienceLists/{audience_list}` - * @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.analytics.data.v1alpha.AudienceList|AudienceList}. - * 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/v1alpha/alpha_analytics_data.get_audience_list.js - * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_GetAudienceList_async - */ + /** + * Gets configuration metadata about a specific audience list. This method + * can be used to understand an audience list after it has been created. + * + * See [Creating an Audience + * List](https://developers.google.com/analytics/devguides/reporting/data/v1/audience-list-basics) + * for an introduction to Audience Lists with examples. + * + * This method is available at beta stability at + * [audienceExports.get](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties.audienceExports/get). + * To give your feedback on this API, complete the + * [Google Analytics Audience Export API + * Feedback](https://forms.gle/EeA5u5LW6PEggtCEA) form. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The audience list resource name. + * Format: `properties/{property}/audienceLists/{audience_list}` + * @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.analytics.data.v1alpha.AudienceList|AudienceList}. + * 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/v1alpha/alpha_analytics_data.get_audience_list.js + * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_GetAudienceList_async + */ getAudienceList( - request?: protos.google.analytics.data.v1alpha.IGetAudienceListRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.data.v1alpha.IAudienceList, - protos.google.analytics.data.v1alpha.IGetAudienceListRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.data.v1alpha.IGetAudienceListRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IAudienceList, + protos.google.analytics.data.v1alpha.IGetAudienceListRequest | undefined, + {} | undefined, + ] + >; getAudienceList( - request: protos.google.analytics.data.v1alpha.IGetAudienceListRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.data.v1alpha.IAudienceList, - protos.google.analytics.data.v1alpha.IGetAudienceListRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.IGetAudienceListRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.data.v1alpha.IAudienceList, + | protos.google.analytics.data.v1alpha.IGetAudienceListRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAudienceList( - request: protos.google.analytics.data.v1alpha.IGetAudienceListRequest, - callback: Callback< - protos.google.analytics.data.v1alpha.IAudienceList, - protos.google.analytics.data.v1alpha.IGetAudienceListRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.IGetAudienceListRequest, + callback: Callback< + protos.google.analytics.data.v1alpha.IAudienceList, + | protos.google.analytics.data.v1alpha.IGetAudienceListRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAudienceList( - request?: protos.google.analytics.data.v1alpha.IGetAudienceListRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.data.v1alpha.IAudienceList, - protos.google.analytics.data.v1alpha.IGetAudienceListRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.data.v1alpha.IGetAudienceListRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.data.v1alpha.IAudienceList, - protos.google.analytics.data.v1alpha.IGetAudienceListRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.data.v1alpha.IAudienceList, - protos.google.analytics.data.v1alpha.IGetAudienceListRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.data.v1alpha.IGetAudienceListRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.data.v1alpha.IAudienceList, + | protos.google.analytics.data.v1alpha.IGetAudienceListRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IAudienceList, + protos.google.analytics.data.v1alpha.IGetAudienceListRequest | 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('getAudienceList request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.data.v1alpha.IAudienceList, - protos.google.analytics.data.v1alpha.IGetAudienceListRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.data.v1alpha.IAudienceList, + | protos.google.analytics.data.v1alpha.IGetAudienceListRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getAudienceList response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getAudienceList(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.data.v1alpha.IAudienceList, - protos.google.analytics.data.v1alpha.IGetAudienceListRequest|undefined, - {}|undefined - ]) => { - this._log.info('getAudienceList response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getAudienceList(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.data.v1alpha.IAudienceList, + ( + | protos.google.analytics.data.v1alpha.IGetAudienceListRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getAudienceList response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a recurring audience list. Recurring audience lists produces new - * audience lists each day. Audience lists are users in an audience at the - * time of the list's creation. - * - * A recurring audience list ensures that you have audience list based on the - * most recent data available for use each day. If you manually create - * audience list, you don't know when an audience list based on an additional - * day's data is available. This recurring audience list automates the - * creation of an audience list when an additional day's data is available. - * You will consume fewer quota tokens by using recurring audience list versus - * manually creating audience list at various times of day trying to guess - * when an additional day's data is ready. - * - * This method is introduced at alpha stability with the intention of - * gathering feedback on syntax and capabilities before entering beta. To give - * your feedback on this API, complete the - * [Google Analytics Audience Export API - * Feedback](https://forms.gle/EeA5u5LW6PEggtCEA) form. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource where this recurring audience list will be - * created. Format: `properties/{property}` - * @param {google.analytics.data.v1alpha.RecurringAudienceList} request.recurringAudienceList - * Required. The recurring audience list 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.analytics.data.v1alpha.RecurringAudienceList|RecurringAudienceList}. - * 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/v1alpha/alpha_analytics_data.create_recurring_audience_list.js - * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_CreateRecurringAudienceList_async - */ + /** + * Creates a recurring audience list. Recurring audience lists produces new + * audience lists each day. Audience lists are users in an audience at the + * time of the list's creation. + * + * A recurring audience list ensures that you have audience list based on the + * most recent data available for use each day. If you manually create + * audience list, you don't know when an audience list based on an additional + * day's data is available. This recurring audience list automates the + * creation of an audience list when an additional day's data is available. + * You will consume fewer quota tokens by using recurring audience list versus + * manually creating audience list at various times of day trying to guess + * when an additional day's data is ready. + * + * This method is introduced at alpha stability with the intention of + * gathering feedback on syntax and capabilities before entering beta. To give + * your feedback on this API, complete the + * [Google Analytics Audience Export API + * Feedback](https://forms.gle/EeA5u5LW6PEggtCEA) form. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource where this recurring audience list will be + * created. Format: `properties/{property}` + * @param {google.analytics.data.v1alpha.RecurringAudienceList} request.recurringAudienceList + * Required. The recurring audience list 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.analytics.data.v1alpha.RecurringAudienceList|RecurringAudienceList}. + * 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/v1alpha/alpha_analytics_data.create_recurring_audience_list.js + * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_CreateRecurringAudienceList_async + */ createRecurringAudienceList( - request?: protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.data.v1alpha.IRecurringAudienceList, - protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IRecurringAudienceList, + ( + | protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest + | undefined + ), + {} | undefined, + ] + >; createRecurringAudienceList( - request: protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.data.v1alpha.IRecurringAudienceList, - protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.data.v1alpha.IRecurringAudienceList, + | protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createRecurringAudienceList( - request: protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest, - callback: Callback< - protos.google.analytics.data.v1alpha.IRecurringAudienceList, - protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest, + callback: Callback< + protos.google.analytics.data.v1alpha.IRecurringAudienceList, + | protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createRecurringAudienceList( - request?: protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.data.v1alpha.IRecurringAudienceList, - protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.data.v1alpha.IRecurringAudienceList, - protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.data.v1alpha.IRecurringAudienceList, - protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.data.v1alpha.IRecurringAudienceList, + | protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IRecurringAudienceList, + ( + | protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest + | 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('createRecurringAudienceList request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.data.v1alpha.IRecurringAudienceList, - protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.data.v1alpha.IRecurringAudienceList, + | protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createRecurringAudienceList response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createRecurringAudienceList(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.data.v1alpha.IRecurringAudienceList, - protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest|undefined, - {}|undefined - ]) => { - this._log.info('createRecurringAudienceList response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createRecurringAudienceList(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.data.v1alpha.IRecurringAudienceList, + ( + | protos.google.analytics.data.v1alpha.ICreateRecurringAudienceListRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createRecurringAudienceList response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets configuration metadata about a specific recurring audience list. This - * method can be used to understand a recurring audience list's state after it - * has been created. For example, a recurring audience list resource will - * generate audience list instances for each day, and this method can be used - * to get the resource name of the most recent audience list instance. - * - * This method is introduced at alpha stability with the intention of - * gathering feedback on syntax and capabilities before entering beta. To give - * your feedback on this API, complete the - * [Google Analytics Audience Export API - * Feedback](https://forms.gle/EeA5u5LW6PEggtCEA) form. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The recurring audience list resource name. - * Format: - * `properties/{property}/recurringAudienceLists/{recurring_audience_list}` - * @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.analytics.data.v1alpha.RecurringAudienceList|RecurringAudienceList}. - * 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/v1alpha/alpha_analytics_data.get_recurring_audience_list.js - * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_GetRecurringAudienceList_async - */ + /** + * Gets configuration metadata about a specific recurring audience list. This + * method can be used to understand a recurring audience list's state after it + * has been created. For example, a recurring audience list resource will + * generate audience list instances for each day, and this method can be used + * to get the resource name of the most recent audience list instance. + * + * This method is introduced at alpha stability with the intention of + * gathering feedback on syntax and capabilities before entering beta. To give + * your feedback on this API, complete the + * [Google Analytics Audience Export API + * Feedback](https://forms.gle/EeA5u5LW6PEggtCEA) form. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The recurring audience list resource name. + * Format: + * `properties/{property}/recurringAudienceLists/{recurring_audience_list}` + * @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.analytics.data.v1alpha.RecurringAudienceList|RecurringAudienceList}. + * 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/v1alpha/alpha_analytics_data.get_recurring_audience_list.js + * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_GetRecurringAudienceList_async + */ getRecurringAudienceList( - request?: protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.data.v1alpha.IRecurringAudienceList, - protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IRecurringAudienceList, + ( + | protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest + | undefined + ), + {} | undefined, + ] + >; getRecurringAudienceList( - request: protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.data.v1alpha.IRecurringAudienceList, - protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.data.v1alpha.IRecurringAudienceList, + | protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getRecurringAudienceList( - request: protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest, - callback: Callback< - protos.google.analytics.data.v1alpha.IRecurringAudienceList, - protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest, + callback: Callback< + protos.google.analytics.data.v1alpha.IRecurringAudienceList, + | protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getRecurringAudienceList( - request?: protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.data.v1alpha.IRecurringAudienceList, - protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.data.v1alpha.IRecurringAudienceList, - protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.data.v1alpha.IRecurringAudienceList, - protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.data.v1alpha.IRecurringAudienceList, + | protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IRecurringAudienceList, + ( + | protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest + | 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('getRecurringAudienceList request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.data.v1alpha.IRecurringAudienceList, - protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.data.v1alpha.IRecurringAudienceList, + | protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getRecurringAudienceList response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getRecurringAudienceList(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.data.v1alpha.IRecurringAudienceList, - protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest|undefined, - {}|undefined - ]) => { - this._log.info('getRecurringAudienceList response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getRecurringAudienceList(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.data.v1alpha.IRecurringAudienceList, + ( + | protos.google.analytics.data.v1alpha.IGetRecurringAudienceListRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getRecurringAudienceList response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Get all property quotas organized by quota category for a given property. - * This will charge 1 property quota from the category with the most quota. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Quotas from this property will be listed in the response. - * Format: `properties/{property}/propertyQuotasSnapshot` - * @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.analytics.data.v1alpha.PropertyQuotasSnapshot|PropertyQuotasSnapshot}. - * 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/v1alpha/alpha_analytics_data.get_property_quotas_snapshot.js - * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_GetPropertyQuotasSnapshot_async - */ + /** + * Get all property quotas organized by quota category for a given property. + * This will charge 1 property quota from the category with the most quota. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Quotas from this property will be listed in the response. + * Format: `properties/{property}/propertyQuotasSnapshot` + * @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.analytics.data.v1alpha.PropertyQuotasSnapshot|PropertyQuotasSnapshot}. + * 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/v1alpha/alpha_analytics_data.get_property_quotas_snapshot.js + * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_GetPropertyQuotasSnapshot_async + */ getPropertyQuotasSnapshot( - request?: protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.data.v1alpha.IPropertyQuotasSnapshot, - protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IPropertyQuotasSnapshot, + ( + | protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest + | undefined + ), + {} | undefined, + ] + >; getPropertyQuotasSnapshot( - request: protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.data.v1alpha.IPropertyQuotasSnapshot, - protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.data.v1alpha.IPropertyQuotasSnapshot, + | protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getPropertyQuotasSnapshot( - request: protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest, - callback: Callback< - protos.google.analytics.data.v1alpha.IPropertyQuotasSnapshot, - protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest, + callback: Callback< + protos.google.analytics.data.v1alpha.IPropertyQuotasSnapshot, + | protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getPropertyQuotasSnapshot( - request?: protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.data.v1alpha.IPropertyQuotasSnapshot, - protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.data.v1alpha.IPropertyQuotasSnapshot, - protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.data.v1alpha.IPropertyQuotasSnapshot, - protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.data.v1alpha.IPropertyQuotasSnapshot, + | protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IPropertyQuotasSnapshot, + ( + | protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest + | 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('getPropertyQuotasSnapshot request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.data.v1alpha.IPropertyQuotasSnapshot, - protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.data.v1alpha.IPropertyQuotasSnapshot, + | protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getPropertyQuotasSnapshot response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getPropertyQuotasSnapshot(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.data.v1alpha.IPropertyQuotasSnapshot, - protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest|undefined, - {}|undefined - ]) => { - this._log.info('getPropertyQuotasSnapshot response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getPropertyQuotasSnapshot(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.data.v1alpha.IPropertyQuotasSnapshot, + ( + | protos.google.analytics.data.v1alpha.IGetPropertyQuotasSnapshotRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getPropertyQuotasSnapshot response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieves a report task's content. After requesting the `CreateReportTask`, - * you are able to retrieve the report content once the report is - * ACTIVE. This method will return an error if the report task's state is not - * `ACTIVE`. A query response will return the tabular row & column values of - * the report. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The report source name. - * Format: `properties/{property}/reportTasks/{report}` - * @param {number} [request.offset] - * Optional. The row count of the start row in the report. The first row is - * counted as row 0. - * - * When paging, the first request does not specify offset; or equivalently, - * sets offset to 0; the first request returns the first `limit` of rows. The - * second request sets offset to the `limit` of the first request; the second - * request returns the second `limit` of rows. - * - * To learn more about this pagination parameter, see - * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). - * @param {number} [request.limit] - * Optional. The number of rows to return from the report. If unspecified, - * 10,000 rows are returned. The API returns a maximum of 250,000 rows per - * request, no matter how many you ask for. `limit` must be positive. - * - * The API can also return fewer rows than the requested `limit`, if there - * aren't as many dimension values as the `limit`. The number of rows - * available to a QueryReportTaskRequest is further limited by the limit of - * the associated ReportTask. A query can retrieve at most ReportTask.limit - * rows. For example, if the ReportTask has a limit of 1,000, then a - * QueryReportTask request with offset=900 and limit=500 will return at most - * 100 rows. - * - * To learn more about this pagination parameter, see - * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). - * @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.analytics.data.v1alpha.QueryReportTaskResponse|QueryReportTaskResponse}. - * 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/v1alpha/alpha_analytics_data.query_report_task.js - * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_QueryReportTask_async - */ + /** + * Retrieves a report task's content. After requesting the `CreateReportTask`, + * you are able to retrieve the report content once the report is + * ACTIVE. This method will return an error if the report task's state is not + * `ACTIVE`. A query response will return the tabular row & column values of + * the report. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The report source name. + * Format: `properties/{property}/reportTasks/{report}` + * @param {number} [request.offset] + * Optional. The row count of the start row in the report. The first row is + * counted as row 0. + * + * When paging, the first request does not specify offset; or equivalently, + * sets offset to 0; the first request returns the first `limit` of rows. The + * second request sets offset to the `limit` of the first request; the second + * request returns the second `limit` of rows. + * + * To learn more about this pagination parameter, see + * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). + * @param {number} [request.limit] + * Optional. The number of rows to return from the report. If unspecified, + * 10,000 rows are returned. The API returns a maximum of 250,000 rows per + * request, no matter how many you ask for. `limit` must be positive. + * + * The API can also return fewer rows than the requested `limit`, if there + * aren't as many dimension values as the `limit`. The number of rows + * available to a QueryReportTaskRequest is further limited by the limit of + * the associated ReportTask. A query can retrieve at most ReportTask.limit + * rows. For example, if the ReportTask has a limit of 1,000, then a + * QueryReportTask request with offset=900 and limit=500 will return at most + * 100 rows. + * + * To learn more about this pagination parameter, see + * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). + * @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.analytics.data.v1alpha.QueryReportTaskResponse|QueryReportTaskResponse}. + * 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/v1alpha/alpha_analytics_data.query_report_task.js + * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_QueryReportTask_async + */ queryReportTask( - request?: protos.google.analytics.data.v1alpha.IQueryReportTaskRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.data.v1alpha.IQueryReportTaskResponse, - protos.google.analytics.data.v1alpha.IQueryReportTaskRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.data.v1alpha.IQueryReportTaskRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IQueryReportTaskResponse, + protos.google.analytics.data.v1alpha.IQueryReportTaskRequest | undefined, + {} | undefined, + ] + >; queryReportTask( - request: protos.google.analytics.data.v1alpha.IQueryReportTaskRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.data.v1alpha.IQueryReportTaskResponse, - protos.google.analytics.data.v1alpha.IQueryReportTaskRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.IQueryReportTaskRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.data.v1alpha.IQueryReportTaskResponse, + | protos.google.analytics.data.v1alpha.IQueryReportTaskRequest + | null + | undefined, + {} | null | undefined + >, + ): void; queryReportTask( - request: protos.google.analytics.data.v1alpha.IQueryReportTaskRequest, - callback: Callback< - protos.google.analytics.data.v1alpha.IQueryReportTaskResponse, - protos.google.analytics.data.v1alpha.IQueryReportTaskRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.IQueryReportTaskRequest, + callback: Callback< + protos.google.analytics.data.v1alpha.IQueryReportTaskResponse, + | protos.google.analytics.data.v1alpha.IQueryReportTaskRequest + | null + | undefined, + {} | null | undefined + >, + ): void; queryReportTask( - request?: protos.google.analytics.data.v1alpha.IQueryReportTaskRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.data.v1alpha.IQueryReportTaskResponse, - protos.google.analytics.data.v1alpha.IQueryReportTaskRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.data.v1alpha.IQueryReportTaskRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.data.v1alpha.IQueryReportTaskResponse, - protos.google.analytics.data.v1alpha.IQueryReportTaskRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.data.v1alpha.IQueryReportTaskResponse, - protos.google.analytics.data.v1alpha.IQueryReportTaskRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.data.v1alpha.IQueryReportTaskRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.data.v1alpha.IQueryReportTaskResponse, + | protos.google.analytics.data.v1alpha.IQueryReportTaskRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IQueryReportTaskResponse, + protos.google.analytics.data.v1alpha.IQueryReportTaskRequest | 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('queryReportTask request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.data.v1alpha.IQueryReportTaskResponse, - protos.google.analytics.data.v1alpha.IQueryReportTaskRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.data.v1alpha.IQueryReportTaskResponse, + | protos.google.analytics.data.v1alpha.IQueryReportTaskRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('queryReportTask response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.queryReportTask(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.data.v1alpha.IQueryReportTaskResponse, - protos.google.analytics.data.v1alpha.IQueryReportTaskRequest|undefined, - {}|undefined - ]) => { - this._log.info('queryReportTask response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .queryReportTask(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.data.v1alpha.IQueryReportTaskResponse, + ( + | protos.google.analytics.data.v1alpha.IQueryReportTaskRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('queryReportTask response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets report metadata about a specific report task. After creating a report - * task, use this method to check its processing state or inspect its - * report definition. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The report task resource name. - * Format: `properties/{property}/reportTasks/{report_task}` - * @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.analytics.data.v1alpha.ReportTask|ReportTask}. - * 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/v1alpha/alpha_analytics_data.get_report_task.js - * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_GetReportTask_async - */ + /** + * Gets report metadata about a specific report task. After creating a report + * task, use this method to check its processing state or inspect its + * report definition. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The report task resource name. + * Format: `properties/{property}/reportTasks/{report_task}` + * @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.analytics.data.v1alpha.ReportTask|ReportTask}. + * 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/v1alpha/alpha_analytics_data.get_report_task.js + * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_GetReportTask_async + */ getReportTask( - request?: protos.google.analytics.data.v1alpha.IGetReportTaskRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.data.v1alpha.IReportTask, - protos.google.analytics.data.v1alpha.IGetReportTaskRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.data.v1alpha.IGetReportTaskRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IReportTask, + protos.google.analytics.data.v1alpha.IGetReportTaskRequest | undefined, + {} | undefined, + ] + >; getReportTask( - request: protos.google.analytics.data.v1alpha.IGetReportTaskRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.data.v1alpha.IReportTask, - protos.google.analytics.data.v1alpha.IGetReportTaskRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.IGetReportTaskRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.data.v1alpha.IReportTask, + | protos.google.analytics.data.v1alpha.IGetReportTaskRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getReportTask( - request: protos.google.analytics.data.v1alpha.IGetReportTaskRequest, - callback: Callback< - protos.google.analytics.data.v1alpha.IReportTask, - protos.google.analytics.data.v1alpha.IGetReportTaskRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.IGetReportTaskRequest, + callback: Callback< + protos.google.analytics.data.v1alpha.IReportTask, + | protos.google.analytics.data.v1alpha.IGetReportTaskRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getReportTask( - request?: protos.google.analytics.data.v1alpha.IGetReportTaskRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.data.v1alpha.IReportTask, - protos.google.analytics.data.v1alpha.IGetReportTaskRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.data.v1alpha.IGetReportTaskRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.data.v1alpha.IReportTask, - protos.google.analytics.data.v1alpha.IGetReportTaskRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.data.v1alpha.IReportTask, - protos.google.analytics.data.v1alpha.IGetReportTaskRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.data.v1alpha.IGetReportTaskRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.data.v1alpha.IReportTask, + | protos.google.analytics.data.v1alpha.IGetReportTaskRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IReportTask, + protos.google.analytics.data.v1alpha.IGetReportTaskRequest | 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('getReportTask request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.data.v1alpha.IReportTask, - protos.google.analytics.data.v1alpha.IGetReportTaskRequest|null|undefined, - {}|null|undefined>|undefined = callback - ? (error, response, options, rawResponse) => { - this._log.info('getReportTask response %j', response); + const wrappedCallback: + | Callback< + protos.google.analytics.data.v1alpha.IReportTask, + | protos.google.analytics.data.v1alpha.IGetReportTaskRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getReportTask response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getReportTask(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.data.v1alpha.IReportTask, - protos.google.analytics.data.v1alpha.IGetReportTaskRequest|undefined, - {}|undefined - ]) => { - this._log.info('getReportTask response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getReportTask(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.data.v1alpha.IReportTask, + ( + | protos.google.analytics.data.v1alpha.IGetReportTaskRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getReportTask response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns a customized report of your Google Analytics event data. Reports - * contain statistics derived from data collected by the Google Analytics - * tracking code. The data returned from the API is as a table with columns - * for the requested dimensions and metrics. Metrics are individual - * measurements of user activity on your property, such as active users or - * event count. Dimensions break down metrics across some common criteria, - * such as country or event name. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.property - * Required. A Google Analytics property identifier whose events are tracked. - * Specified in the URL path and not the body. To learn more, see [where to - * find your Property - * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id). - * Within a batch request, this property should either be unspecified or - * consistent with the batch-level property. - * - * Example: properties/1234 - * @param {number[]} [request.dimensions] - * Optional. The dimensions requested and displayed. - * @param {number[]} [request.metrics] - * Optional. The metrics requested and displayed. - * @param {number[]} [request.dateRanges] - * Optional. Date ranges of data to read. If multiple date ranges are - * requested, each response row will contain a zero based date range index. If - * two date ranges overlap, the event data for the overlapping days is - * included in the response rows for both date ranges. In a cohort request, - * this `dateRanges` must be unspecified. - * @param {google.analytics.data.v1alpha.FilterExpression} [request.dimensionFilter] - * Optional. Dimension filters let you ask for only specific dimension values - * in the report. To learn more, see [Fundamentals of Dimension - * Filters](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#dimension_filters) - * for examples. Metrics cannot be used in this filter. - * @param {google.analytics.data.v1alpha.FilterExpression} [request.metricFilter] - * Optional. The filter clause of metrics. Applied after aggregating the - * report's rows, similar to SQL having-clause. Dimensions cannot be used in - * this filter. - * @param {number} [request.offset] - * Optional. The row count of the start row. The first row is counted as row - * 0. - * - * When paging, the first request does not specify offset; or equivalently, - * sets offset to 0; the first request returns the first `limit` of rows. The - * second request sets offset to the `limit` of the first request; the second - * request returns the second `limit` of rows. - * - * To learn more about this pagination parameter, see - * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). - * @param {number} [request.limit] - * Optional. The maximum number of rows to return. If unspecified, 10,000 rows - * are returned. The API returns a maximum of 250,000 rows per request, no - * matter how many you ask for. `limit` must be positive. - * - * The API can also return fewer rows than the requested `limit`, if there - * aren't as many dimension values as the `limit`. For instance, there are - * fewer than 300 possible values for the dimension `country`, so when - * reporting on only `country`, you can't get more than 300 rows, even if you - * set `limit` to a higher value. - * - * To learn more about this pagination parameter, see - * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). - * @param {number[]} [request.metricAggregations] - * Optional. Aggregation of metrics. Aggregated metric values will be shown in - * rows where the dimension_values are set to "RESERVED_(MetricAggregation)". - * Aggregates including both comparisons and multiple date ranges will - * be aggregated based on the date ranges. - * @param {number[]} [request.orderBys] - * Optional. Specifies how rows are ordered in the response. - * Requests including both comparisons and multiple date ranges will - * have order bys applied on the comparisons. - * @param {string} [request.currencyCode] - * Optional. A currency code in ISO4217 format, such as "AED", "USD", "JPY". - * If the field is empty, the report uses the property's default currency. - * @param {google.analytics.data.v1alpha.CohortSpec} [request.cohortSpec] - * Optional. Cohort group associated with this request. If there is a cohort - * group in the request the 'cohort' dimension must be present. - * @param {boolean} [request.keepEmptyRows] - * Optional. If false or unspecified, each row with all metrics equal to 0 - * will not be returned. If true, these rows will be returned if they are not - * separately removed by a filter. - * - * Regardless of this `keep_empty_rows` setting, only data recorded by the - * Google Analytics property can be displayed in a report. - * - * For example if a property never logs a `purchase` event, then a query for - * the `eventName` dimension and `eventCount` metric will not have a row - * eventName: "purchase" and eventCount: 0. - * @param {boolean} [request.returnPropertyQuota] - * Optional. Toggles whether to return the current state of this Google - * Analytics property's quota. Quota is returned in - * [PropertyQuota](#PropertyQuota). - * @param {number[]} [request.comparisons] - * Optional. The configuration of comparisons requested and displayed. The - * request only requires a comparisons field in order to receive a comparison - * column in the response. - * @param {google.analytics.data.v1alpha.ConversionSpec} [request.conversionSpec] - * Optional. Controls conversion reporting. This field is optional. If this - * field is set or any conversion metrics are requested, the report will be a - * conversion report. - * @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.analytics.data.v1alpha.RunReportResponse|RunReportResponse}. - * 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/v1alpha/alpha_analytics_data.run_report.js - * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_RunReport_async - */ + /** + * Returns a customized report of your Google Analytics event data. Reports + * contain statistics derived from data collected by the Google Analytics + * tracking code. The data returned from the API is as a table with columns + * for the requested dimensions and metrics. Metrics are individual + * measurements of user activity on your property, such as active users or + * event count. Dimensions break down metrics across some common criteria, + * such as country or event name. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.property + * Required. A Google Analytics property identifier whose events are tracked. + * Specified in the URL path and not the body. To learn more, see [where to + * find your Property + * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id). + * Within a batch request, this property should either be unspecified or + * consistent with the batch-level property. + * + * Example: properties/1234 + * @param {number[]} [request.dimensions] + * Optional. The dimensions requested and displayed. + * @param {number[]} [request.metrics] + * Optional. The metrics requested and displayed. + * @param {number[]} [request.dateRanges] + * Optional. Date ranges of data to read. If multiple date ranges are + * requested, each response row will contain a zero based date range index. If + * two date ranges overlap, the event data for the overlapping days is + * included in the response rows for both date ranges. In a cohort request, + * this `dateRanges` must be unspecified. + * @param {google.analytics.data.v1alpha.FilterExpression} [request.dimensionFilter] + * Optional. Dimension filters let you ask for only specific dimension values + * in the report. To learn more, see [Fundamentals of Dimension + * Filters](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#dimension_filters) + * for examples. Metrics cannot be used in this filter. + * @param {google.analytics.data.v1alpha.FilterExpression} [request.metricFilter] + * Optional. The filter clause of metrics. Applied after aggregating the + * report's rows, similar to SQL having-clause. Dimensions cannot be used in + * this filter. + * @param {number} [request.offset] + * Optional. The row count of the start row. The first row is counted as row + * 0. + * + * When paging, the first request does not specify offset; or equivalently, + * sets offset to 0; the first request returns the first `limit` of rows. The + * second request sets offset to the `limit` of the first request; the second + * request returns the second `limit` of rows. + * + * To learn more about this pagination parameter, see + * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). + * @param {number} [request.limit] + * Optional. The maximum number of rows to return. If unspecified, 10,000 rows + * are returned. The API returns a maximum of 250,000 rows per request, no + * matter how many you ask for. `limit` must be positive. + * + * The API can also return fewer rows than the requested `limit`, if there + * aren't as many dimension values as the `limit`. For instance, there are + * fewer than 300 possible values for the dimension `country`, so when + * reporting on only `country`, you can't get more than 300 rows, even if you + * set `limit` to a higher value. + * + * To learn more about this pagination parameter, see + * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). + * @param {number[]} [request.metricAggregations] + * Optional. Aggregation of metrics. Aggregated metric values will be shown in + * rows where the dimension_values are set to "RESERVED_(MetricAggregation)". + * Aggregates including both comparisons and multiple date ranges will + * be aggregated based on the date ranges. + * @param {number[]} [request.orderBys] + * Optional. Specifies how rows are ordered in the response. + * Requests including both comparisons and multiple date ranges will + * have order bys applied on the comparisons. + * @param {string} [request.currencyCode] + * Optional. A currency code in ISO4217 format, such as "AED", "USD", "JPY". + * If the field is empty, the report uses the property's default currency. + * @param {google.analytics.data.v1alpha.CohortSpec} [request.cohortSpec] + * Optional. Cohort group associated with this request. If there is a cohort + * group in the request the 'cohort' dimension must be present. + * @param {boolean} [request.keepEmptyRows] + * Optional. If false or unspecified, each row with all metrics equal to 0 + * will not be returned. If true, these rows will be returned if they are not + * separately removed by a filter. + * + * Regardless of this `keep_empty_rows` setting, only data recorded by the + * Google Analytics property can be displayed in a report. + * + * For example if a property never logs a `purchase` event, then a query for + * the `eventName` dimension and `eventCount` metric will not have a row + * eventName: "purchase" and eventCount: 0. + * @param {boolean} [request.returnPropertyQuota] + * Optional. Toggles whether to return the current state of this Google + * Analytics property's quota. Quota is returned in + * [PropertyQuota](#PropertyQuota). + * @param {number[]} [request.comparisons] + * Optional. The configuration of comparisons requested and displayed. The + * request only requires a comparisons field in order to receive a comparison + * column in the response. + * @param {google.analytics.data.v1alpha.ConversionSpec} [request.conversionSpec] + * Optional. Controls conversion reporting. This field is optional. If this + * field is set or any conversion metrics are requested, the report will be a + * conversion report. + * @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.analytics.data.v1alpha.RunReportResponse|RunReportResponse}. + * 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/v1alpha/alpha_analytics_data.run_report.js + * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_RunReport_async + */ runReport( - request?: protos.google.analytics.data.v1alpha.IRunReportRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.data.v1alpha.IRunReportResponse, - protos.google.analytics.data.v1alpha.IRunReportRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.data.v1alpha.IRunReportRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IRunReportResponse, + protos.google.analytics.data.v1alpha.IRunReportRequest | undefined, + {} | undefined, + ] + >; runReport( - request: protos.google.analytics.data.v1alpha.IRunReportRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.data.v1alpha.IRunReportResponse, - protos.google.analytics.data.v1alpha.IRunReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.IRunReportRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.data.v1alpha.IRunReportResponse, + protos.google.analytics.data.v1alpha.IRunReportRequest | null | undefined, + {} | null | undefined + >, + ): void; runReport( - request: protos.google.analytics.data.v1alpha.IRunReportRequest, - callback: Callback< - protos.google.analytics.data.v1alpha.IRunReportResponse, - protos.google.analytics.data.v1alpha.IRunReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.IRunReportRequest, + callback: Callback< + protos.google.analytics.data.v1alpha.IRunReportResponse, + protos.google.analytics.data.v1alpha.IRunReportRequest | null | undefined, + {} | null | undefined + >, + ): void; runReport( - request?: protos.google.analytics.data.v1alpha.IRunReportRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.data.v1alpha.IRunReportResponse, - protos.google.analytics.data.v1alpha.IRunReportRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.data.v1alpha.IRunReportRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.data.v1alpha.IRunReportResponse, - protos.google.analytics.data.v1alpha.IRunReportRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.data.v1alpha.IRunReportResponse, - protos.google.analytics.data.v1alpha.IRunReportRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.data.v1alpha.IRunReportRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.data.v1alpha.IRunReportResponse, + protos.google.analytics.data.v1alpha.IRunReportRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IRunReportResponse, + protos.google.analytics.data.v1alpha.IRunReportRequest | 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({ - 'property': request.property ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + property: request.property ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('runReport request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.data.v1alpha.IRunReportResponse, - protos.google.analytics.data.v1alpha.IRunReportRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.data.v1alpha.IRunReportResponse, + | protos.google.analytics.data.v1alpha.IRunReportRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('runReport response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.runReport(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.data.v1alpha.IRunReportResponse, - protos.google.analytics.data.v1alpha.IRunReportRequest|undefined, - {}|undefined - ]) => { - this._log.info('runReport response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .runReport(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.data.v1alpha.IRunReportResponse, + protos.google.analytics.data.v1alpha.IRunReportRequest | undefined, + {} | undefined, + ]) => { + this._log.info('runReport response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns metadata for dimensions and metrics available in reporting methods. - * Used to explore the dimensions and metrics. In this method, a Google - * Analytics property identifier is specified in the request, and - * the metadata response includes Custom dimensions and metrics as well as - * Universal metadata. - * - * For example if a custom metric with parameter name `levels_unlocked` is - * registered to a property, the Metadata response will contain - * `customEvent:levels_unlocked`. Universal metadata are dimensions and - * metrics applicable to any property such as `country` and `totalUsers`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the metadata to retrieve. This name field is - * specified in the URL path and not URL parameters. Property is a numeric - * Google Analytics property identifier. To learn more, see [where to find - * your Property - * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id). - * - * Example: properties/1234/metadata - * - * Set the Property ID to 0 for dimensions and metrics common to all - * properties. In this special mode, this method will not return custom - * dimensions and metrics. - * @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.analytics.data.v1alpha.Metadata|Metadata}. - * 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/v1alpha/alpha_analytics_data.get_metadata.js - * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_GetMetadata_async - */ + /** + * Returns metadata for dimensions and metrics available in reporting methods. + * Used to explore the dimensions and metrics. In this method, a Google + * Analytics property identifier is specified in the request, and + * the metadata response includes Custom dimensions and metrics as well as + * Universal metadata. + * + * For example if a custom metric with parameter name `levels_unlocked` is + * registered to a property, the Metadata response will contain + * `customEvent:levels_unlocked`. Universal metadata are dimensions and + * metrics applicable to any property such as `country` and `totalUsers`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the metadata to retrieve. This name field is + * specified in the URL path and not URL parameters. Property is a numeric + * Google Analytics property identifier. To learn more, see [where to find + * your Property + * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id). + * + * Example: properties/1234/metadata + * + * Set the Property ID to 0 for dimensions and metrics common to all + * properties. In this special mode, this method will not return custom + * dimensions and metrics. + * @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.analytics.data.v1alpha.Metadata|Metadata}. + * 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/v1alpha/alpha_analytics_data.get_metadata.js + * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_GetMetadata_async + */ getMetadata( - request?: protos.google.analytics.data.v1alpha.IGetMetadataRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.data.v1alpha.IMetadata, - protos.google.analytics.data.v1alpha.IGetMetadataRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.data.v1alpha.IGetMetadataRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IMetadata, + protos.google.analytics.data.v1alpha.IGetMetadataRequest | undefined, + {} | undefined, + ] + >; getMetadata( - request: protos.google.analytics.data.v1alpha.IGetMetadataRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.data.v1alpha.IMetadata, - protos.google.analytics.data.v1alpha.IGetMetadataRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.IGetMetadataRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.data.v1alpha.IMetadata, + | protos.google.analytics.data.v1alpha.IGetMetadataRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getMetadata( - request: protos.google.analytics.data.v1alpha.IGetMetadataRequest, - callback: Callback< - protos.google.analytics.data.v1alpha.IMetadata, - protos.google.analytics.data.v1alpha.IGetMetadataRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.IGetMetadataRequest, + callback: Callback< + protos.google.analytics.data.v1alpha.IMetadata, + | protos.google.analytics.data.v1alpha.IGetMetadataRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getMetadata( - request?: protos.google.analytics.data.v1alpha.IGetMetadataRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.data.v1alpha.IMetadata, - protos.google.analytics.data.v1alpha.IGetMetadataRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.data.v1alpha.IGetMetadataRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.data.v1alpha.IMetadata, - protos.google.analytics.data.v1alpha.IGetMetadataRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.data.v1alpha.IMetadata, - protos.google.analytics.data.v1alpha.IGetMetadataRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.data.v1alpha.IGetMetadataRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.data.v1alpha.IMetadata, + | protos.google.analytics.data.v1alpha.IGetMetadataRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IMetadata, + protos.google.analytics.data.v1alpha.IGetMetadataRequest | 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('getMetadata request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.data.v1alpha.IMetadata, - protos.google.analytics.data.v1alpha.IGetMetadataRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.data.v1alpha.IMetadata, + | protos.google.analytics.data.v1alpha.IGetMetadataRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getMetadata response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getMetadata(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.data.v1alpha.IMetadata, - protos.google.analytics.data.v1alpha.IGetMetadataRequest|undefined, - {}|undefined - ]) => { - this._log.info('getMetadata response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getMetadata(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.data.v1alpha.IMetadata, + protos.google.analytics.data.v1alpha.IGetMetadataRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getMetadata response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates an audience list for later retrieval. This method quickly returns - * the audience list's resource name and initiates a long running asynchronous - * request to form an audience list. To list the users in an audience list, - * first create the audience list through this method and then send the - * audience resource name to the `QueryAudienceList` method. - * - * See [Creating an Audience - * List](https://developers.google.com/analytics/devguides/reporting/data/v1/audience-list-basics) - * for an introduction to Audience Lists with examples. - * - * An audience list is a snapshot of the users currently in the audience at - * the time of audience list creation. Creating audience lists for one - * audience on different days will return different results as users enter and - * exit the audience. - * - * Audiences in Google Analytics 4 allow you to segment your users in the ways - * that are important to your business. To learn more, see - * https://support.google.com/analytics/answer/9267572. Audience lists contain - * the users in each audience. - * - * This method is available at beta stability at - * [audienceExports.create](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties.audienceExports/create). - * To give your feedback on this API, complete the [Google Analytics Audience - * Export API Feedback](https://forms.gle/EeA5u5LW6PEggtCEA) form. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource where this audience list will be created. - * Format: `properties/{property}` - * @param {google.analytics.data.v1alpha.AudienceList} request.audienceList - * Required. The audience list 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 include:samples/generated/v1alpha/alpha_analytics_data.create_audience_list.js - * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_CreateAudienceList_async - */ + /** + * Creates an audience list for later retrieval. This method quickly returns + * the audience list's resource name and initiates a long running asynchronous + * request to form an audience list. To list the users in an audience list, + * first create the audience list through this method and then send the + * audience resource name to the `QueryAudienceList` method. + * + * See [Creating an Audience + * List](https://developers.google.com/analytics/devguides/reporting/data/v1/audience-list-basics) + * for an introduction to Audience Lists with examples. + * + * An audience list is a snapshot of the users currently in the audience at + * the time of audience list creation. Creating audience lists for one + * audience on different days will return different results as users enter and + * exit the audience. + * + * Audiences in Google Analytics 4 allow you to segment your users in the ways + * that are important to your business. To learn more, see + * https://support.google.com/analytics/answer/9267572. Audience lists contain + * the users in each audience. + * + * This method is available at beta stability at + * [audienceExports.create](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties.audienceExports/create). + * To give your feedback on this API, complete the [Google Analytics Audience + * Export API Feedback](https://forms.gle/EeA5u5LW6PEggtCEA) form. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource where this audience list will be created. + * Format: `properties/{property}` + * @param {google.analytics.data.v1alpha.AudienceList} request.audienceList + * Required. The audience list 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 include:samples/generated/v1alpha/alpha_analytics_data.create_audience_list.js + * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_CreateAudienceList_async + */ createAudienceList( - request?: protos.google.analytics.data.v1alpha.ICreateAudienceListRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.analytics.data.v1alpha.ICreateAudienceListRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.analytics.data.v1alpha.IAudienceList, + protos.google.analytics.data.v1alpha.IAudienceListMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; createAudienceList( - request: protos.google.analytics.data.v1alpha.ICreateAudienceListRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.ICreateAudienceListRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.analytics.data.v1alpha.IAudienceList, + protos.google.analytics.data.v1alpha.IAudienceListMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createAudienceList( - request: protos.google.analytics.data.v1alpha.ICreateAudienceListRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.ICreateAudienceListRequest, + callback: Callback< + LROperation< + protos.google.analytics.data.v1alpha.IAudienceList, + protos.google.analytics.data.v1alpha.IAudienceListMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createAudienceList( - request?: protos.google.analytics.data.v1alpha.ICreateAudienceListRequest, - 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.analytics.data.v1alpha.ICreateAudienceListRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.analytics.data.v1alpha.IAudienceList, + protos.google.analytics.data.v1alpha.IAudienceListMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.analytics.data.v1alpha.IAudienceList, + protos.google.analytics.data.v1alpha.IAudienceListMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.analytics.data.v1alpha.IAudienceList, + protos.google.analytics.data.v1alpha.IAudienceListMetadata + >, + 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.analytics.data.v1alpha.IAudienceList, + protos.google.analytics.data.v1alpha.IAudienceListMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('createAudienceList response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('createAudienceList request %j', request); - return this.innerApiCalls.createAudienceList(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('createAudienceList response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .createAudienceList(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.analytics.data.v1alpha.IAudienceList, + protos.google.analytics.data.v1alpha.IAudienceListMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createAudienceList response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `createAudienceList()`. - * @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/v1alpha/alpha_analytics_data.create_audience_list.js - * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_CreateAudienceList_async - */ - async checkCreateAudienceListProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `createAudienceList()`. + * @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/v1alpha/alpha_analytics_data.create_audience_list.js + * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_CreateAudienceList_async + */ + async checkCreateAudienceListProgress( + name: string, + ): Promise< + LROperation< + protos.google.analytics.data.v1alpha.AudienceList, + protos.google.analytics.data.v1alpha.AudienceListMetadata + > + > { this._log.info('createAudienceList 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.createAudienceList, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createAudienceList, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.analytics.data.v1alpha.AudienceList, + protos.google.analytics.data.v1alpha.AudienceListMetadata + >; } -/** - * Initiates the creation of a report task. This method quickly - * returns a report task and initiates a long running - * asynchronous request to form a customized report of your Google Analytics - * event data. - * - * A report task will be retained and available for querying for 72 hours - * after it has been created. - * - * A report task created by one user can be listed and queried by all users - * who have access to the property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource where this report task will be created. - * Format: `properties/{propertyId}` - * @param {google.analytics.data.v1alpha.ReportTask} request.reportTask - * Required. The report task configuration 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 include:samples/generated/v1alpha/alpha_analytics_data.create_report_task.js - * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_CreateReportTask_async - */ + /** + * Initiates the creation of a report task. This method quickly + * returns a report task and initiates a long running + * asynchronous request to form a customized report of your Google Analytics + * event data. + * + * A report task will be retained and available for querying for 72 hours + * after it has been created. + * + * A report task created by one user can be listed and queried by all users + * who have access to the property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource where this report task will be created. + * Format: `properties/{propertyId}` + * @param {google.analytics.data.v1alpha.ReportTask} request.reportTask + * Required. The report task configuration 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 include:samples/generated/v1alpha/alpha_analytics_data.create_report_task.js + * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_CreateReportTask_async + */ createReportTask( - request?: protos.google.analytics.data.v1alpha.ICreateReportTaskRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.analytics.data.v1alpha.ICreateReportTaskRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.analytics.data.v1alpha.IReportTask, + protos.google.analytics.data.v1alpha.IReportTaskMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; createReportTask( - request: protos.google.analytics.data.v1alpha.ICreateReportTaskRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.ICreateReportTaskRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.analytics.data.v1alpha.IReportTask, + protos.google.analytics.data.v1alpha.IReportTaskMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createReportTask( - request: protos.google.analytics.data.v1alpha.ICreateReportTaskRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1alpha.ICreateReportTaskRequest, + callback: Callback< + LROperation< + protos.google.analytics.data.v1alpha.IReportTask, + protos.google.analytics.data.v1alpha.IReportTaskMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createReportTask( - request?: protos.google.analytics.data.v1alpha.ICreateReportTaskRequest, - 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.analytics.data.v1alpha.ICreateReportTaskRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.analytics.data.v1alpha.IReportTask, + protos.google.analytics.data.v1alpha.IReportTaskMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.analytics.data.v1alpha.IReportTask, + protos.google.analytics.data.v1alpha.IReportTaskMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.analytics.data.v1alpha.IReportTask, + protos.google.analytics.data.v1alpha.IReportTaskMetadata + >, + 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.analytics.data.v1alpha.IReportTask, + protos.google.analytics.data.v1alpha.IReportTaskMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('createReportTask response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('createReportTask request %j', request); - return this.innerApiCalls.createReportTask(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('createReportTask response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .createReportTask(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.analytics.data.v1alpha.IReportTask, + protos.google.analytics.data.v1alpha.IReportTaskMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createReportTask response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `createReportTask()`. - * @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/v1alpha/alpha_analytics_data.create_report_task.js - * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_CreateReportTask_async - */ - async checkCreateReportTaskProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `createReportTask()`. + * @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/v1alpha/alpha_analytics_data.create_report_task.js + * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_CreateReportTask_async + */ + async checkCreateReportTaskProgress( + name: string, + ): Promise< + LROperation< + protos.google.analytics.data.v1alpha.ReportTask, + protos.google.analytics.data.v1alpha.ReportTaskMetadata + > + > { this._log.info('createReportTask 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.createReportTask, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createReportTask, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.analytics.data.v1alpha.ReportTask, + protos.google.analytics.data.v1alpha.ReportTaskMetadata + >; } - /** - * Lists all audience lists for a property. This method can be used for you to - * find and reuse existing audience lists rather than creating unnecessary new - * audience lists. The same audience can have multiple audience lists that - * represent the list of users that were in an audience on different days. - * - * See [Creating an Audience - * List](https://developers.google.com/analytics/devguides/reporting/data/v1/audience-list-basics) - * for an introduction to Audience Lists with examples. - * - * This method is available at beta stability at - * [audienceExports.list](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties.audienceExports/list). - * To give your feedback on this API, complete the - * [Google Analytics Audience Export API - * Feedback](https://forms.gle/EeA5u5LW6PEggtCEA) form. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. All audience lists for this property will be listed in the - * response. Format: `properties/{property}` - * @param {number} [request.pageSize] - * Optional. The maximum number of audience lists to return. The service may - * return fewer than this value. If unspecified, at most 200 audience lists - * will be returned. The maximum value is 1000 (higher values will be coerced - * to the maximum). - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListAudienceLists` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListAudienceLists` must - * match the call that provided the page token. - * @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.analytics.data.v1alpha.AudienceList|AudienceList}. - * 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 `listAudienceListsAsync()` - * 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 audience lists for a property. This method can be used for you to + * find and reuse existing audience lists rather than creating unnecessary new + * audience lists. The same audience can have multiple audience lists that + * represent the list of users that were in an audience on different days. + * + * See [Creating an Audience + * List](https://developers.google.com/analytics/devguides/reporting/data/v1/audience-list-basics) + * for an introduction to Audience Lists with examples. + * + * This method is available at beta stability at + * [audienceExports.list](https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties.audienceExports/list). + * To give your feedback on this API, complete the + * [Google Analytics Audience Export API + * Feedback](https://forms.gle/EeA5u5LW6PEggtCEA) form. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. All audience lists for this property will be listed in the + * response. Format: `properties/{property}` + * @param {number} [request.pageSize] + * Optional. The maximum number of audience lists to return. The service may + * return fewer than this value. If unspecified, at most 200 audience lists + * will be returned. The maximum value is 1000 (higher values will be coerced + * to the maximum). + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListAudienceLists` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListAudienceLists` must + * match the call that provided the page token. + * @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.analytics.data.v1alpha.AudienceList|AudienceList}. + * 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 `listAudienceListsAsync()` + * 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. + */ listAudienceLists( - request?: protos.google.analytics.data.v1alpha.IListAudienceListsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.data.v1alpha.IAudienceList[], - protos.google.analytics.data.v1alpha.IListAudienceListsRequest|null, - protos.google.analytics.data.v1alpha.IListAudienceListsResponse - ]>; + request?: protos.google.analytics.data.v1alpha.IListAudienceListsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IAudienceList[], + protos.google.analytics.data.v1alpha.IListAudienceListsRequest | null, + protos.google.analytics.data.v1alpha.IListAudienceListsResponse, + ] + >; listAudienceLists( - request: protos.google.analytics.data.v1alpha.IListAudienceListsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.data.v1alpha.IListAudienceListsRequest, - protos.google.analytics.data.v1alpha.IListAudienceListsResponse|null|undefined, - protos.google.analytics.data.v1alpha.IAudienceList>): void; + request: protos.google.analytics.data.v1alpha.IListAudienceListsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.data.v1alpha.IListAudienceListsRequest, + | protos.google.analytics.data.v1alpha.IListAudienceListsResponse + | null + | undefined, + protos.google.analytics.data.v1alpha.IAudienceList + >, + ): void; listAudienceLists( - request: protos.google.analytics.data.v1alpha.IListAudienceListsRequest, - callback: PaginationCallback< - protos.google.analytics.data.v1alpha.IListAudienceListsRequest, - protos.google.analytics.data.v1alpha.IListAudienceListsResponse|null|undefined, - protos.google.analytics.data.v1alpha.IAudienceList>): void; + request: protos.google.analytics.data.v1alpha.IListAudienceListsRequest, + callback: PaginationCallback< + protos.google.analytics.data.v1alpha.IListAudienceListsRequest, + | protos.google.analytics.data.v1alpha.IListAudienceListsResponse + | null + | undefined, + protos.google.analytics.data.v1alpha.IAudienceList + >, + ): void; listAudienceLists( - request?: protos.google.analytics.data.v1alpha.IListAudienceListsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.data.v1alpha.IListAudienceListsRequest, - protos.google.analytics.data.v1alpha.IListAudienceListsResponse|null|undefined, - protos.google.analytics.data.v1alpha.IAudienceList>, - callback?: PaginationCallback< + request?: protos.google.analytics.data.v1alpha.IListAudienceListsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.data.v1alpha.IListAudienceListsRequest, - protos.google.analytics.data.v1alpha.IListAudienceListsResponse|null|undefined, - protos.google.analytics.data.v1alpha.IAudienceList>): - Promise<[ - protos.google.analytics.data.v1alpha.IAudienceList[], - protos.google.analytics.data.v1alpha.IListAudienceListsRequest|null, - protos.google.analytics.data.v1alpha.IListAudienceListsResponse - ]>|void { + | protos.google.analytics.data.v1alpha.IListAudienceListsResponse + | null + | undefined, + protos.google.analytics.data.v1alpha.IAudienceList + >, + callback?: PaginationCallback< + protos.google.analytics.data.v1alpha.IListAudienceListsRequest, + | protos.google.analytics.data.v1alpha.IListAudienceListsResponse + | null + | undefined, + protos.google.analytics.data.v1alpha.IAudienceList + >, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IAudienceList[], + protos.google.analytics.data.v1alpha.IListAudienceListsRequest | null, + protos.google.analytics.data.v1alpha.IListAudienceListsResponse, + ] + > | 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.analytics.data.v1alpha.IListAudienceListsRequest, - protos.google.analytics.data.v1alpha.IListAudienceListsResponse|null|undefined, - protos.google.analytics.data.v1alpha.IAudienceList>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.data.v1alpha.IListAudienceListsRequest, + | protos.google.analytics.data.v1alpha.IListAudienceListsResponse + | null + | undefined, + protos.google.analytics.data.v1alpha.IAudienceList + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listAudienceLists values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -2000,226 +2673,255 @@ export class AlphaAnalyticsDataClient { this._log.info('listAudienceLists request %j', request); return this.innerApiCalls .listAudienceLists(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.data.v1alpha.IAudienceList[], - protos.google.analytics.data.v1alpha.IListAudienceListsRequest|null, - protos.google.analytics.data.v1alpha.IListAudienceListsResponse - ]) => { - this._log.info('listAudienceLists values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.data.v1alpha.IAudienceList[], + protos.google.analytics.data.v1alpha.IListAudienceListsRequest | null, + protos.google.analytics.data.v1alpha.IListAudienceListsResponse, + ]) => { + this._log.info('listAudienceLists values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listAudienceLists`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. All audience lists for this property will be listed in the - * response. Format: `properties/{property}` - * @param {number} [request.pageSize] - * Optional. The maximum number of audience lists to return. The service may - * return fewer than this value. If unspecified, at most 200 audience lists - * will be returned. The maximum value is 1000 (higher values will be coerced - * to the maximum). - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListAudienceLists` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListAudienceLists` must - * match the call that provided the page token. - * @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.analytics.data.v1alpha.AudienceList|AudienceList} 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 `listAudienceListsAsync()` - * 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 `listAudienceLists`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. All audience lists for this property will be listed in the + * response. Format: `properties/{property}` + * @param {number} [request.pageSize] + * Optional. The maximum number of audience lists to return. The service may + * return fewer than this value. If unspecified, at most 200 audience lists + * will be returned. The maximum value is 1000 (higher values will be coerced + * to the maximum). + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListAudienceLists` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListAudienceLists` must + * match the call that provided the page token. + * @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.analytics.data.v1alpha.AudienceList|AudienceList} 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 `listAudienceListsAsync()` + * 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. + */ listAudienceListsStream( - request?: protos.google.analytics.data.v1alpha.IListAudienceListsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.data.v1alpha.IListAudienceListsRequest, + 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['listAudienceLists']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listAudienceLists stream %j', request); return this.descriptors.page.listAudienceLists.createStream( this.innerApiCalls.listAudienceLists as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listAudienceLists`, 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. All audience lists for this property will be listed in the - * response. Format: `properties/{property}` - * @param {number} [request.pageSize] - * Optional. The maximum number of audience lists to return. The service may - * return fewer than this value. If unspecified, at most 200 audience lists - * will be returned. The maximum value is 1000 (higher values will be coerced - * to the maximum). - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListAudienceLists` call. - * Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListAudienceLists` must - * match the call that provided the 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 protos.google.analytics.data.v1alpha.AudienceList|AudienceList}. 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 include:samples/generated/v1alpha/alpha_analytics_data.list_audience_lists.js - * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_ListAudienceLists_async - */ + /** + * Equivalent to `listAudienceLists`, 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. All audience lists for this property will be listed in the + * response. Format: `properties/{property}` + * @param {number} [request.pageSize] + * Optional. The maximum number of audience lists to return. The service may + * return fewer than this value. If unspecified, at most 200 audience lists + * will be returned. The maximum value is 1000 (higher values will be coerced + * to the maximum). + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListAudienceLists` call. + * Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListAudienceLists` must + * match the call that provided the 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 protos.google.analytics.data.v1alpha.AudienceList|AudienceList}. 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 include:samples/generated/v1alpha/alpha_analytics_data.list_audience_lists.js + * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_ListAudienceLists_async + */ listAudienceListsAsync( - request?: protos.google.analytics.data.v1alpha.IListAudienceListsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.data.v1alpha.IListAudienceListsRequest, + 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['listAudienceLists']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listAudienceLists iterate %j', request); return this.descriptors.page.listAudienceLists.asyncIterate( this.innerApiCalls['listAudienceLists'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists all recurring audience lists for a property. This method can be used - * for you to find and reuse existing recurring audience lists rather than - * creating unnecessary new recurring audience lists. The same audience can - * have multiple recurring audience lists that represent different dimension - * combinations; for example, just the dimension `deviceId` or both the - * dimensions `deviceId` and `userId`. - * - * This method is introduced at alpha stability with the intention of - * gathering feedback on syntax and capabilities before entering beta. To give - * your feedback on this API, complete the - * [Google Analytics Audience Export API - * Feedback](https://forms.gle/EeA5u5LW6PEggtCEA) form. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. All recurring audience lists for this property will be listed in - * the response. Format: `properties/{property}` - * @param {number} [request.pageSize] - * Optional. The maximum number of recurring audience lists to return. The - * service may return fewer than this value. If unspecified, at most 200 - * recurring audience lists will be returned. The maximum value is 1000 - * (higher values will be coerced to the maximum). - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListRecurringAudienceLists` call. Provide this to retrieve the subsequent - * page. - * - * When paginating, all other parameters provided to - * `ListRecurringAudienceLists` must match the call that provided the page - * token. - * @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.analytics.data.v1alpha.RecurringAudienceList|RecurringAudienceList}. - * 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 `listRecurringAudienceListsAsync()` - * 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 recurring audience lists for a property. This method can be used + * for you to find and reuse existing recurring audience lists rather than + * creating unnecessary new recurring audience lists. The same audience can + * have multiple recurring audience lists that represent different dimension + * combinations; for example, just the dimension `deviceId` or both the + * dimensions `deviceId` and `userId`. + * + * This method is introduced at alpha stability with the intention of + * gathering feedback on syntax and capabilities before entering beta. To give + * your feedback on this API, complete the + * [Google Analytics Audience Export API + * Feedback](https://forms.gle/EeA5u5LW6PEggtCEA) form. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. All recurring audience lists for this property will be listed in + * the response. Format: `properties/{property}` + * @param {number} [request.pageSize] + * Optional. The maximum number of recurring audience lists to return. The + * service may return fewer than this value. If unspecified, at most 200 + * recurring audience lists will be returned. The maximum value is 1000 + * (higher values will be coerced to the maximum). + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListRecurringAudienceLists` call. Provide this to retrieve the subsequent + * page. + * + * When paginating, all other parameters provided to + * `ListRecurringAudienceLists` must match the call that provided the page + * token. + * @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.analytics.data.v1alpha.RecurringAudienceList|RecurringAudienceList}. + * 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 `listRecurringAudienceListsAsync()` + * 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. + */ listRecurringAudienceLists( - request?: protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.data.v1alpha.IRecurringAudienceList[], - protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest|null, - protos.google.analytics.data.v1alpha.IListRecurringAudienceListsResponse - ]>; + request?: protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IRecurringAudienceList[], + protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest | null, + protos.google.analytics.data.v1alpha.IListRecurringAudienceListsResponse, + ] + >; listRecurringAudienceLists( - request: protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest, - protos.google.analytics.data.v1alpha.IListRecurringAudienceListsResponse|null|undefined, - protos.google.analytics.data.v1alpha.IRecurringAudienceList>): void; + request: protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest, + | protos.google.analytics.data.v1alpha.IListRecurringAudienceListsResponse + | null + | undefined, + protos.google.analytics.data.v1alpha.IRecurringAudienceList + >, + ): void; listRecurringAudienceLists( - request: protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest, - callback: PaginationCallback< - protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest, - protos.google.analytics.data.v1alpha.IListRecurringAudienceListsResponse|null|undefined, - protos.google.analytics.data.v1alpha.IRecurringAudienceList>): void; + request: protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest, + callback: PaginationCallback< + protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest, + | protos.google.analytics.data.v1alpha.IListRecurringAudienceListsResponse + | null + | undefined, + protos.google.analytics.data.v1alpha.IRecurringAudienceList + >, + ): void; listRecurringAudienceLists( - request?: protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest, - protos.google.analytics.data.v1alpha.IListRecurringAudienceListsResponse|null|undefined, - protos.google.analytics.data.v1alpha.IRecurringAudienceList>, - callback?: PaginationCallback< + request?: protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest, - protos.google.analytics.data.v1alpha.IListRecurringAudienceListsResponse|null|undefined, - protos.google.analytics.data.v1alpha.IRecurringAudienceList>): - Promise<[ - protos.google.analytics.data.v1alpha.IRecurringAudienceList[], - protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest|null, - protos.google.analytics.data.v1alpha.IListRecurringAudienceListsResponse - ]>|void { + | protos.google.analytics.data.v1alpha.IListRecurringAudienceListsResponse + | null + | undefined, + protos.google.analytics.data.v1alpha.IRecurringAudienceList + >, + callback?: PaginationCallback< + protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest, + | protos.google.analytics.data.v1alpha.IListRecurringAudienceListsResponse + | null + | undefined, + protos.google.analytics.data.v1alpha.IRecurringAudienceList + >, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IRecurringAudienceList[], + protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest | null, + protos.google.analytics.data.v1alpha.IListRecurringAudienceListsResponse, + ] + > | 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.analytics.data.v1alpha.IListRecurringAudienceListsRequest, - protos.google.analytics.data.v1alpha.IListRecurringAudienceListsResponse|null|undefined, - protos.google.analytics.data.v1alpha.IRecurringAudienceList>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest, + | protos.google.analytics.data.v1alpha.IListRecurringAudienceListsResponse + | null + | undefined, + protos.google.analytics.data.v1alpha.IRecurringAudienceList + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listRecurringAudienceLists values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -2228,211 +2930,240 @@ export class AlphaAnalyticsDataClient { this._log.info('listRecurringAudienceLists request %j', request); return this.innerApiCalls .listRecurringAudienceLists(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.data.v1alpha.IRecurringAudienceList[], - protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest|null, - protos.google.analytics.data.v1alpha.IListRecurringAudienceListsResponse - ]) => { - this._log.info('listRecurringAudienceLists values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.data.v1alpha.IRecurringAudienceList[], + protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest | null, + protos.google.analytics.data.v1alpha.IListRecurringAudienceListsResponse, + ]) => { + this._log.info('listRecurringAudienceLists values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listRecurringAudienceLists`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. All recurring audience lists for this property will be listed in - * the response. Format: `properties/{property}` - * @param {number} [request.pageSize] - * Optional. The maximum number of recurring audience lists to return. The - * service may return fewer than this value. If unspecified, at most 200 - * recurring audience lists will be returned. The maximum value is 1000 - * (higher values will be coerced to the maximum). - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListRecurringAudienceLists` call. Provide this to retrieve the subsequent - * page. - * - * When paginating, all other parameters provided to - * `ListRecurringAudienceLists` must match the call that provided the page - * token. - * @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.analytics.data.v1alpha.RecurringAudienceList|RecurringAudienceList} 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 `listRecurringAudienceListsAsync()` - * 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 `listRecurringAudienceLists`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. All recurring audience lists for this property will be listed in + * the response. Format: `properties/{property}` + * @param {number} [request.pageSize] + * Optional. The maximum number of recurring audience lists to return. The + * service may return fewer than this value. If unspecified, at most 200 + * recurring audience lists will be returned. The maximum value is 1000 + * (higher values will be coerced to the maximum). + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListRecurringAudienceLists` call. Provide this to retrieve the subsequent + * page. + * + * When paginating, all other parameters provided to + * `ListRecurringAudienceLists` must match the call that provided the page + * token. + * @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.analytics.data.v1alpha.RecurringAudienceList|RecurringAudienceList} 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 `listRecurringAudienceListsAsync()` + * 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. + */ listRecurringAudienceListsStream( - request?: protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest, + 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['listRecurringAudienceLists']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listRecurringAudienceLists stream %j', request); return this.descriptors.page.listRecurringAudienceLists.createStream( this.innerApiCalls.listRecurringAudienceLists as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listRecurringAudienceLists`, 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. All recurring audience lists for this property will be listed in - * the response. Format: `properties/{property}` - * @param {number} [request.pageSize] - * Optional. The maximum number of recurring audience lists to return. The - * service may return fewer than this value. If unspecified, at most 200 - * recurring audience lists will be returned. The maximum value is 1000 - * (higher values will be coerced to the maximum). - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous - * `ListRecurringAudienceLists` call. Provide this to retrieve the subsequent - * page. - * - * When paginating, all other parameters provided to - * `ListRecurringAudienceLists` must match the call that provided the 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 protos.google.analytics.data.v1alpha.RecurringAudienceList|RecurringAudienceList}. 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 include:samples/generated/v1alpha/alpha_analytics_data.list_recurring_audience_lists.js - * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_ListRecurringAudienceLists_async - */ + /** + * Equivalent to `listRecurringAudienceLists`, 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. All recurring audience lists for this property will be listed in + * the response. Format: `properties/{property}` + * @param {number} [request.pageSize] + * Optional. The maximum number of recurring audience lists to return. The + * service may return fewer than this value. If unspecified, at most 200 + * recurring audience lists will be returned. The maximum value is 1000 + * (higher values will be coerced to the maximum). + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous + * `ListRecurringAudienceLists` call. Provide this to retrieve the subsequent + * page. + * + * When paginating, all other parameters provided to + * `ListRecurringAudienceLists` must match the call that provided the 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 protos.google.analytics.data.v1alpha.RecurringAudienceList|RecurringAudienceList}. 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 include:samples/generated/v1alpha/alpha_analytics_data.list_recurring_audience_lists.js + * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_ListRecurringAudienceLists_async + */ listRecurringAudienceListsAsync( - request?: protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.data.v1alpha.IListRecurringAudienceListsRequest, + 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['listRecurringAudienceLists']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listRecurringAudienceLists iterate %j', request); return this.descriptors.page.listRecurringAudienceLists.asyncIterate( this.innerApiCalls['listRecurringAudienceLists'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists all report tasks for a property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. All report tasks for this property will be listed in the - * response. Format: `properties/{property}` - * @param {number} [request.pageSize] - * Optional. The maximum number of report tasks to return. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListReportTasks` call. - * Provide this to retrieve the subsequent page. - * @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.analytics.data.v1alpha.ReportTask|ReportTask}. - * 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 `listReportTasksAsync()` - * 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 report tasks for a property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. All report tasks for this property will be listed in the + * response. Format: `properties/{property}` + * @param {number} [request.pageSize] + * Optional. The maximum number of report tasks to return. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListReportTasks` call. + * Provide this to retrieve the subsequent page. + * @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.analytics.data.v1alpha.ReportTask|ReportTask}. + * 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 `listReportTasksAsync()` + * 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. + */ listReportTasks( - request?: protos.google.analytics.data.v1alpha.IListReportTasksRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.data.v1alpha.IReportTask[], - protos.google.analytics.data.v1alpha.IListReportTasksRequest|null, - protos.google.analytics.data.v1alpha.IListReportTasksResponse - ]>; + request?: protos.google.analytics.data.v1alpha.IListReportTasksRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IReportTask[], + protos.google.analytics.data.v1alpha.IListReportTasksRequest | null, + protos.google.analytics.data.v1alpha.IListReportTasksResponse, + ] + >; listReportTasks( - request: protos.google.analytics.data.v1alpha.IListReportTasksRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.data.v1alpha.IListReportTasksRequest, - protos.google.analytics.data.v1alpha.IListReportTasksResponse|null|undefined, - protos.google.analytics.data.v1alpha.IReportTask>): void; + request: protos.google.analytics.data.v1alpha.IListReportTasksRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.data.v1alpha.IListReportTasksRequest, + | protos.google.analytics.data.v1alpha.IListReportTasksResponse + | null + | undefined, + protos.google.analytics.data.v1alpha.IReportTask + >, + ): void; listReportTasks( - request: protos.google.analytics.data.v1alpha.IListReportTasksRequest, - callback: PaginationCallback< - protos.google.analytics.data.v1alpha.IListReportTasksRequest, - protos.google.analytics.data.v1alpha.IListReportTasksResponse|null|undefined, - protos.google.analytics.data.v1alpha.IReportTask>): void; + request: protos.google.analytics.data.v1alpha.IListReportTasksRequest, + callback: PaginationCallback< + protos.google.analytics.data.v1alpha.IListReportTasksRequest, + | protos.google.analytics.data.v1alpha.IListReportTasksResponse + | null + | undefined, + protos.google.analytics.data.v1alpha.IReportTask + >, + ): void; listReportTasks( - request?: protos.google.analytics.data.v1alpha.IListReportTasksRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.data.v1alpha.IListReportTasksRequest, - protos.google.analytics.data.v1alpha.IListReportTasksResponse|null|undefined, - protos.google.analytics.data.v1alpha.IReportTask>, - callback?: PaginationCallback< + request?: protos.google.analytics.data.v1alpha.IListReportTasksRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.data.v1alpha.IListReportTasksRequest, - protos.google.analytics.data.v1alpha.IListReportTasksResponse|null|undefined, - protos.google.analytics.data.v1alpha.IReportTask>): - Promise<[ - protos.google.analytics.data.v1alpha.IReportTask[], - protos.google.analytics.data.v1alpha.IListReportTasksRequest|null, - protos.google.analytics.data.v1alpha.IListReportTasksResponse - ]>|void { + | protos.google.analytics.data.v1alpha.IListReportTasksResponse + | null + | undefined, + protos.google.analytics.data.v1alpha.IReportTask + >, + callback?: PaginationCallback< + protos.google.analytics.data.v1alpha.IListReportTasksRequest, + | protos.google.analytics.data.v1alpha.IListReportTasksResponse + | null + | undefined, + protos.google.analytics.data.v1alpha.IReportTask + >, + ): Promise< + [ + protos.google.analytics.data.v1alpha.IReportTask[], + protos.google.analytics.data.v1alpha.IListReportTasksRequest | null, + protos.google.analytics.data.v1alpha.IListReportTasksResponse, + ] + > | 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.analytics.data.v1alpha.IListReportTasksRequest, - protos.google.analytics.data.v1alpha.IListReportTasksResponse|null|undefined, - protos.google.analytics.data.v1alpha.IReportTask>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.data.v1alpha.IListReportTasksRequest, + | protos.google.analytics.data.v1alpha.IListReportTasksResponse + | null + | undefined, + protos.google.analytics.data.v1alpha.IReportTask + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listReportTasks values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -2441,113 +3172,117 @@ export class AlphaAnalyticsDataClient { this._log.info('listReportTasks request %j', request); return this.innerApiCalls .listReportTasks(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.data.v1alpha.IReportTask[], - protos.google.analytics.data.v1alpha.IListReportTasksRequest|null, - protos.google.analytics.data.v1alpha.IListReportTasksResponse - ]) => { - this._log.info('listReportTasks values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.data.v1alpha.IReportTask[], + protos.google.analytics.data.v1alpha.IListReportTasksRequest | null, + protos.google.analytics.data.v1alpha.IListReportTasksResponse, + ]) => { + this._log.info('listReportTasks values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listReportTasks`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. All report tasks for this property will be listed in the - * response. Format: `properties/{property}` - * @param {number} [request.pageSize] - * Optional. The maximum number of report tasks to return. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListReportTasks` call. - * Provide this to retrieve the subsequent page. - * @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.analytics.data.v1alpha.ReportTask|ReportTask} 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 `listReportTasksAsync()` - * 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 `listReportTasks`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. All report tasks for this property will be listed in the + * response. Format: `properties/{property}` + * @param {number} [request.pageSize] + * Optional. The maximum number of report tasks to return. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListReportTasks` call. + * Provide this to retrieve the subsequent page. + * @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.analytics.data.v1alpha.ReportTask|ReportTask} 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 `listReportTasksAsync()` + * 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. + */ listReportTasksStream( - request?: protos.google.analytics.data.v1alpha.IListReportTasksRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.data.v1alpha.IListReportTasksRequest, + 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['listReportTasks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listReportTasks stream %j', request); return this.descriptors.page.listReportTasks.createStream( this.innerApiCalls.listReportTasks as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listReportTasks`, 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. All report tasks for this property will be listed in the - * response. Format: `properties/{property}` - * @param {number} [request.pageSize] - * Optional. The maximum number of report tasks to return. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListReportTasks` call. - * Provide this to retrieve the subsequent page. - * @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.analytics.data.v1alpha.ReportTask|ReportTask}. 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 include:samples/generated/v1alpha/alpha_analytics_data.list_report_tasks.js - * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_ListReportTasks_async - */ + /** + * Equivalent to `listReportTasks`, 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. All report tasks for this property will be listed in the + * response. Format: `properties/{property}` + * @param {number} [request.pageSize] + * Optional. The maximum number of report tasks to return. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListReportTasks` call. + * Provide this to retrieve the subsequent page. + * @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.analytics.data.v1alpha.ReportTask|ReportTask}. 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 include:samples/generated/v1alpha/alpha_analytics_data.list_report_tasks.js + * region_tag:analyticsdata_v1alpha_generated_AlphaAnalyticsData_ListReportTasks_async + */ listReportTasksAsync( - request?: protos.google.analytics.data.v1alpha.IListReportTasksRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.data.v1alpha.IListReportTasksRequest, + 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['listReportTasks']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listReportTasks iterate %j', request); return this.descriptors.page.listReportTasks.asyncIterate( this.innerApiCalls['listReportTasks'] as GaxCall, request as {}, - callSettings + callSettings, ) as 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. @@ -2590,22 +3325,22 @@ export class AlphaAnalyticsDataClient { protos.google.longrunning.Operation, protos.google.longrunning.GetOperationRequest, {} | 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); } /** @@ -2640,15 +3375,15 @@ export class AlphaAnalyticsDataClient { */ listOperationsAsync( request: protos.google.longrunning.ListOperationsRequest, - options?: gax.CallOptions + 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); } /** @@ -2682,7 +3417,7 @@ export class AlphaAnalyticsDataClient { * await client.cancelOperation({name: ''}); * ``` */ - cancelOperation( + cancelOperation( request: protos.google.longrunning.CancelOperationRequest, optionsOrCallback?: | gax.CallOptions @@ -2695,25 +3430,24 @@ export class AlphaAnalyticsDataClient { protos.google.longrunning.CancelOperationRequest, protos.google.protobuf.Empty, {} | 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); } - /** * Deletes a long-running operation. This method indicates that the client is * no longer interested in the operation result. It does not cancel the @@ -2752,22 +3486,22 @@ export class AlphaAnalyticsDataClient { protos.google.protobuf.Empty, protos.google.longrunning.DeleteOperationRequest, {} | 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); } @@ -2782,7 +3516,7 @@ export class AlphaAnalyticsDataClient { * @param {string} audience_list * @returns {string} Resource name string. */ - audienceListPath(property:string,audienceList:string) { + audienceListPath(property: string, audienceList: string) { return this.pathTemplates.audienceListPathTemplate.render({ property: property, audience_list: audienceList, @@ -2797,7 +3531,8 @@ export class AlphaAnalyticsDataClient { * @returns {string} A string representing the property. */ matchPropertyFromAudienceListName(audienceListName: string) { - return this.pathTemplates.audienceListPathTemplate.match(audienceListName).property; + return this.pathTemplates.audienceListPathTemplate.match(audienceListName) + .property; } /** @@ -2808,7 +3543,8 @@ export class AlphaAnalyticsDataClient { * @returns {string} A string representing the audience_list. */ matchAudienceListFromAudienceListName(audienceListName: string) { - return this.pathTemplates.audienceListPathTemplate.match(audienceListName).audience_list; + return this.pathTemplates.audienceListPathTemplate.match(audienceListName) + .audience_list; } /** @@ -2817,7 +3553,7 @@ export class AlphaAnalyticsDataClient { * @param {string} property * @returns {string} Resource name string. */ - metadataPath(property:string) { + metadataPath(property: string) { return this.pathTemplates.metadataPathTemplate.render({ property: property, }); @@ -2840,7 +3576,7 @@ export class AlphaAnalyticsDataClient { * @param {string} property * @returns {string} Resource name string. */ - propertyPath(property:string) { + propertyPath(property: string) { return this.pathTemplates.propertyPathTemplate.render({ property: property, }); @@ -2863,7 +3599,7 @@ export class AlphaAnalyticsDataClient { * @param {string} property * @returns {string} Resource name string. */ - propertyQuotasSnapshotPath(property:string) { + propertyQuotasSnapshotPath(property: string) { return this.pathTemplates.propertyQuotasSnapshotPathTemplate.render({ property: property, }); @@ -2876,8 +3612,12 @@ export class AlphaAnalyticsDataClient { * A fully-qualified path representing PropertyQuotasSnapshot resource. * @returns {string} A string representing the property. */ - matchPropertyFromPropertyQuotasSnapshotName(propertyQuotasSnapshotName: string) { - return this.pathTemplates.propertyQuotasSnapshotPathTemplate.match(propertyQuotasSnapshotName).property; + matchPropertyFromPropertyQuotasSnapshotName( + propertyQuotasSnapshotName: string, + ) { + return this.pathTemplates.propertyQuotasSnapshotPathTemplate.match( + propertyQuotasSnapshotName, + ).property; } /** @@ -2887,7 +3627,7 @@ export class AlphaAnalyticsDataClient { * @param {string} recurring_audience_list * @returns {string} Resource name string. */ - recurringAudienceListPath(property:string,recurringAudienceList:string) { + recurringAudienceListPath(property: string, recurringAudienceList: string) { return this.pathTemplates.recurringAudienceListPathTemplate.render({ property: property, recurring_audience_list: recurringAudienceList, @@ -2901,8 +3641,12 @@ export class AlphaAnalyticsDataClient { * A fully-qualified path representing RecurringAudienceList resource. * @returns {string} A string representing the property. */ - matchPropertyFromRecurringAudienceListName(recurringAudienceListName: string) { - return this.pathTemplates.recurringAudienceListPathTemplate.match(recurringAudienceListName).property; + matchPropertyFromRecurringAudienceListName( + recurringAudienceListName: string, + ) { + return this.pathTemplates.recurringAudienceListPathTemplate.match( + recurringAudienceListName, + ).property; } /** @@ -2912,8 +3656,12 @@ export class AlphaAnalyticsDataClient { * A fully-qualified path representing RecurringAudienceList resource. * @returns {string} A string representing the recurring_audience_list. */ - matchRecurringAudienceListFromRecurringAudienceListName(recurringAudienceListName: string) { - return this.pathTemplates.recurringAudienceListPathTemplate.match(recurringAudienceListName).recurring_audience_list; + matchRecurringAudienceListFromRecurringAudienceListName( + recurringAudienceListName: string, + ) { + return this.pathTemplates.recurringAudienceListPathTemplate.match( + recurringAudienceListName, + ).recurring_audience_list; } /** @@ -2923,7 +3671,7 @@ export class AlphaAnalyticsDataClient { * @param {string} report_task * @returns {string} Resource name string. */ - reportTaskPath(property:string,reportTask:string) { + reportTaskPath(property: string, reportTask: string) { return this.pathTemplates.reportTaskPathTemplate.render({ property: property, report_task: reportTask, @@ -2938,7 +3686,8 @@ export class AlphaAnalyticsDataClient { * @returns {string} A string representing the property. */ matchPropertyFromReportTaskName(reportTaskName: string) { - return this.pathTemplates.reportTaskPathTemplate.match(reportTaskName).property; + return this.pathTemplates.reportTaskPathTemplate.match(reportTaskName) + .property; } /** @@ -2949,7 +3698,8 @@ export class AlphaAnalyticsDataClient { * @returns {string} A string representing the report_task. */ matchReportTaskFromReportTaskName(reportTaskName: string) { - return this.pathTemplates.reportTaskPathTemplate.match(reportTaskName).report_task; + return this.pathTemplates.reportTaskPathTemplate.match(reportTaskName) + .report_task; } /** @@ -2960,7 +3710,7 @@ export class AlphaAnalyticsDataClient { */ close(): Promise { if (this.alphaAnalyticsDataStub && !this._terminated) { - return this.alphaAnalyticsDataStub.then(stub => { + return this.alphaAnalyticsDataStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2969,4 +3719,4 @@ export class AlphaAnalyticsDataClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-analytics-data/src/v1alpha/index.ts b/packages/google-analytics-data/src/v1alpha/index.ts index ad8f01f138b3..ec6a3361eba0 100644 --- a/packages/google-analytics-data/src/v1alpha/index.ts +++ b/packages/google-analytics-data/src/v1alpha/index.ts @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {AlphaAnalyticsDataClient} from './alpha_analytics_data_client'; +export { AlphaAnalyticsDataClient } from './alpha_analytics_data_client'; diff --git a/packages/google-analytics-data/src/v1beta/beta_analytics_data_client.ts b/packages/google-analytics-data/src/v1beta/beta_analytics_data_client.ts index 64d219c3e6bc..fd7ced5d8238 100644 --- a/packages/google-analytics-data/src/v1beta/beta_analytics_data_client.ts +++ b/packages/google-analytics-data/src/v1beta/beta_analytics_data_client.ts @@ -18,11 +18,20 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +53,7 @@ export class BetaAnalyticsDataClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('data'); @@ -57,10 +66,10 @@ export class BetaAnalyticsDataClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - betaAnalyticsDataStub?: Promise<{[name: string]: Function}>; + betaAnalyticsDataStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of BetaAnalyticsDataClient. @@ -101,21 +110,42 @@ export class BetaAnalyticsDataClient { * const client = new BetaAnalyticsDataClient({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 BetaAnalyticsDataClient; - 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 = 'analyticsdata.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -140,7 +170,7 @@ export class BetaAnalyticsDataClient { 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; @@ -154,10 +184,7 @@ export class BetaAnalyticsDataClient { } // 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 { @@ -179,13 +206,13 @@ export class BetaAnalyticsDataClient { // Create useful helper objects for these. this.pathTemplates = { audienceExportPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/audienceExports/{audience_export}' + 'properties/{property}/audienceExports/{audience_export}', ), metadataPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}/metadata' + 'properties/{property}/metadata', ), propertyPathTemplate: new this._gaxModule.PathTemplate( - 'properties/{property}' + 'properties/{property}', ), }; @@ -193,8 +220,11 @@ export class BetaAnalyticsDataClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listAudienceExports: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'audienceExports') + listAudienceExports: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'audienceExports', + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -203,29 +233,37 @@ export class BetaAnalyticsDataClient { // 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 = []; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const createAudienceExportResponse = protoFilesRoot.lookup( - '.google.analytics.data.v1beta.AudienceExport') as gax.protobuf.Type; + '.google.analytics.data.v1beta.AudienceExport', + ) as gax.protobuf.Type; const createAudienceExportMetadata = protoFilesRoot.lookup( - '.google.analytics.data.v1beta.AudienceExportMetadata') as gax.protobuf.Type; + '.google.analytics.data.v1beta.AudienceExportMetadata', + ) as gax.protobuf.Type; this.descriptors.longrunning = { createAudienceExport: new this._gaxModule.LongrunningDescriptor( this.operationsClient, createAudienceExportResponse.decode.bind(createAudienceExportResponse), - createAudienceExportMetadata.decode.bind(createAudienceExportMetadata)) + createAudienceExportMetadata.decode.bind(createAudienceExportMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.analytics.data.v1beta.BetaAnalyticsData', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.analytics.data.v1beta.BetaAnalyticsData', + 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 @@ -256,28 +294,45 @@ export class BetaAnalyticsDataClient { // Put together the "service stub" for // google.analytics.data.v1beta.BetaAnalyticsData. this.betaAnalyticsDataStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.analytics.data.v1beta.BetaAnalyticsData') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.analytics.data.v1beta.BetaAnalyticsData', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.analytics.data.v1beta.BetaAnalyticsData, - 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 betaAnalyticsDataStubMethods = - ['runReport', 'runPivotReport', 'batchRunReports', 'batchRunPivotReports', 'getMetadata', 'runRealtimeReport', 'checkCompatibility', 'createAudienceExport', 'queryAudienceExport', 'getAudienceExport', 'listAudienceExports']; + const betaAnalyticsDataStubMethods = [ + 'runReport', + 'runPivotReport', + 'batchRunReports', + 'batchRunPivotReports', + 'getMetadata', + 'runRealtimeReport', + 'checkCompatibility', + 'createAudienceExport', + 'queryAudienceExport', + 'getAudienceExport', + 'listAudienceExports', + ]; for (const methodName of betaAnalyticsDataStubMethods) { const callPromise = this.betaAnalyticsDataStub.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] || @@ -287,7 +342,7 @@ export class BetaAnalyticsDataClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -302,8 +357,14 @@ export class BetaAnalyticsDataClient { * @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 'analyticsdata.googleapis.com'; } @@ -314,8 +375,14 @@ export class BetaAnalyticsDataClient { * @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 'analyticsdata.googleapis.com'; } @@ -348,7 +415,7 @@ export class BetaAnalyticsDataClient { static get scopes() { return [ 'https://www.googleapis.com/auth/analytics', - 'https://www.googleapis.com/auth/analytics.readonly' + 'https://www.googleapis.com/auth/analytics.readonly', ]; } @@ -358,8 +425,9 @@ export class BetaAnalyticsDataClient { * 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; @@ -370,1413 +438,1893 @@ export class BetaAnalyticsDataClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Returns a customized report of your Google Analytics event data. Reports - * contain statistics derived from data collected by the Google Analytics - * tracking code. The data returned from the API is as a table with columns - * for the requested dimensions and metrics. Metrics are individual - * measurements of user activity on your property, such as active users or - * event count. Dimensions break down metrics across some common criteria, - * such as country or event name. - * - * For a guide to constructing requests & understanding responses, see - * [Creating a - * Report](https://developers.google.com/analytics/devguides/reporting/data/v1/basics). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.property - * A Google Analytics property identifier whose events are tracked. - * Specified in the URL path and not the body. To learn more, see [where to - * find your Property - * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id). - * Within a batch request, this property should either be unspecified or - * consistent with the batch-level property. - * - * Example: properties/1234 - * @param {number[]} request.dimensions - * The dimensions requested and displayed. - * @param {number[]} request.metrics - * The metrics requested and displayed. - * @param {number[]} request.dateRanges - * Date ranges of data to read. If multiple date ranges are requested, each - * response row will contain a zero based date range index. If two date - * ranges overlap, the event data for the overlapping days is included in the - * response rows for both date ranges. In a cohort request, this `dateRanges` - * must be unspecified. - * @param {google.analytics.data.v1beta.FilterExpression} request.dimensionFilter - * Dimension filters let you ask for only specific dimension values in - * the report. To learn more, see [Fundamentals of Dimension - * Filters](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#dimension_filters) - * for examples. Metrics cannot be used in this filter. - * @param {google.analytics.data.v1beta.FilterExpression} request.metricFilter - * The filter clause of metrics. Applied after aggregating the report's rows, - * similar to SQL having-clause. Dimensions cannot be used in this filter. - * @param {number} request.offset - * The row count of the start row. The first row is counted as row 0. - * - * When paging, the first request does not specify offset; or equivalently, - * sets offset to 0; the first request returns the first `limit` of rows. The - * second request sets offset to the `limit` of the first request; the second - * request returns the second `limit` of rows. - * - * To learn more about this pagination parameter, see - * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). - * @param {number} request.limit - * The number of rows to return. If unspecified, 10,000 rows are returned. The - * API returns a maximum of 250,000 rows per request, no matter how many you - * ask for. `limit` must be positive. - * - * The API can also return fewer rows than the requested `limit`, if there - * aren't as many dimension values as the `limit`. For instance, there are - * fewer than 300 possible values for the dimension `country`, so when - * reporting on only `country`, you can't get more than 300 rows, even if you - * set `limit` to a higher value. - * - * To learn more about this pagination parameter, see - * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). - * @param {number[]} request.metricAggregations - * Aggregation of metrics. Aggregated metric values will be shown in rows - * where the dimension_values are set to "RESERVED_(MetricAggregation)". - * Aggregates including both comparisons and multiple date ranges will - * be aggregated based on the date ranges. - * @param {number[]} request.orderBys - * Specifies how rows are ordered in the response. - * Requests including both comparisons and multiple date ranges will - * have order bys applied on the comparisons. - * @param {string} request.currencyCode - * A currency code in ISO4217 format, such as "AED", "USD", "JPY". - * If the field is empty, the report uses the property's default currency. - * @param {google.analytics.data.v1beta.CohortSpec} request.cohortSpec - * Cohort group associated with this request. If there is a cohort group - * in the request the 'cohort' dimension must be present. - * @param {boolean} request.keepEmptyRows - * If false or unspecified, each row with all metrics equal to 0 will not be - * returned. If true, these rows will be returned if they are not separately - * removed by a filter. - * - * Regardless of this `keep_empty_rows` setting, only data recorded by the - * Google Analytics property can be displayed in a report. - * - * For example if a property never logs a `purchase` event, then a query for - * the `eventName` dimension and `eventCount` metric will not have a row - * eventName: "purchase" and eventCount: 0. - * @param {boolean} request.returnPropertyQuota - * Toggles whether to return the current state of this Google Analytics - * property's quota. Quota is returned in [PropertyQuota](#PropertyQuota). - * @param {number[]} [request.comparisons] - * Optional. The configuration of comparisons requested and displayed. The - * request only requires a comparisons field in order to receive a comparison - * column 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.analytics.data.v1beta.RunReportResponse|RunReportResponse}. - * 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/v1beta/beta_analytics_data.run_report.js - * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_RunReport_async - */ + /** + * Returns a customized report of your Google Analytics event data. Reports + * contain statistics derived from data collected by the Google Analytics + * tracking code. The data returned from the API is as a table with columns + * for the requested dimensions and metrics. Metrics are individual + * measurements of user activity on your property, such as active users or + * event count. Dimensions break down metrics across some common criteria, + * such as country or event name. + * + * For a guide to constructing requests & understanding responses, see + * [Creating a + * Report](https://developers.google.com/analytics/devguides/reporting/data/v1/basics). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.property + * A Google Analytics property identifier whose events are tracked. + * Specified in the URL path and not the body. To learn more, see [where to + * find your Property + * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id). + * Within a batch request, this property should either be unspecified or + * consistent with the batch-level property. + * + * Example: properties/1234 + * @param {number[]} request.dimensions + * The dimensions requested and displayed. + * @param {number[]} request.metrics + * The metrics requested and displayed. + * @param {number[]} request.dateRanges + * Date ranges of data to read. If multiple date ranges are requested, each + * response row will contain a zero based date range index. If two date + * ranges overlap, the event data for the overlapping days is included in the + * response rows for both date ranges. In a cohort request, this `dateRanges` + * must be unspecified. + * @param {google.analytics.data.v1beta.FilterExpression} request.dimensionFilter + * Dimension filters let you ask for only specific dimension values in + * the report. To learn more, see [Fundamentals of Dimension + * Filters](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#dimension_filters) + * for examples. Metrics cannot be used in this filter. + * @param {google.analytics.data.v1beta.FilterExpression} request.metricFilter + * The filter clause of metrics. Applied after aggregating the report's rows, + * similar to SQL having-clause. Dimensions cannot be used in this filter. + * @param {number} request.offset + * The row count of the start row. The first row is counted as row 0. + * + * When paging, the first request does not specify offset; or equivalently, + * sets offset to 0; the first request returns the first `limit` of rows. The + * second request sets offset to the `limit` of the first request; the second + * request returns the second `limit` of rows. + * + * To learn more about this pagination parameter, see + * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). + * @param {number} request.limit + * The number of rows to return. If unspecified, 10,000 rows are returned. The + * API returns a maximum of 250,000 rows per request, no matter how many you + * ask for. `limit` must be positive. + * + * The API can also return fewer rows than the requested `limit`, if there + * aren't as many dimension values as the `limit`. For instance, there are + * fewer than 300 possible values for the dimension `country`, so when + * reporting on only `country`, you can't get more than 300 rows, even if you + * set `limit` to a higher value. + * + * To learn more about this pagination parameter, see + * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). + * @param {number[]} request.metricAggregations + * Aggregation of metrics. Aggregated metric values will be shown in rows + * where the dimension_values are set to "RESERVED_(MetricAggregation)". + * Aggregates including both comparisons and multiple date ranges will + * be aggregated based on the date ranges. + * @param {number[]} request.orderBys + * Specifies how rows are ordered in the response. + * Requests including both comparisons and multiple date ranges will + * have order bys applied on the comparisons. + * @param {string} request.currencyCode + * A currency code in ISO4217 format, such as "AED", "USD", "JPY". + * If the field is empty, the report uses the property's default currency. + * @param {google.analytics.data.v1beta.CohortSpec} request.cohortSpec + * Cohort group associated with this request. If there is a cohort group + * in the request the 'cohort' dimension must be present. + * @param {boolean} request.keepEmptyRows + * If false or unspecified, each row with all metrics equal to 0 will not be + * returned. If true, these rows will be returned if they are not separately + * removed by a filter. + * + * Regardless of this `keep_empty_rows` setting, only data recorded by the + * Google Analytics property can be displayed in a report. + * + * For example if a property never logs a `purchase` event, then a query for + * the `eventName` dimension and `eventCount` metric will not have a row + * eventName: "purchase" and eventCount: 0. + * @param {boolean} request.returnPropertyQuota + * Toggles whether to return the current state of this Google Analytics + * property's quota. Quota is returned in [PropertyQuota](#PropertyQuota). + * @param {number[]} [request.comparisons] + * Optional. The configuration of comparisons requested and displayed. The + * request only requires a comparisons field in order to receive a comparison + * column 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.analytics.data.v1beta.RunReportResponse|RunReportResponse}. + * 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/v1beta/beta_analytics_data.run_report.js + * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_RunReport_async + */ runReport( - request?: protos.google.analytics.data.v1beta.IRunReportRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.data.v1beta.IRunReportResponse, - protos.google.analytics.data.v1beta.IRunReportRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.data.v1beta.IRunReportRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.data.v1beta.IRunReportResponse, + protos.google.analytics.data.v1beta.IRunReportRequest | undefined, + {} | undefined, + ] + >; runReport( - request: protos.google.analytics.data.v1beta.IRunReportRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.data.v1beta.IRunReportResponse, - protos.google.analytics.data.v1beta.IRunReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1beta.IRunReportRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.data.v1beta.IRunReportResponse, + protos.google.analytics.data.v1beta.IRunReportRequest | null | undefined, + {} | null | undefined + >, + ): void; runReport( - request: protos.google.analytics.data.v1beta.IRunReportRequest, - callback: Callback< - protos.google.analytics.data.v1beta.IRunReportResponse, - protos.google.analytics.data.v1beta.IRunReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1beta.IRunReportRequest, + callback: Callback< + protos.google.analytics.data.v1beta.IRunReportResponse, + protos.google.analytics.data.v1beta.IRunReportRequest | null | undefined, + {} | null | undefined + >, + ): void; runReport( - request?: protos.google.analytics.data.v1beta.IRunReportRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.data.v1beta.IRunReportResponse, - protos.google.analytics.data.v1beta.IRunReportRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.data.v1beta.IRunReportRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.data.v1beta.IRunReportResponse, - protos.google.analytics.data.v1beta.IRunReportRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.data.v1beta.IRunReportResponse, - protos.google.analytics.data.v1beta.IRunReportRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.data.v1beta.IRunReportRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.data.v1beta.IRunReportResponse, + protos.google.analytics.data.v1beta.IRunReportRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.data.v1beta.IRunReportResponse, + protos.google.analytics.data.v1beta.IRunReportRequest | 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({ - 'property': request.property ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + property: request.property ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('runReport request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.data.v1beta.IRunReportResponse, - protos.google.analytics.data.v1beta.IRunReportRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.data.v1beta.IRunReportResponse, + | protos.google.analytics.data.v1beta.IRunReportRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('runReport response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.runReport(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.data.v1beta.IRunReportResponse, - protos.google.analytics.data.v1beta.IRunReportRequest|undefined, - {}|undefined - ]) => { - this._log.info('runReport response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .runReport(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.data.v1beta.IRunReportResponse, + protos.google.analytics.data.v1beta.IRunReportRequest | undefined, + {} | undefined, + ]) => { + this._log.info('runReport response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns a customized pivot report of your Google Analytics event data. - * Pivot reports are more advanced and expressive formats than regular - * reports. In a pivot report, dimensions are only visible if they are - * included in a pivot. Multiple pivots can be specified to further dissect - * your data. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.property - * A Google Analytics property identifier whose events are tracked. - * Specified in the URL path and not the body. To learn more, see [where to - * find your Property - * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id). - * Within a batch request, this property should either be unspecified or - * consistent with the batch-level property. - * - * Example: properties/1234 - * @param {number[]} request.dimensions - * The dimensions requested. All defined dimensions must be used by one of the - * following: dimension_expression, dimension_filter, pivots, order_bys. - * @param {number[]} request.metrics - * The metrics requested, at least one metric needs to be specified. All - * defined metrics must be used by one of the following: metric_expression, - * metric_filter, order_bys. - * @param {number[]} request.dateRanges - * The date range to retrieve event data for the report. If multiple date - * ranges are specified, event data from each date range is used in the - * report. A special dimension with field name "dateRange" can be included in - * a Pivot's field names; if included, the report compares between date - * ranges. In a cohort request, this `dateRanges` must be unspecified. - * @param {number[]} request.pivots - * Describes the visual format of the report's dimensions in columns or rows. - * The union of the fieldNames (dimension names) in all pivots must be a - * subset of dimension names defined in Dimensions. No two pivots can share a - * dimension. A dimension is only visible if it appears in a pivot. - * @param {google.analytics.data.v1beta.FilterExpression} request.dimensionFilter - * The filter clause of dimensions. Dimensions must be requested to be used in - * this filter. Metrics cannot be used in this filter. - * @param {google.analytics.data.v1beta.FilterExpression} request.metricFilter - * The filter clause of metrics. Applied at post aggregation phase, similar to - * SQL having-clause. Metrics must be requested to be used in this filter. - * Dimensions cannot be used in this filter. - * @param {string} request.currencyCode - * A currency code in ISO4217 format, such as "AED", "USD", "JPY". - * If the field is empty, the report uses the property's default currency. - * @param {google.analytics.data.v1beta.CohortSpec} request.cohortSpec - * Cohort group associated with this request. If there is a cohort group - * in the request the 'cohort' dimension must be present. - * @param {boolean} request.keepEmptyRows - * If false or unspecified, each row with all metrics equal to 0 will not be - * returned. If true, these rows will be returned if they are not separately - * removed by a filter. - * - * Regardless of this `keep_empty_rows` setting, only data recorded by the - * Google Analytics property can be displayed in a report. - * - * For example if a property never logs a `purchase` event, then a query for - * the `eventName` dimension and `eventCount` metric will not have a row - * eventName: "purchase" and eventCount: 0. - * @param {boolean} request.returnPropertyQuota - * Toggles whether to return the current state of this Google Analytics - * property's quota. Quota is returned in [PropertyQuota](#PropertyQuota). - * @param {number[]} [request.comparisons] - * Optional. The configuration of comparisons requested and displayed. The - * request requires both a comparisons field and a comparisons dimension to - * receive a comparison column 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.analytics.data.v1beta.RunPivotReportResponse|RunPivotReportResponse}. - * 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/v1beta/beta_analytics_data.run_pivot_report.js - * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_RunPivotReport_async - */ + /** + * Returns a customized pivot report of your Google Analytics event data. + * Pivot reports are more advanced and expressive formats than regular + * reports. In a pivot report, dimensions are only visible if they are + * included in a pivot. Multiple pivots can be specified to further dissect + * your data. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.property + * A Google Analytics property identifier whose events are tracked. + * Specified in the URL path and not the body. To learn more, see [where to + * find your Property + * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id). + * Within a batch request, this property should either be unspecified or + * consistent with the batch-level property. + * + * Example: properties/1234 + * @param {number[]} request.dimensions + * The dimensions requested. All defined dimensions must be used by one of the + * following: dimension_expression, dimension_filter, pivots, order_bys. + * @param {number[]} request.metrics + * The metrics requested, at least one metric needs to be specified. All + * defined metrics must be used by one of the following: metric_expression, + * metric_filter, order_bys. + * @param {number[]} request.dateRanges + * The date range to retrieve event data for the report. If multiple date + * ranges are specified, event data from each date range is used in the + * report. A special dimension with field name "dateRange" can be included in + * a Pivot's field names; if included, the report compares between date + * ranges. In a cohort request, this `dateRanges` must be unspecified. + * @param {number[]} request.pivots + * Describes the visual format of the report's dimensions in columns or rows. + * The union of the fieldNames (dimension names) in all pivots must be a + * subset of dimension names defined in Dimensions. No two pivots can share a + * dimension. A dimension is only visible if it appears in a pivot. + * @param {google.analytics.data.v1beta.FilterExpression} request.dimensionFilter + * The filter clause of dimensions. Dimensions must be requested to be used in + * this filter. Metrics cannot be used in this filter. + * @param {google.analytics.data.v1beta.FilterExpression} request.metricFilter + * The filter clause of metrics. Applied at post aggregation phase, similar to + * SQL having-clause. Metrics must be requested to be used in this filter. + * Dimensions cannot be used in this filter. + * @param {string} request.currencyCode + * A currency code in ISO4217 format, such as "AED", "USD", "JPY". + * If the field is empty, the report uses the property's default currency. + * @param {google.analytics.data.v1beta.CohortSpec} request.cohortSpec + * Cohort group associated with this request. If there is a cohort group + * in the request the 'cohort' dimension must be present. + * @param {boolean} request.keepEmptyRows + * If false or unspecified, each row with all metrics equal to 0 will not be + * returned. If true, these rows will be returned if they are not separately + * removed by a filter. + * + * Regardless of this `keep_empty_rows` setting, only data recorded by the + * Google Analytics property can be displayed in a report. + * + * For example if a property never logs a `purchase` event, then a query for + * the `eventName` dimension and `eventCount` metric will not have a row + * eventName: "purchase" and eventCount: 0. + * @param {boolean} request.returnPropertyQuota + * Toggles whether to return the current state of this Google Analytics + * property's quota. Quota is returned in [PropertyQuota](#PropertyQuota). + * @param {number[]} [request.comparisons] + * Optional. The configuration of comparisons requested and displayed. The + * request requires both a comparisons field and a comparisons dimension to + * receive a comparison column 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.analytics.data.v1beta.RunPivotReportResponse|RunPivotReportResponse}. + * 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/v1beta/beta_analytics_data.run_pivot_report.js + * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_RunPivotReport_async + */ runPivotReport( - request?: protos.google.analytics.data.v1beta.IRunPivotReportRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.data.v1beta.IRunPivotReportResponse, - protos.google.analytics.data.v1beta.IRunPivotReportRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.data.v1beta.IRunPivotReportRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.data.v1beta.IRunPivotReportResponse, + protos.google.analytics.data.v1beta.IRunPivotReportRequest | undefined, + {} | undefined, + ] + >; runPivotReport( - request: protos.google.analytics.data.v1beta.IRunPivotReportRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.data.v1beta.IRunPivotReportResponse, - protos.google.analytics.data.v1beta.IRunPivotReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1beta.IRunPivotReportRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.data.v1beta.IRunPivotReportResponse, + | protos.google.analytics.data.v1beta.IRunPivotReportRequest + | null + | undefined, + {} | null | undefined + >, + ): void; runPivotReport( - request: protos.google.analytics.data.v1beta.IRunPivotReportRequest, - callback: Callback< - protos.google.analytics.data.v1beta.IRunPivotReportResponse, - protos.google.analytics.data.v1beta.IRunPivotReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1beta.IRunPivotReportRequest, + callback: Callback< + protos.google.analytics.data.v1beta.IRunPivotReportResponse, + | protos.google.analytics.data.v1beta.IRunPivotReportRequest + | null + | undefined, + {} | null | undefined + >, + ): void; runPivotReport( - request?: protos.google.analytics.data.v1beta.IRunPivotReportRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.data.v1beta.IRunPivotReportResponse, - protos.google.analytics.data.v1beta.IRunPivotReportRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.data.v1beta.IRunPivotReportRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.data.v1beta.IRunPivotReportResponse, - protos.google.analytics.data.v1beta.IRunPivotReportRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.data.v1beta.IRunPivotReportResponse, - protos.google.analytics.data.v1beta.IRunPivotReportRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.data.v1beta.IRunPivotReportRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.data.v1beta.IRunPivotReportResponse, + | protos.google.analytics.data.v1beta.IRunPivotReportRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.data.v1beta.IRunPivotReportResponse, + protos.google.analytics.data.v1beta.IRunPivotReportRequest | 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({ - 'property': request.property ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + property: request.property ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('runPivotReport request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.data.v1beta.IRunPivotReportResponse, - protos.google.analytics.data.v1beta.IRunPivotReportRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.data.v1beta.IRunPivotReportResponse, + | protos.google.analytics.data.v1beta.IRunPivotReportRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('runPivotReport response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.runPivotReport(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.data.v1beta.IRunPivotReportResponse, - protos.google.analytics.data.v1beta.IRunPivotReportRequest|undefined, - {}|undefined - ]) => { - this._log.info('runPivotReport response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .runPivotReport(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.data.v1beta.IRunPivotReportResponse, + ( + | protos.google.analytics.data.v1beta.IRunPivotReportRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('runPivotReport response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns multiple reports in a batch. All reports must be for the same - * Google Analytics property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.property - * A Google Analytics property identifier whose events are tracked. - * Specified in the URL path and not the body. To learn more, see [where to - * find your Property - * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id). - * This property must be specified for the batch. The property within - * RunReportRequest may either be unspecified or consistent with this - * property. - * - * Example: properties/1234 - * @param {number[]} request.requests - * Individual requests. Each request has a separate report response. Each - * batch request is allowed up to 5 requests. - * @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.analytics.data.v1beta.BatchRunReportsResponse|BatchRunReportsResponse}. - * 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/v1beta/beta_analytics_data.batch_run_reports.js - * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunReports_async - */ + /** + * Returns multiple reports in a batch. All reports must be for the same + * Google Analytics property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.property + * A Google Analytics property identifier whose events are tracked. + * Specified in the URL path and not the body. To learn more, see [where to + * find your Property + * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id). + * This property must be specified for the batch. The property within + * RunReportRequest may either be unspecified or consistent with this + * property. + * + * Example: properties/1234 + * @param {number[]} request.requests + * Individual requests. Each request has a separate report response. Each + * batch request is allowed up to 5 requests. + * @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.analytics.data.v1beta.BatchRunReportsResponse|BatchRunReportsResponse}. + * 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/v1beta/beta_analytics_data.batch_run_reports.js + * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunReports_async + */ batchRunReports( - request?: protos.google.analytics.data.v1beta.IBatchRunReportsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.data.v1beta.IBatchRunReportsResponse, - protos.google.analytics.data.v1beta.IBatchRunReportsRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.data.v1beta.IBatchRunReportsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.data.v1beta.IBatchRunReportsResponse, + protos.google.analytics.data.v1beta.IBatchRunReportsRequest | undefined, + {} | undefined, + ] + >; batchRunReports( - request: protos.google.analytics.data.v1beta.IBatchRunReportsRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.data.v1beta.IBatchRunReportsResponse, - protos.google.analytics.data.v1beta.IBatchRunReportsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1beta.IBatchRunReportsRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.data.v1beta.IBatchRunReportsResponse, + | protos.google.analytics.data.v1beta.IBatchRunReportsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchRunReports( - request: protos.google.analytics.data.v1beta.IBatchRunReportsRequest, - callback: Callback< - protos.google.analytics.data.v1beta.IBatchRunReportsResponse, - protos.google.analytics.data.v1beta.IBatchRunReportsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1beta.IBatchRunReportsRequest, + callback: Callback< + protos.google.analytics.data.v1beta.IBatchRunReportsResponse, + | protos.google.analytics.data.v1beta.IBatchRunReportsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchRunReports( - request?: protos.google.analytics.data.v1beta.IBatchRunReportsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.data.v1beta.IBatchRunReportsResponse, - protos.google.analytics.data.v1beta.IBatchRunReportsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.data.v1beta.IBatchRunReportsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.data.v1beta.IBatchRunReportsResponse, - protos.google.analytics.data.v1beta.IBatchRunReportsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.data.v1beta.IBatchRunReportsResponse, - protos.google.analytics.data.v1beta.IBatchRunReportsRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.data.v1beta.IBatchRunReportsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.data.v1beta.IBatchRunReportsResponse, + | protos.google.analytics.data.v1beta.IBatchRunReportsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.data.v1beta.IBatchRunReportsResponse, + protos.google.analytics.data.v1beta.IBatchRunReportsRequest | 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({ - 'property': request.property ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + property: request.property ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('batchRunReports request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.data.v1beta.IBatchRunReportsResponse, - protos.google.analytics.data.v1beta.IBatchRunReportsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.data.v1beta.IBatchRunReportsResponse, + | protos.google.analytics.data.v1beta.IBatchRunReportsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchRunReports response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.batchRunReports(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.data.v1beta.IBatchRunReportsResponse, - protos.google.analytics.data.v1beta.IBatchRunReportsRequest|undefined, - {}|undefined - ]) => { - this._log.info('batchRunReports response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchRunReports(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.data.v1beta.IBatchRunReportsResponse, + ( + | protos.google.analytics.data.v1beta.IBatchRunReportsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchRunReports response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns multiple pivot reports in a batch. All reports must be for the same - * Google Analytics property. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.property - * A Google Analytics property identifier whose events are tracked. - * Specified in the URL path and not the body. To learn more, see [where to - * find your Property - * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id). - * This property must be specified for the batch. The property within - * RunPivotReportRequest may either be unspecified or consistent with this - * property. - * - * Example: properties/1234 - * @param {number[]} request.requests - * Individual requests. Each request has a separate pivot report response. - * Each batch request is allowed up to 5 requests. - * @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.analytics.data.v1beta.BatchRunPivotReportsResponse|BatchRunPivotReportsResponse}. - * 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/v1beta/beta_analytics_data.batch_run_pivot_reports.js - * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunPivotReports_async - */ + /** + * Returns multiple pivot reports in a batch. All reports must be for the same + * Google Analytics property. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.property + * A Google Analytics property identifier whose events are tracked. + * Specified in the URL path and not the body. To learn more, see [where to + * find your Property + * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id). + * This property must be specified for the batch. The property within + * RunPivotReportRequest may either be unspecified or consistent with this + * property. + * + * Example: properties/1234 + * @param {number[]} request.requests + * Individual requests. Each request has a separate pivot report response. + * Each batch request is allowed up to 5 requests. + * @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.analytics.data.v1beta.BatchRunPivotReportsResponse|BatchRunPivotReportsResponse}. + * 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/v1beta/beta_analytics_data.batch_run_pivot_reports.js + * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunPivotReports_async + */ batchRunPivotReports( - request?: protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.data.v1beta.IBatchRunPivotReportsResponse, - protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.data.v1beta.IBatchRunPivotReportsResponse, + ( + | protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest + | undefined + ), + {} | undefined, + ] + >; batchRunPivotReports( - request: protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.data.v1beta.IBatchRunPivotReportsResponse, - protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.data.v1beta.IBatchRunPivotReportsResponse, + | protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchRunPivotReports( - request: protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest, - callback: Callback< - protos.google.analytics.data.v1beta.IBatchRunPivotReportsResponse, - protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest, + callback: Callback< + protos.google.analytics.data.v1beta.IBatchRunPivotReportsResponse, + | protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; batchRunPivotReports( - request?: protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.data.v1beta.IBatchRunPivotReportsResponse, - protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.data.v1beta.IBatchRunPivotReportsResponse, - protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.data.v1beta.IBatchRunPivotReportsResponse, - protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.data.v1beta.IBatchRunPivotReportsResponse, + | protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.data.v1beta.IBatchRunPivotReportsResponse, + ( + | protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest + | 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({ - 'property': request.property ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + property: request.property ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('batchRunPivotReports request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.data.v1beta.IBatchRunPivotReportsResponse, - protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.data.v1beta.IBatchRunPivotReportsResponse, + | protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchRunPivotReports response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.batchRunPivotReports(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.data.v1beta.IBatchRunPivotReportsResponse, - protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest|undefined, - {}|undefined - ]) => { - this._log.info('batchRunPivotReports response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .batchRunPivotReports(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.data.v1beta.IBatchRunPivotReportsResponse, + ( + | protos.google.analytics.data.v1beta.IBatchRunPivotReportsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('batchRunPivotReports response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns metadata for dimensions and metrics available in reporting methods. - * Used to explore the dimensions and metrics. In this method, a Google - * Analytics property identifier is specified in the request, and - * the metadata response includes Custom dimensions and metrics as well as - * Universal metadata. - * - * For example if a custom metric with parameter name `levels_unlocked` is - * registered to a property, the Metadata response will contain - * `customEvent:levels_unlocked`. Universal metadata are dimensions and - * metrics applicable to any property such as `country` and `totalUsers`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the metadata to retrieve. This name field is - * specified in the URL path and not URL parameters. Property is a numeric - * Google Analytics property identifier. To learn more, see [where to find - * your Property - * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id). - * - * Example: properties/1234/metadata - * - * Set the Property ID to 0 for dimensions and metrics common to all - * properties. In this special mode, this method will not return custom - * dimensions and metrics. - * @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.analytics.data.v1beta.Metadata|Metadata}. - * 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/v1beta/beta_analytics_data.get_metadata.js - * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_GetMetadata_async - */ + /** + * Returns metadata for dimensions and metrics available in reporting methods. + * Used to explore the dimensions and metrics. In this method, a Google + * Analytics property identifier is specified in the request, and + * the metadata response includes Custom dimensions and metrics as well as + * Universal metadata. + * + * For example if a custom metric with parameter name `levels_unlocked` is + * registered to a property, the Metadata response will contain + * `customEvent:levels_unlocked`. Universal metadata are dimensions and + * metrics applicable to any property such as `country` and `totalUsers`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the metadata to retrieve. This name field is + * specified in the URL path and not URL parameters. Property is a numeric + * Google Analytics property identifier. To learn more, see [where to find + * your Property + * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id). + * + * Example: properties/1234/metadata + * + * Set the Property ID to 0 for dimensions and metrics common to all + * properties. In this special mode, this method will not return custom + * dimensions and metrics. + * @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.analytics.data.v1beta.Metadata|Metadata}. + * 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/v1beta/beta_analytics_data.get_metadata.js + * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_GetMetadata_async + */ getMetadata( - request?: protos.google.analytics.data.v1beta.IGetMetadataRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.data.v1beta.IMetadata, - protos.google.analytics.data.v1beta.IGetMetadataRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.data.v1beta.IGetMetadataRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.data.v1beta.IMetadata, + protos.google.analytics.data.v1beta.IGetMetadataRequest | undefined, + {} | undefined, + ] + >; getMetadata( - request: protos.google.analytics.data.v1beta.IGetMetadataRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.data.v1beta.IMetadata, - protos.google.analytics.data.v1beta.IGetMetadataRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1beta.IGetMetadataRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.data.v1beta.IMetadata, + | protos.google.analytics.data.v1beta.IGetMetadataRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getMetadata( - request: protos.google.analytics.data.v1beta.IGetMetadataRequest, - callback: Callback< - protos.google.analytics.data.v1beta.IMetadata, - protos.google.analytics.data.v1beta.IGetMetadataRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1beta.IGetMetadataRequest, + callback: Callback< + protos.google.analytics.data.v1beta.IMetadata, + | protos.google.analytics.data.v1beta.IGetMetadataRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getMetadata( - request?: protos.google.analytics.data.v1beta.IGetMetadataRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.data.v1beta.IMetadata, - protos.google.analytics.data.v1beta.IGetMetadataRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.data.v1beta.IGetMetadataRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.data.v1beta.IMetadata, - protos.google.analytics.data.v1beta.IGetMetadataRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.data.v1beta.IMetadata, - protos.google.analytics.data.v1beta.IGetMetadataRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.data.v1beta.IGetMetadataRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.data.v1beta.IMetadata, + | protos.google.analytics.data.v1beta.IGetMetadataRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.data.v1beta.IMetadata, + protos.google.analytics.data.v1beta.IGetMetadataRequest | 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('getMetadata request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.data.v1beta.IMetadata, - protos.google.analytics.data.v1beta.IGetMetadataRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.data.v1beta.IMetadata, + | protos.google.analytics.data.v1beta.IGetMetadataRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getMetadata response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getMetadata(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.data.v1beta.IMetadata, - protos.google.analytics.data.v1beta.IGetMetadataRequest|undefined, - {}|undefined - ]) => { - this._log.info('getMetadata response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getMetadata(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.data.v1beta.IMetadata, + protos.google.analytics.data.v1beta.IGetMetadataRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getMetadata response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Returns a customized report of realtime event data for your property. - * Events appear in realtime reports seconds after they have been sent to - * the Google Analytics. Realtime reports show events and usage data for the - * periods of time ranging from the present moment to 30 minutes ago (up to - * 60 minutes for Google Analytics 360 properties). - * - * For a guide to constructing realtime requests & understanding responses, - * see [Creating a Realtime - * Report](https://developers.google.com/analytics/devguides/reporting/data/v1/realtime-basics). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.property - * A Google Analytics property identifier whose events are tracked. - * Specified in the URL path and not the body. To learn more, see [where to - * find your Property - * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id). - * - * Example: properties/1234 - * @param {number[]} request.dimensions - * The dimensions requested and displayed. - * @param {number[]} request.metrics - * The metrics requested and displayed. - * @param {google.analytics.data.v1beta.FilterExpression} request.dimensionFilter - * The filter clause of dimensions. Metrics cannot be used in this filter. - * @param {google.analytics.data.v1beta.FilterExpression} request.metricFilter - * The filter clause of metrics. Applied at post aggregation phase, similar to - * SQL having-clause. Dimensions cannot be used in this filter. - * @param {number} request.limit - * The number of rows to return. If unspecified, 10,000 rows are returned. The - * API returns a maximum of 250,000 rows per request, no matter how many you - * ask for. `limit` must be positive. - * - * The API can also return fewer rows than the requested `limit`, if there - * aren't as many dimension values as the `limit`. For instance, there are - * fewer than 300 possible values for the dimension `country`, so when - * reporting on only `country`, you can't get more than 300 rows, even if you - * set `limit` to a higher value. - * @param {number[]} request.metricAggregations - * Aggregation of metrics. Aggregated metric values will be shown in rows - * where the dimension_values are set to "RESERVED_(MetricAggregation)". - * @param {number[]} request.orderBys - * Specifies how rows are ordered in the response. - * @param {boolean} request.returnPropertyQuota - * Toggles whether to return the current state of this Google Analytics - * property's Realtime quota. Quota is returned in - * [PropertyQuota](#PropertyQuota). - * @param {number[]} request.minuteRanges - * The minute ranges of event data to read. If unspecified, one minute range - * for the last 30 minutes will be used. If multiple minute ranges are - * requested, each response row will contain a zero based minute range index. - * If two minute ranges overlap, the event data for the overlapping minutes is - * included in the response rows for both minute ranges. - * @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.analytics.data.v1beta.RunRealtimeReportResponse|RunRealtimeReportResponse}. - * 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/v1beta/beta_analytics_data.run_realtime_report.js - * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_RunRealtimeReport_async - */ + /** + * Returns a customized report of realtime event data for your property. + * Events appear in realtime reports seconds after they have been sent to + * the Google Analytics. Realtime reports show events and usage data for the + * periods of time ranging from the present moment to 30 minutes ago (up to + * 60 minutes for Google Analytics 360 properties). + * + * For a guide to constructing realtime requests & understanding responses, + * see [Creating a Realtime + * Report](https://developers.google.com/analytics/devguides/reporting/data/v1/realtime-basics). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.property + * A Google Analytics property identifier whose events are tracked. + * Specified in the URL path and not the body. To learn more, see [where to + * find your Property + * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id). + * + * Example: properties/1234 + * @param {number[]} request.dimensions + * The dimensions requested and displayed. + * @param {number[]} request.metrics + * The metrics requested and displayed. + * @param {google.analytics.data.v1beta.FilterExpression} request.dimensionFilter + * The filter clause of dimensions. Metrics cannot be used in this filter. + * @param {google.analytics.data.v1beta.FilterExpression} request.metricFilter + * The filter clause of metrics. Applied at post aggregation phase, similar to + * SQL having-clause. Dimensions cannot be used in this filter. + * @param {number} request.limit + * The number of rows to return. If unspecified, 10,000 rows are returned. The + * API returns a maximum of 250,000 rows per request, no matter how many you + * ask for. `limit` must be positive. + * + * The API can also return fewer rows than the requested `limit`, if there + * aren't as many dimension values as the `limit`. For instance, there are + * fewer than 300 possible values for the dimension `country`, so when + * reporting on only `country`, you can't get more than 300 rows, even if you + * set `limit` to a higher value. + * @param {number[]} request.metricAggregations + * Aggregation of metrics. Aggregated metric values will be shown in rows + * where the dimension_values are set to "RESERVED_(MetricAggregation)". + * @param {number[]} request.orderBys + * Specifies how rows are ordered in the response. + * @param {boolean} request.returnPropertyQuota + * Toggles whether to return the current state of this Google Analytics + * property's Realtime quota. Quota is returned in + * [PropertyQuota](#PropertyQuota). + * @param {number[]} request.minuteRanges + * The minute ranges of event data to read. If unspecified, one minute range + * for the last 30 minutes will be used. If multiple minute ranges are + * requested, each response row will contain a zero based minute range index. + * If two minute ranges overlap, the event data for the overlapping minutes is + * included in the response rows for both minute ranges. + * @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.analytics.data.v1beta.RunRealtimeReportResponse|RunRealtimeReportResponse}. + * 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/v1beta/beta_analytics_data.run_realtime_report.js + * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_RunRealtimeReport_async + */ runRealtimeReport( - request?: protos.google.analytics.data.v1beta.IRunRealtimeReportRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.data.v1beta.IRunRealtimeReportResponse, - protos.google.analytics.data.v1beta.IRunRealtimeReportRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.data.v1beta.IRunRealtimeReportRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.data.v1beta.IRunRealtimeReportResponse, + protos.google.analytics.data.v1beta.IRunRealtimeReportRequest | undefined, + {} | undefined, + ] + >; runRealtimeReport( - request: protos.google.analytics.data.v1beta.IRunRealtimeReportRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.data.v1beta.IRunRealtimeReportResponse, - protos.google.analytics.data.v1beta.IRunRealtimeReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1beta.IRunRealtimeReportRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.data.v1beta.IRunRealtimeReportResponse, + | protos.google.analytics.data.v1beta.IRunRealtimeReportRequest + | null + | undefined, + {} | null | undefined + >, + ): void; runRealtimeReport( - request: protos.google.analytics.data.v1beta.IRunRealtimeReportRequest, - callback: Callback< - protos.google.analytics.data.v1beta.IRunRealtimeReportResponse, - protos.google.analytics.data.v1beta.IRunRealtimeReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1beta.IRunRealtimeReportRequest, + callback: Callback< + protos.google.analytics.data.v1beta.IRunRealtimeReportResponse, + | protos.google.analytics.data.v1beta.IRunRealtimeReportRequest + | null + | undefined, + {} | null | undefined + >, + ): void; runRealtimeReport( - request?: protos.google.analytics.data.v1beta.IRunRealtimeReportRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.data.v1beta.IRunRealtimeReportResponse, - protos.google.analytics.data.v1beta.IRunRealtimeReportRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.data.v1beta.IRunRealtimeReportRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.data.v1beta.IRunRealtimeReportResponse, - protos.google.analytics.data.v1beta.IRunRealtimeReportRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.data.v1beta.IRunRealtimeReportResponse, - protos.google.analytics.data.v1beta.IRunRealtimeReportRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.data.v1beta.IRunRealtimeReportRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.data.v1beta.IRunRealtimeReportResponse, + | protos.google.analytics.data.v1beta.IRunRealtimeReportRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.data.v1beta.IRunRealtimeReportResponse, + protos.google.analytics.data.v1beta.IRunRealtimeReportRequest | 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({ - 'property': request.property ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + property: request.property ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('runRealtimeReport request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.data.v1beta.IRunRealtimeReportResponse, - protos.google.analytics.data.v1beta.IRunRealtimeReportRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.data.v1beta.IRunRealtimeReportResponse, + | protos.google.analytics.data.v1beta.IRunRealtimeReportRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('runRealtimeReport response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.runRealtimeReport(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.data.v1beta.IRunRealtimeReportResponse, - protos.google.analytics.data.v1beta.IRunRealtimeReportRequest|undefined, - {}|undefined - ]) => { - this._log.info('runRealtimeReport response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .runRealtimeReport(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.data.v1beta.IRunRealtimeReportResponse, + ( + | protos.google.analytics.data.v1beta.IRunRealtimeReportRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('runRealtimeReport response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This compatibility method lists dimensions and metrics that can be added to - * a report request and maintain compatibility. This method fails if the - * request's dimensions and metrics are incompatible. - * - * In Google Analytics, reports fail if they request incompatible dimensions - * and/or metrics; in that case, you will need to remove dimensions and/or - * metrics from the incompatible report until the report is compatible. - * - * The Realtime and Core reports have different compatibility rules. This - * method checks compatibility for Core reports. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.property - * A Google Analytics property identifier whose events are tracked. To - * learn more, see [where to find your Property - * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id). - * `property` should be the same value as in your `runReport` request. - * - * Example: properties/1234 - * @param {number[]} request.dimensions - * The dimensions in this report. `dimensions` should be the same value as in - * your `runReport` request. - * @param {number[]} request.metrics - * The metrics in this report. `metrics` should be the same value as in your - * `runReport` request. - * @param {google.analytics.data.v1beta.FilterExpression} request.dimensionFilter - * The filter clause of dimensions. `dimensionFilter` should be the same value - * as in your `runReport` request. - * @param {google.analytics.data.v1beta.FilterExpression} request.metricFilter - * The filter clause of metrics. `metricFilter` should be the same value as in - * your `runReport` request - * @param {google.analytics.data.v1beta.Compatibility} request.compatibilityFilter - * Filters the dimensions and metrics in the response to just this - * compatibility. Commonly used as `”compatibilityFilter”: “COMPATIBLE”` - * to only return compatible dimensions & metrics. - * @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.analytics.data.v1beta.CheckCompatibilityResponse|CheckCompatibilityResponse}. - * 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/v1beta/beta_analytics_data.check_compatibility.js - * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_CheckCompatibility_async - */ + /** + * This compatibility method lists dimensions and metrics that can be added to + * a report request and maintain compatibility. This method fails if the + * request's dimensions and metrics are incompatible. + * + * In Google Analytics, reports fail if they request incompatible dimensions + * and/or metrics; in that case, you will need to remove dimensions and/or + * metrics from the incompatible report until the report is compatible. + * + * The Realtime and Core reports have different compatibility rules. This + * method checks compatibility for Core reports. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.property + * A Google Analytics property identifier whose events are tracked. To + * learn more, see [where to find your Property + * ID](https://developers.google.com/analytics/devguides/reporting/data/v1/property-id). + * `property` should be the same value as in your `runReport` request. + * + * Example: properties/1234 + * @param {number[]} request.dimensions + * The dimensions in this report. `dimensions` should be the same value as in + * your `runReport` request. + * @param {number[]} request.metrics + * The metrics in this report. `metrics` should be the same value as in your + * `runReport` request. + * @param {google.analytics.data.v1beta.FilterExpression} request.dimensionFilter + * The filter clause of dimensions. `dimensionFilter` should be the same value + * as in your `runReport` request. + * @param {google.analytics.data.v1beta.FilterExpression} request.metricFilter + * The filter clause of metrics. `metricFilter` should be the same value as in + * your `runReport` request + * @param {google.analytics.data.v1beta.Compatibility} request.compatibilityFilter + * Filters the dimensions and metrics in the response to just this + * compatibility. Commonly used as `”compatibilityFilter”: “COMPATIBLE”` + * to only return compatible dimensions & metrics. + * @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.analytics.data.v1beta.CheckCompatibilityResponse|CheckCompatibilityResponse}. + * 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/v1beta/beta_analytics_data.check_compatibility.js + * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_CheckCompatibility_async + */ checkCompatibility( - request?: protos.google.analytics.data.v1beta.ICheckCompatibilityRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.data.v1beta.ICheckCompatibilityResponse, - protos.google.analytics.data.v1beta.ICheckCompatibilityRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.data.v1beta.ICheckCompatibilityRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.data.v1beta.ICheckCompatibilityResponse, + ( + | protos.google.analytics.data.v1beta.ICheckCompatibilityRequest + | undefined + ), + {} | undefined, + ] + >; checkCompatibility( - request: protos.google.analytics.data.v1beta.ICheckCompatibilityRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.data.v1beta.ICheckCompatibilityResponse, - protos.google.analytics.data.v1beta.ICheckCompatibilityRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1beta.ICheckCompatibilityRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.data.v1beta.ICheckCompatibilityResponse, + | protos.google.analytics.data.v1beta.ICheckCompatibilityRequest + | null + | undefined, + {} | null | undefined + >, + ): void; checkCompatibility( - request: protos.google.analytics.data.v1beta.ICheckCompatibilityRequest, - callback: Callback< - protos.google.analytics.data.v1beta.ICheckCompatibilityResponse, - protos.google.analytics.data.v1beta.ICheckCompatibilityRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1beta.ICheckCompatibilityRequest, + callback: Callback< + protos.google.analytics.data.v1beta.ICheckCompatibilityResponse, + | protos.google.analytics.data.v1beta.ICheckCompatibilityRequest + | null + | undefined, + {} | null | undefined + >, + ): void; checkCompatibility( - request?: protos.google.analytics.data.v1beta.ICheckCompatibilityRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.data.v1beta.ICheckCompatibilityResponse, - protos.google.analytics.data.v1beta.ICheckCompatibilityRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.data.v1beta.ICheckCompatibilityRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.data.v1beta.ICheckCompatibilityResponse, - protos.google.analytics.data.v1beta.ICheckCompatibilityRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.data.v1beta.ICheckCompatibilityResponse, - protos.google.analytics.data.v1beta.ICheckCompatibilityRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.data.v1beta.ICheckCompatibilityRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.data.v1beta.ICheckCompatibilityResponse, + | protos.google.analytics.data.v1beta.ICheckCompatibilityRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.data.v1beta.ICheckCompatibilityResponse, + ( + | protos.google.analytics.data.v1beta.ICheckCompatibilityRequest + | 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({ - 'property': request.property ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + property: request.property ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('checkCompatibility request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.data.v1beta.ICheckCompatibilityResponse, - protos.google.analytics.data.v1beta.ICheckCompatibilityRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.data.v1beta.ICheckCompatibilityResponse, + | protos.google.analytics.data.v1beta.ICheckCompatibilityRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('checkCompatibility response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.checkCompatibility(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.data.v1beta.ICheckCompatibilityResponse, - protos.google.analytics.data.v1beta.ICheckCompatibilityRequest|undefined, - {}|undefined - ]) => { - this._log.info('checkCompatibility response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .checkCompatibility(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.data.v1beta.ICheckCompatibilityResponse, + ( + | protos.google.analytics.data.v1beta.ICheckCompatibilityRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('checkCompatibility response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Retrieves an audience export of users. After creating an audience, the - * users are not immediately available for exporting. First, a request to - * `CreateAudienceExport` is necessary to create an audience export of users, - * and then second, this method is used to retrieve the users in the audience - * export. - * - * See [Creating an Audience - * Export](https://developers.google.com/analytics/devguides/reporting/data/v1/audience-list-basics) - * for an introduction to Audience Exports with examples. - * - * Audiences in Google Analytics 4 allow you to segment your users in the ways - * that are important to your business. To learn more, see - * https://support.google.com/analytics/answer/9267572. - * - * Audience Export APIs have some methods at alpha and other methods at beta - * stability. The intention is to advance methods to beta stability after some - * feedback and adoption. To give your feedback on this API, complete the - * [Google Analytics Audience Export API - * Feedback](https://forms.gle/EeA5u5LW6PEggtCEA) form. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the audience export to retrieve users from. - * Format: `properties/{property}/audienceExports/{audience_export}` - * @param {number} [request.offset] - * Optional. The row count of the start row. The first row is counted as row - * 0. - * - * When paging, the first request does not specify offset; or equivalently, - * sets offset to 0; the first request returns the first `limit` of rows. The - * second request sets offset to the `limit` of the first request; the second - * request returns the second `limit` of rows. - * - * To learn more about this pagination parameter, see - * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). - * @param {number} [request.limit] - * Optional. The number of rows to return. If unspecified, 10,000 rows are - * returned. The API returns a maximum of 250,000 rows per request, no matter - * how many you ask for. `limit` must be positive. - * - * The API can also return fewer rows than the requested `limit`, if there - * aren't as many dimension values as the `limit`. - * - * To learn more about this pagination parameter, see - * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). - * @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.analytics.data.v1beta.QueryAudienceExportResponse|QueryAudienceExportResponse}. - * 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/v1beta/beta_analytics_data.query_audience_export.js - * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_QueryAudienceExport_async - */ + /** + * Retrieves an audience export of users. After creating an audience, the + * users are not immediately available for exporting. First, a request to + * `CreateAudienceExport` is necessary to create an audience export of users, + * and then second, this method is used to retrieve the users in the audience + * export. + * + * See [Creating an Audience + * Export](https://developers.google.com/analytics/devguides/reporting/data/v1/audience-list-basics) + * for an introduction to Audience Exports with examples. + * + * Audiences in Google Analytics 4 allow you to segment your users in the ways + * that are important to your business. To learn more, see + * https://support.google.com/analytics/answer/9267572. + * + * Audience Export APIs have some methods at alpha and other methods at beta + * stability. The intention is to advance methods to beta stability after some + * feedback and adoption. To give your feedback on this API, complete the + * [Google Analytics Audience Export API + * Feedback](https://forms.gle/EeA5u5LW6PEggtCEA) form. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the audience export to retrieve users from. + * Format: `properties/{property}/audienceExports/{audience_export}` + * @param {number} [request.offset] + * Optional. The row count of the start row. The first row is counted as row + * 0. + * + * When paging, the first request does not specify offset; or equivalently, + * sets offset to 0; the first request returns the first `limit` of rows. The + * second request sets offset to the `limit` of the first request; the second + * request returns the second `limit` of rows. + * + * To learn more about this pagination parameter, see + * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). + * @param {number} [request.limit] + * Optional. The number of rows to return. If unspecified, 10,000 rows are + * returned. The API returns a maximum of 250,000 rows per request, no matter + * how many you ask for. `limit` must be positive. + * + * The API can also return fewer rows than the requested `limit`, if there + * aren't as many dimension values as the `limit`. + * + * To learn more about this pagination parameter, see + * [Pagination](https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination). + * @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.analytics.data.v1beta.QueryAudienceExportResponse|QueryAudienceExportResponse}. + * 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/v1beta/beta_analytics_data.query_audience_export.js + * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_QueryAudienceExport_async + */ queryAudienceExport( - request?: protos.google.analytics.data.v1beta.IQueryAudienceExportRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.data.v1beta.IQueryAudienceExportResponse, - protos.google.analytics.data.v1beta.IQueryAudienceExportRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.data.v1beta.IQueryAudienceExportRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.data.v1beta.IQueryAudienceExportResponse, + ( + | protos.google.analytics.data.v1beta.IQueryAudienceExportRequest + | undefined + ), + {} | undefined, + ] + >; queryAudienceExport( - request: protos.google.analytics.data.v1beta.IQueryAudienceExportRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.data.v1beta.IQueryAudienceExportResponse, - protos.google.analytics.data.v1beta.IQueryAudienceExportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1beta.IQueryAudienceExportRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.data.v1beta.IQueryAudienceExportResponse, + | protos.google.analytics.data.v1beta.IQueryAudienceExportRequest + | null + | undefined, + {} | null | undefined + >, + ): void; queryAudienceExport( - request: protos.google.analytics.data.v1beta.IQueryAudienceExportRequest, - callback: Callback< - protos.google.analytics.data.v1beta.IQueryAudienceExportResponse, - protos.google.analytics.data.v1beta.IQueryAudienceExportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1beta.IQueryAudienceExportRequest, + callback: Callback< + protos.google.analytics.data.v1beta.IQueryAudienceExportResponse, + | protos.google.analytics.data.v1beta.IQueryAudienceExportRequest + | null + | undefined, + {} | null | undefined + >, + ): void; queryAudienceExport( - request?: protos.google.analytics.data.v1beta.IQueryAudienceExportRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.data.v1beta.IQueryAudienceExportResponse, - protos.google.analytics.data.v1beta.IQueryAudienceExportRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.data.v1beta.IQueryAudienceExportRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.data.v1beta.IQueryAudienceExportResponse, - protos.google.analytics.data.v1beta.IQueryAudienceExportRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.data.v1beta.IQueryAudienceExportResponse, - protos.google.analytics.data.v1beta.IQueryAudienceExportRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.data.v1beta.IQueryAudienceExportRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.data.v1beta.IQueryAudienceExportResponse, + | protos.google.analytics.data.v1beta.IQueryAudienceExportRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.data.v1beta.IQueryAudienceExportResponse, + ( + | protos.google.analytics.data.v1beta.IQueryAudienceExportRequest + | 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('queryAudienceExport request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.data.v1beta.IQueryAudienceExportResponse, - protos.google.analytics.data.v1beta.IQueryAudienceExportRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.data.v1beta.IQueryAudienceExportResponse, + | protos.google.analytics.data.v1beta.IQueryAudienceExportRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('queryAudienceExport response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.queryAudienceExport(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.data.v1beta.IQueryAudienceExportResponse, - protos.google.analytics.data.v1beta.IQueryAudienceExportRequest|undefined, - {}|undefined - ]) => { - this._log.info('queryAudienceExport response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .queryAudienceExport(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.data.v1beta.IQueryAudienceExportResponse, + ( + | protos.google.analytics.data.v1beta.IQueryAudienceExportRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('queryAudienceExport response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets configuration metadata about a specific audience export. This method - * can be used to understand an audience export after it has been created. - * - * See [Creating an Audience - * Export](https://developers.google.com/analytics/devguides/reporting/data/v1/audience-list-basics) - * for an introduction to Audience Exports with examples. - * - * Audience Export APIs have some methods at alpha and other methods at beta - * stability. The intention is to advance methods to beta stability after some - * feedback and adoption. To give your feedback on this API, complete the - * [Google Analytics Audience Export API - * Feedback](https://forms.gle/EeA5u5LW6PEggtCEA) form. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The audience export resource name. - * Format: `properties/{property}/audienceExports/{audience_export}` - * @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.analytics.data.v1beta.AudienceExport|AudienceExport}. - * 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/v1beta/beta_analytics_data.get_audience_export.js - * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_GetAudienceExport_async - */ + /** + * Gets configuration metadata about a specific audience export. This method + * can be used to understand an audience export after it has been created. + * + * See [Creating an Audience + * Export](https://developers.google.com/analytics/devguides/reporting/data/v1/audience-list-basics) + * for an introduction to Audience Exports with examples. + * + * Audience Export APIs have some methods at alpha and other methods at beta + * stability. The intention is to advance methods to beta stability after some + * feedback and adoption. To give your feedback on this API, complete the + * [Google Analytics Audience Export API + * Feedback](https://forms.gle/EeA5u5LW6PEggtCEA) form. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The audience export resource name. + * Format: `properties/{property}/audienceExports/{audience_export}` + * @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.analytics.data.v1beta.AudienceExport|AudienceExport}. + * 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/v1beta/beta_analytics_data.get_audience_export.js + * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_GetAudienceExport_async + */ getAudienceExport( - request?: protos.google.analytics.data.v1beta.IGetAudienceExportRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.data.v1beta.IAudienceExport, - protos.google.analytics.data.v1beta.IGetAudienceExportRequest|undefined, {}|undefined - ]>; + request?: protos.google.analytics.data.v1beta.IGetAudienceExportRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.data.v1beta.IAudienceExport, + protos.google.analytics.data.v1beta.IGetAudienceExportRequest | undefined, + {} | undefined, + ] + >; getAudienceExport( - request: protos.google.analytics.data.v1beta.IGetAudienceExportRequest, - options: CallOptions, - callback: Callback< - protos.google.analytics.data.v1beta.IAudienceExport, - protos.google.analytics.data.v1beta.IGetAudienceExportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1beta.IGetAudienceExportRequest, + options: CallOptions, + callback: Callback< + protos.google.analytics.data.v1beta.IAudienceExport, + | protos.google.analytics.data.v1beta.IGetAudienceExportRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAudienceExport( - request: protos.google.analytics.data.v1beta.IGetAudienceExportRequest, - callback: Callback< - protos.google.analytics.data.v1beta.IAudienceExport, - protos.google.analytics.data.v1beta.IGetAudienceExportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1beta.IGetAudienceExportRequest, + callback: Callback< + protos.google.analytics.data.v1beta.IAudienceExport, + | protos.google.analytics.data.v1beta.IGetAudienceExportRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getAudienceExport( - request?: protos.google.analytics.data.v1beta.IGetAudienceExportRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.analytics.data.v1beta.IAudienceExport, - protos.google.analytics.data.v1beta.IGetAudienceExportRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.analytics.data.v1beta.IGetAudienceExportRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.analytics.data.v1beta.IAudienceExport, - protos.google.analytics.data.v1beta.IGetAudienceExportRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.analytics.data.v1beta.IAudienceExport, - protos.google.analytics.data.v1beta.IGetAudienceExportRequest|undefined, {}|undefined - ]>|void { + | protos.google.analytics.data.v1beta.IGetAudienceExportRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.analytics.data.v1beta.IAudienceExport, + | protos.google.analytics.data.v1beta.IGetAudienceExportRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.analytics.data.v1beta.IAudienceExport, + protos.google.analytics.data.v1beta.IGetAudienceExportRequest | 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('getAudienceExport request %j', request); - const wrappedCallback: Callback< - protos.google.analytics.data.v1beta.IAudienceExport, - protos.google.analytics.data.v1beta.IGetAudienceExportRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.analytics.data.v1beta.IAudienceExport, + | protos.google.analytics.data.v1beta.IGetAudienceExportRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getAudienceExport response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getAudienceExport(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.analytics.data.v1beta.IAudienceExport, - protos.google.analytics.data.v1beta.IGetAudienceExportRequest|undefined, - {}|undefined - ]) => { - this._log.info('getAudienceExport response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getAudienceExport(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.analytics.data.v1beta.IAudienceExport, + ( + | protos.google.analytics.data.v1beta.IGetAudienceExportRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getAudienceExport response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates an audience export for later retrieval. This method quickly returns - * the audience export's resource name and initiates a long running - * asynchronous request to form an audience export. To export the users in an - * audience export, first create the audience export through this method and - * then send the audience resource name to the `QueryAudienceExport` method. - * - * See [Creating an Audience - * Export](https://developers.google.com/analytics/devguides/reporting/data/v1/audience-list-basics) - * for an introduction to Audience Exports with examples. - * - * An audience export is a snapshot of the users currently in the audience at - * the time of audience export creation. Creating audience exports for one - * audience on different days will return different results as users enter and - * exit the audience. - * - * Audiences in Google Analytics 4 allow you to segment your users in the ways - * that are important to your business. To learn more, see - * https://support.google.com/analytics/answer/9267572. Audience exports - * contain the users in each audience. - * - * Audience Export APIs have some methods at alpha and other methods at beta - * stability. The intention is to advance methods to beta stability after some - * feedback and adoption. To give your feedback on this API, complete the - * [Google Analytics Audience Export API - * Feedback](https://forms.gle/EeA5u5LW6PEggtCEA) form. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource where this audience export will be created. - * Format: `properties/{property}` - * @param {google.analytics.data.v1beta.AudienceExport} request.audienceExport - * Required. The audience export 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 include:samples/generated/v1beta/beta_analytics_data.create_audience_export.js - * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_CreateAudienceExport_async - */ + /** + * Creates an audience export for later retrieval. This method quickly returns + * the audience export's resource name and initiates a long running + * asynchronous request to form an audience export. To export the users in an + * audience export, first create the audience export through this method and + * then send the audience resource name to the `QueryAudienceExport` method. + * + * See [Creating an Audience + * Export](https://developers.google.com/analytics/devguides/reporting/data/v1/audience-list-basics) + * for an introduction to Audience Exports with examples. + * + * An audience export is a snapshot of the users currently in the audience at + * the time of audience export creation. Creating audience exports for one + * audience on different days will return different results as users enter and + * exit the audience. + * + * Audiences in Google Analytics 4 allow you to segment your users in the ways + * that are important to your business. To learn more, see + * https://support.google.com/analytics/answer/9267572. Audience exports + * contain the users in each audience. + * + * Audience Export APIs have some methods at alpha and other methods at beta + * stability. The intention is to advance methods to beta stability after some + * feedback and adoption. To give your feedback on this API, complete the + * [Google Analytics Audience Export API + * Feedback](https://forms.gle/EeA5u5LW6PEggtCEA) form. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource where this audience export will be created. + * Format: `properties/{property}` + * @param {google.analytics.data.v1beta.AudienceExport} request.audienceExport + * Required. The audience export 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 include:samples/generated/v1beta/beta_analytics_data.create_audience_export.js + * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_CreateAudienceExport_async + */ createAudienceExport( - request?: protos.google.analytics.data.v1beta.ICreateAudienceExportRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.analytics.data.v1beta.ICreateAudienceExportRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.analytics.data.v1beta.IAudienceExport, + protos.google.analytics.data.v1beta.IAudienceExportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; createAudienceExport( - request: protos.google.analytics.data.v1beta.ICreateAudienceExportRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1beta.ICreateAudienceExportRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.analytics.data.v1beta.IAudienceExport, + protos.google.analytics.data.v1beta.IAudienceExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createAudienceExport( - request: protos.google.analytics.data.v1beta.ICreateAudienceExportRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.analytics.data.v1beta.ICreateAudienceExportRequest, + callback: Callback< + LROperation< + protos.google.analytics.data.v1beta.IAudienceExport, + protos.google.analytics.data.v1beta.IAudienceExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createAudienceExport( - request?: protos.google.analytics.data.v1beta.ICreateAudienceExportRequest, - 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.analytics.data.v1beta.ICreateAudienceExportRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.analytics.data.v1beta.IAudienceExport, + protos.google.analytics.data.v1beta.IAudienceExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.analytics.data.v1beta.IAudienceExport, + protos.google.analytics.data.v1beta.IAudienceExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.analytics.data.v1beta.IAudienceExport, + protos.google.analytics.data.v1beta.IAudienceExportMetadata + >, + 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.analytics.data.v1beta.IAudienceExport, + protos.google.analytics.data.v1beta.IAudienceExportMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('createAudienceExport response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('createAudienceExport request %j', request); - return this.innerApiCalls.createAudienceExport(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('createAudienceExport response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .createAudienceExport(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.analytics.data.v1beta.IAudienceExport, + protos.google.analytics.data.v1beta.IAudienceExportMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createAudienceExport response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `createAudienceExport()`. - * @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/v1beta/beta_analytics_data.create_audience_export.js - * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_CreateAudienceExport_async - */ - async checkCreateAudienceExportProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `createAudienceExport()`. + * @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/v1beta/beta_analytics_data.create_audience_export.js + * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_CreateAudienceExport_async + */ + async checkCreateAudienceExportProgress( + name: string, + ): Promise< + LROperation< + protos.google.analytics.data.v1beta.AudienceExport, + protos.google.analytics.data.v1beta.AudienceExportMetadata + > + > { this._log.info('createAudienceExport 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.createAudienceExport, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createAudienceExport, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.analytics.data.v1beta.AudienceExport, + protos.google.analytics.data.v1beta.AudienceExportMetadata + >; } - /** - * Lists all audience exports for a property. This method can be used for you - * to find and reuse existing audience exports rather than creating - * unnecessary new audience exports. The same audience can have multiple - * audience exports that represent the export of users that were in an - * audience on different days. - * - * See [Creating an Audience - * Export](https://developers.google.com/analytics/devguides/reporting/data/v1/audience-list-basics) - * for an introduction to Audience Exports with examples. - * - * Audience Export APIs have some methods at alpha and other methods at beta - * stability. The intention is to advance methods to beta stability after some - * feedback and adoption. To give your feedback on this API, complete the - * [Google Analytics Audience Export API - * Feedback](https://forms.gle/EeA5u5LW6PEggtCEA) form. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. All audience exports for this property will be listed in the - * response. Format: `properties/{property}` - * @param {number} [request.pageSize] - * Optional. The maximum number of audience exports to return. The service may - * return fewer than this value. If unspecified, at most 200 audience exports - * will be returned. The maximum value is 1000 (higher values will be coerced - * to the maximum). - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListAudienceExports` - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListAudienceExports` - * must match the call that provided the page token. - * @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.analytics.data.v1beta.AudienceExport|AudienceExport}. - * 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 `listAudienceExportsAsync()` - * 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 audience exports for a property. This method can be used for you + * to find and reuse existing audience exports rather than creating + * unnecessary new audience exports. The same audience can have multiple + * audience exports that represent the export of users that were in an + * audience on different days. + * + * See [Creating an Audience + * Export](https://developers.google.com/analytics/devguides/reporting/data/v1/audience-list-basics) + * for an introduction to Audience Exports with examples. + * + * Audience Export APIs have some methods at alpha and other methods at beta + * stability. The intention is to advance methods to beta stability after some + * feedback and adoption. To give your feedback on this API, complete the + * [Google Analytics Audience Export API + * Feedback](https://forms.gle/EeA5u5LW6PEggtCEA) form. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. All audience exports for this property will be listed in the + * response. Format: `properties/{property}` + * @param {number} [request.pageSize] + * Optional. The maximum number of audience exports to return. The service may + * return fewer than this value. If unspecified, at most 200 audience exports + * will be returned. The maximum value is 1000 (higher values will be coerced + * to the maximum). + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListAudienceExports` + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListAudienceExports` + * must match the call that provided the page token. + * @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.analytics.data.v1beta.AudienceExport|AudienceExport}. + * 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 `listAudienceExportsAsync()` + * 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. + */ listAudienceExports( - request?: protos.google.analytics.data.v1beta.IListAudienceExportsRequest, - options?: CallOptions): - Promise<[ - protos.google.analytics.data.v1beta.IAudienceExport[], - protos.google.analytics.data.v1beta.IListAudienceExportsRequest|null, - protos.google.analytics.data.v1beta.IListAudienceExportsResponse - ]>; + request?: protos.google.analytics.data.v1beta.IListAudienceExportsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.analytics.data.v1beta.IAudienceExport[], + protos.google.analytics.data.v1beta.IListAudienceExportsRequest | null, + protos.google.analytics.data.v1beta.IListAudienceExportsResponse, + ] + >; listAudienceExports( - request: protos.google.analytics.data.v1beta.IListAudienceExportsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.analytics.data.v1beta.IListAudienceExportsRequest, - protos.google.analytics.data.v1beta.IListAudienceExportsResponse|null|undefined, - protos.google.analytics.data.v1beta.IAudienceExport>): void; + request: protos.google.analytics.data.v1beta.IListAudienceExportsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.analytics.data.v1beta.IListAudienceExportsRequest, + | protos.google.analytics.data.v1beta.IListAudienceExportsResponse + | null + | undefined, + protos.google.analytics.data.v1beta.IAudienceExport + >, + ): void; listAudienceExports( - request: protos.google.analytics.data.v1beta.IListAudienceExportsRequest, - callback: PaginationCallback< - protos.google.analytics.data.v1beta.IListAudienceExportsRequest, - protos.google.analytics.data.v1beta.IListAudienceExportsResponse|null|undefined, - protos.google.analytics.data.v1beta.IAudienceExport>): void; + request: protos.google.analytics.data.v1beta.IListAudienceExportsRequest, + callback: PaginationCallback< + protos.google.analytics.data.v1beta.IListAudienceExportsRequest, + | protos.google.analytics.data.v1beta.IListAudienceExportsResponse + | null + | undefined, + protos.google.analytics.data.v1beta.IAudienceExport + >, + ): void; listAudienceExports( - request?: protos.google.analytics.data.v1beta.IListAudienceExportsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.analytics.data.v1beta.IListAudienceExportsRequest, - protos.google.analytics.data.v1beta.IListAudienceExportsResponse|null|undefined, - protos.google.analytics.data.v1beta.IAudienceExport>, - callback?: PaginationCallback< + request?: protos.google.analytics.data.v1beta.IListAudienceExportsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.analytics.data.v1beta.IListAudienceExportsRequest, - protos.google.analytics.data.v1beta.IListAudienceExportsResponse|null|undefined, - protos.google.analytics.data.v1beta.IAudienceExport>): - Promise<[ - protos.google.analytics.data.v1beta.IAudienceExport[], - protos.google.analytics.data.v1beta.IListAudienceExportsRequest|null, - protos.google.analytics.data.v1beta.IListAudienceExportsResponse - ]>|void { + | protos.google.analytics.data.v1beta.IListAudienceExportsResponse + | null + | undefined, + protos.google.analytics.data.v1beta.IAudienceExport + >, + callback?: PaginationCallback< + protos.google.analytics.data.v1beta.IListAudienceExportsRequest, + | protos.google.analytics.data.v1beta.IListAudienceExportsResponse + | null + | undefined, + protos.google.analytics.data.v1beta.IAudienceExport + >, + ): Promise< + [ + protos.google.analytics.data.v1beta.IAudienceExport[], + protos.google.analytics.data.v1beta.IListAudienceExportsRequest | null, + protos.google.analytics.data.v1beta.IListAudienceExportsResponse, + ] + > | 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.analytics.data.v1beta.IListAudienceExportsRequest, - protos.google.analytics.data.v1beta.IListAudienceExportsResponse|null|undefined, - protos.google.analytics.data.v1beta.IAudienceExport>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.analytics.data.v1beta.IListAudienceExportsRequest, + | protos.google.analytics.data.v1beta.IListAudienceExportsResponse + | null + | undefined, + protos.google.analytics.data.v1beta.IAudienceExport + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listAudienceExports values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1785,125 +2333,129 @@ export class BetaAnalyticsDataClient { this._log.info('listAudienceExports request %j', request); return this.innerApiCalls .listAudienceExports(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.analytics.data.v1beta.IAudienceExport[], - protos.google.analytics.data.v1beta.IListAudienceExportsRequest|null, - protos.google.analytics.data.v1beta.IListAudienceExportsResponse - ]) => { - this._log.info('listAudienceExports values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.analytics.data.v1beta.IAudienceExport[], + protos.google.analytics.data.v1beta.IListAudienceExportsRequest | null, + protos.google.analytics.data.v1beta.IListAudienceExportsResponse, + ]) => { + this._log.info('listAudienceExports values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listAudienceExports`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. All audience exports for this property will be listed in the - * response. Format: `properties/{property}` - * @param {number} [request.pageSize] - * Optional. The maximum number of audience exports to return. The service may - * return fewer than this value. If unspecified, at most 200 audience exports - * will be returned. The maximum value is 1000 (higher values will be coerced - * to the maximum). - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListAudienceExports` - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListAudienceExports` - * must match the call that provided the page token. - * @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.analytics.data.v1beta.AudienceExport|AudienceExport} 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 `listAudienceExportsAsync()` - * 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 `listAudienceExports`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. All audience exports for this property will be listed in the + * response. Format: `properties/{property}` + * @param {number} [request.pageSize] + * Optional. The maximum number of audience exports to return. The service may + * return fewer than this value. If unspecified, at most 200 audience exports + * will be returned. The maximum value is 1000 (higher values will be coerced + * to the maximum). + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListAudienceExports` + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListAudienceExports` + * must match the call that provided the page token. + * @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.analytics.data.v1beta.AudienceExport|AudienceExport} 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 `listAudienceExportsAsync()` + * 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. + */ listAudienceExportsStream( - request?: protos.google.analytics.data.v1beta.IListAudienceExportsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.analytics.data.v1beta.IListAudienceExportsRequest, + 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['listAudienceExports']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listAudienceExports stream %j', request); return this.descriptors.page.listAudienceExports.createStream( this.innerApiCalls.listAudienceExports as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listAudienceExports`, 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. All audience exports for this property will be listed in the - * response. Format: `properties/{property}` - * @param {number} [request.pageSize] - * Optional. The maximum number of audience exports to return. The service may - * return fewer than this value. If unspecified, at most 200 audience exports - * will be returned. The maximum value is 1000 (higher values will be coerced - * to the maximum). - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListAudienceExports` - * call. Provide this to retrieve the subsequent page. - * - * When paginating, all other parameters provided to `ListAudienceExports` - * must match the call that provided the 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 protos.google.analytics.data.v1beta.AudienceExport|AudienceExport}. 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 include:samples/generated/v1beta/beta_analytics_data.list_audience_exports.js - * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_ListAudienceExports_async - */ + /** + * Equivalent to `listAudienceExports`, 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. All audience exports for this property will be listed in the + * response. Format: `properties/{property}` + * @param {number} [request.pageSize] + * Optional. The maximum number of audience exports to return. The service may + * return fewer than this value. If unspecified, at most 200 audience exports + * will be returned. The maximum value is 1000 (higher values will be coerced + * to the maximum). + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListAudienceExports` + * call. Provide this to retrieve the subsequent page. + * + * When paginating, all other parameters provided to `ListAudienceExports` + * must match the call that provided the 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 protos.google.analytics.data.v1beta.AudienceExport|AudienceExport}. 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 include:samples/generated/v1beta/beta_analytics_data.list_audience_exports.js + * region_tag:analyticsdata_v1beta_generated_BetaAnalyticsData_ListAudienceExports_async + */ listAudienceExportsAsync( - request?: protos.google.analytics.data.v1beta.IListAudienceExportsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.analytics.data.v1beta.IListAudienceExportsRequest, + 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['listAudienceExports']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listAudienceExports iterate %j', request); return this.descriptors.page.listAudienceExports.asyncIterate( this.innerApiCalls['listAudienceExports'] as GaxCall, request as {}, - callSettings + callSettings, ) as 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. @@ -1946,22 +2498,22 @@ export class BetaAnalyticsDataClient { protos.google.longrunning.Operation, protos.google.longrunning.GetOperationRequest, {} | 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); } /** @@ -1996,15 +2548,15 @@ export class BetaAnalyticsDataClient { */ listOperationsAsync( request: protos.google.longrunning.ListOperationsRequest, - options?: gax.CallOptions + 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); } /** @@ -2038,7 +2590,7 @@ export class BetaAnalyticsDataClient { * await client.cancelOperation({name: ''}); * ``` */ - cancelOperation( + cancelOperation( request: protos.google.longrunning.CancelOperationRequest, optionsOrCallback?: | gax.CallOptions @@ -2051,25 +2603,24 @@ export class BetaAnalyticsDataClient { protos.google.longrunning.CancelOperationRequest, protos.google.protobuf.Empty, {} | 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); } - /** * Deletes a long-running operation. This method indicates that the client is * no longer interested in the operation result. It does not cancel the @@ -2108,22 +2659,22 @@ export class BetaAnalyticsDataClient { protos.google.protobuf.Empty, protos.google.longrunning.DeleteOperationRequest, {} | 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); } @@ -2138,7 +2689,7 @@ export class BetaAnalyticsDataClient { * @param {string} audience_export * @returns {string} Resource name string. */ - audienceExportPath(property:string,audienceExport:string) { + audienceExportPath(property: string, audienceExport: string) { return this.pathTemplates.audienceExportPathTemplate.render({ property: property, audience_export: audienceExport, @@ -2153,7 +2704,9 @@ export class BetaAnalyticsDataClient { * @returns {string} A string representing the property. */ matchPropertyFromAudienceExportName(audienceExportName: string) { - return this.pathTemplates.audienceExportPathTemplate.match(audienceExportName).property; + return this.pathTemplates.audienceExportPathTemplate.match( + audienceExportName, + ).property; } /** @@ -2164,7 +2717,9 @@ export class BetaAnalyticsDataClient { * @returns {string} A string representing the audience_export. */ matchAudienceExportFromAudienceExportName(audienceExportName: string) { - return this.pathTemplates.audienceExportPathTemplate.match(audienceExportName).audience_export; + return this.pathTemplates.audienceExportPathTemplate.match( + audienceExportName, + ).audience_export; } /** @@ -2173,7 +2728,7 @@ export class BetaAnalyticsDataClient { * @param {string} property * @returns {string} Resource name string. */ - metadataPath(property:string) { + metadataPath(property: string) { return this.pathTemplates.metadataPathTemplate.render({ property: property, }); @@ -2196,7 +2751,7 @@ export class BetaAnalyticsDataClient { * @param {string} property * @returns {string} Resource name string. */ - propertyPath(property:string) { + propertyPath(property: string) { return this.pathTemplates.propertyPathTemplate.render({ property: property, }); @@ -2221,7 +2776,7 @@ export class BetaAnalyticsDataClient { */ close(): Promise { if (this.betaAnalyticsDataStub && !this._terminated) { - return this.betaAnalyticsDataStub.then(stub => { + return this.betaAnalyticsDataStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -2230,4 +2785,4 @@ export class BetaAnalyticsDataClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-analytics-data/src/v1beta/index.ts b/packages/google-analytics-data/src/v1beta/index.ts index baac0092ffc3..defdd194c228 100644 --- a/packages/google-analytics-data/src/v1beta/index.ts +++ b/packages/google-analytics-data/src/v1beta/index.ts @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {BetaAnalyticsDataClient} from './beta_analytics_data_client'; +export { BetaAnalyticsDataClient } from './beta_analytics_data_client'; diff --git a/packages/google-analytics-data/system-test/fixtures/sample/src/index.ts b/packages/google-analytics-data/system-test/fixtures/sample/src/index.ts index 079657c400b5..738715bb441d 100644 --- a/packages/google-analytics-data/system-test/fixtures/sample/src/index.ts +++ b/packages/google-analytics-data/system-test/fixtures/sample/src/index.ts @@ -16,7 +16,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {BetaAnalyticsDataClient} from '@google-analytics/data'; +import { BetaAnalyticsDataClient } from '@google-analytics/data'; // check that the client class type name can be used function doStuffWithBetaAnalyticsDataClient(client: BetaAnalyticsDataClient) { diff --git a/packages/google-analytics-data/system-test/install.ts b/packages/google-analytics-data/system-test/install.ts index f66069aa3940..ccf167042d2e 100644 --- a/packages/google-analytics-data/system-test/install.ts +++ b/packages/google-analytics-data/system-test/install.ts @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - cjs: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/packages/google-analytics-data/test/gapic_alpha_analytics_data_v1alpha.ts b/packages/google-analytics-data/test/gapic_alpha_analytics_data_v1alpha.ts index 13e7fac4efb8..567c5f3510a1 100644 --- a/packages/google-analytics-data/test/gapic_alpha_analytics_data_v1alpha.ts +++ b/packages/google-analytics-data/test/gapic_alpha_analytics_data_v1alpha.ts @@ -19,2844 +19,3789 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as alphaanalyticsdataModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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('v1alpha.AlphaAnalyticsDataClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'analyticsdata.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient(); - 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 = alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient.servicePath; - assert.strictEqual(servicePath, 'analyticsdata.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'analyticsdata.googleapis.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'analyticsdata.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'analyticsdata.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'analyticsdata.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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'analyticsdata.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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'analyticsdata.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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('has universeDomain', () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has port', () => { - const port = alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient.port; - assert(port); - assert(typeof port === 'number'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient.servicePath; + assert.strictEqual(servicePath, 'analyticsdata.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'analyticsdata.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + universeDomain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'analyticsdata.example.com'); + }); - it('should create a client with no option', () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient(); - assert(client); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + universe_domain: 'example.com', }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'analyticsdata.example.com'); + }); - it('should create a client with gRPC fallback', () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - fallback: true, - }); - assert(client); + 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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'analyticsdata.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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'analyticsdata.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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.alphaAnalyticsDataStub, undefined); - await client.initialize(); - assert(client.alphaAnalyticsDataStub); - }); + it('has port', () => { + const port = + alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the initialized client', done => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.alphaAnalyticsDataStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('should create a client with no option', () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + fallback: true, }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.alphaAnalyticsDataStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); + it('has initialize method and supports deferred initialization', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); + assert.strictEqual(client.alphaAnalyticsDataStub, undefined); + await client.initialize(); + assert(client.alphaAnalyticsDataStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - 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 close method for the initialized client', (done) => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.alphaAnalyticsDataStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - 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('has close method for the non-initialized client', (done) => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.alphaAnalyticsDataStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('runFunnelReport', () => { - it('invokes runFunnelReport without error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.RunFunnelReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.RunFunnelReportRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1alpha.RunFunnelReportResponse() - ); - client.innerApiCalls.runFunnelReport = stubSimpleCall(expectedResponse); - const [response] = await client.runFunnelReport(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.runFunnelReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runFunnelReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes runFunnelReport without error using callback', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.RunFunnelReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.RunFunnelReportRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1alpha.RunFunnelReportResponse() - ); - client.innerApiCalls.runFunnelReport = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.runFunnelReport( - request, - (err?: Error|null, result?: protos.google.analytics.data.v1alpha.IRunFunnelReportResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.runFunnelReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runFunnelReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes runFunnelReport with error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.RunFunnelReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.RunFunnelReportRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.runFunnelReport = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.runFunnelReport(request), expectedError); - const actualRequest = (client.innerApiCalls.runFunnelReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runFunnelReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes runFunnelReport with closed client', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.RunFunnelReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.RunFunnelReportRequest', ['property']); - request.property = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.runFunnelReport(request), expectedError); - }); - }); - - describe('queryAudienceList', () => { - it('invokes queryAudienceList without error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.QueryAudienceListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.QueryAudienceListRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1alpha.QueryAudienceListResponse() - ); - client.innerApiCalls.queryAudienceList = stubSimpleCall(expectedResponse); - const [response] = await client.queryAudienceList(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.queryAudienceList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.queryAudienceList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes queryAudienceList without error using callback', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.QueryAudienceListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.QueryAudienceListRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1alpha.QueryAudienceListResponse() - ); - client.innerApiCalls.queryAudienceList = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.queryAudienceList( - request, - (err?: Error|null, result?: protos.google.analytics.data.v1alpha.IQueryAudienceListResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.queryAudienceList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.queryAudienceList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes queryAudienceList with error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.QueryAudienceListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.QueryAudienceListRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.queryAudienceList = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.queryAudienceList(request), expectedError); - const actualRequest = (client.innerApiCalls.queryAudienceList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.queryAudienceList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes queryAudienceList with closed client', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.QueryAudienceListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.QueryAudienceListRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.queryAudienceList(request), expectedError); - }); - }); - - describe('getAudienceList', () => { - it('invokes getAudienceList without error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.GetAudienceListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.GetAudienceListRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1alpha.AudienceList() - ); - client.innerApiCalls.getAudienceList = stubSimpleCall(expectedResponse); - const [response] = await client.getAudienceList(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAudienceList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAudienceList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAudienceList without error using callback', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.GetAudienceListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.GetAudienceListRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1alpha.AudienceList() - ); - client.innerApiCalls.getAudienceList = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getAudienceList( - request, - (err?: Error|null, result?: protos.google.analytics.data.v1alpha.IAudienceList|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAudienceList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAudienceList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAudienceList with error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.GetAudienceListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.GetAudienceListRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getAudienceList = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getAudienceList(request), expectedError); - const actualRequest = (client.innerApiCalls.getAudienceList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAudienceList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getAudienceList with closed client', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.GetAudienceListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.GetAudienceListRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getAudienceList(request), expectedError); - }); - }); - - describe('createRecurringAudienceList', () => { - it('invokes createRecurringAudienceList without error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.CreateRecurringAudienceListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.CreateRecurringAudienceListRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1alpha.RecurringAudienceList() - ); - client.innerApiCalls.createRecurringAudienceList = stubSimpleCall(expectedResponse); - const [response] = await client.createRecurringAudienceList(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createRecurringAudienceList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createRecurringAudienceList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createRecurringAudienceList without error using callback', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.CreateRecurringAudienceListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.CreateRecurringAudienceListRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1alpha.RecurringAudienceList() - ); - client.innerApiCalls.createRecurringAudienceList = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createRecurringAudienceList( - request, - (err?: Error|null, result?: protos.google.analytics.data.v1alpha.IRecurringAudienceList|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createRecurringAudienceList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createRecurringAudienceList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createRecurringAudienceList with error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.CreateRecurringAudienceListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.CreateRecurringAudienceListRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createRecurringAudienceList = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createRecurringAudienceList(request), expectedError); - const actualRequest = (client.innerApiCalls.createRecurringAudienceList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createRecurringAudienceList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createRecurringAudienceList with closed client', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.CreateRecurringAudienceListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.CreateRecurringAudienceListRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createRecurringAudienceList(request), expectedError); - }); - }); - - describe('getRecurringAudienceList', () => { - it('invokes getRecurringAudienceList without error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.GetRecurringAudienceListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.GetRecurringAudienceListRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1alpha.RecurringAudienceList() - ); - client.innerApiCalls.getRecurringAudienceList = stubSimpleCall(expectedResponse); - const [response] = await client.getRecurringAudienceList(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getRecurringAudienceList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRecurringAudienceList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getRecurringAudienceList without error using callback', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.GetRecurringAudienceListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.GetRecurringAudienceListRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1alpha.RecurringAudienceList() - ); - client.innerApiCalls.getRecurringAudienceList = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getRecurringAudienceList( - request, - (err?: Error|null, result?: protos.google.analytics.data.v1alpha.IRecurringAudienceList|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getRecurringAudienceList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRecurringAudienceList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getRecurringAudienceList with error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.GetRecurringAudienceListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.GetRecurringAudienceListRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getRecurringAudienceList = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getRecurringAudienceList(request), expectedError); - const actualRequest = (client.innerApiCalls.getRecurringAudienceList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getRecurringAudienceList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getRecurringAudienceList with closed client', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.GetRecurringAudienceListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.GetRecurringAudienceListRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getRecurringAudienceList(request), expectedError); - }); - }); - - describe('getPropertyQuotasSnapshot', () => { - it('invokes getPropertyQuotasSnapshot without error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.GetPropertyQuotasSnapshotRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.GetPropertyQuotasSnapshotRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1alpha.PropertyQuotasSnapshot() - ); - client.innerApiCalls.getPropertyQuotasSnapshot = stubSimpleCall(expectedResponse); - const [response] = await client.getPropertyQuotasSnapshot(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getPropertyQuotasSnapshot as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getPropertyQuotasSnapshot as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getPropertyQuotasSnapshot without error using callback', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.GetPropertyQuotasSnapshotRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.GetPropertyQuotasSnapshotRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1alpha.PropertyQuotasSnapshot() - ); - client.innerApiCalls.getPropertyQuotasSnapshot = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getPropertyQuotasSnapshot( - request, - (err?: Error|null, result?: protos.google.analytics.data.v1alpha.IPropertyQuotasSnapshot|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getPropertyQuotasSnapshot as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getPropertyQuotasSnapshot as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getPropertyQuotasSnapshot with error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.GetPropertyQuotasSnapshotRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.GetPropertyQuotasSnapshotRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getPropertyQuotasSnapshot = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getPropertyQuotasSnapshot(request), expectedError); - const actualRequest = (client.innerApiCalls.getPropertyQuotasSnapshot as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getPropertyQuotasSnapshot as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getPropertyQuotasSnapshot with closed client', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.GetPropertyQuotasSnapshotRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.GetPropertyQuotasSnapshotRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getPropertyQuotasSnapshot(request), expectedError); - }); - }); - - describe('queryReportTask', () => { - it('invokes queryReportTask without error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.QueryReportTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.QueryReportTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1alpha.QueryReportTaskResponse() - ); - client.innerApiCalls.queryReportTask = stubSimpleCall(expectedResponse); - const [response] = await client.queryReportTask(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.queryReportTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.queryReportTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes queryReportTask without error using callback', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.QueryReportTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.QueryReportTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1alpha.QueryReportTaskResponse() - ); - client.innerApiCalls.queryReportTask = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.queryReportTask( - request, - (err?: Error|null, result?: protos.google.analytics.data.v1alpha.IQueryReportTaskResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.queryReportTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.queryReportTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes queryReportTask with error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.QueryReportTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.QueryReportTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.queryReportTask = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.queryReportTask(request), expectedError); - const actualRequest = (client.innerApiCalls.queryReportTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.queryReportTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes queryReportTask with closed client', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.QueryReportTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.QueryReportTaskRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.queryReportTask(request), expectedError); - }); - }); - - describe('getReportTask', () => { - it('invokes getReportTask without error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.GetReportTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.GetReportTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1alpha.ReportTask() - ); - client.innerApiCalls.getReportTask = stubSimpleCall(expectedResponse); - const [response] = await client.getReportTask(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getReportTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getReportTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getReportTask without error using callback', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.GetReportTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.GetReportTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1alpha.ReportTask() - ); - client.innerApiCalls.getReportTask = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getReportTask( - request, - (err?: Error|null, result?: protos.google.analytics.data.v1alpha.IReportTask|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getReportTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getReportTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getReportTask with error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.GetReportTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.GetReportTaskRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getReportTask = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getReportTask(request), expectedError); - const actualRequest = (client.innerApiCalls.getReportTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getReportTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getReportTask with closed client', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.GetReportTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.GetReportTaskRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getReportTask(request), expectedError); - }); - }); - - describe('runReport', () => { - it('invokes runReport without error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.RunReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.RunReportRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1alpha.RunReportResponse() - ); - client.innerApiCalls.runReport = stubSimpleCall(expectedResponse); - const [response] = await client.runReport(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.runReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes runReport without error using callback', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.RunReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.RunReportRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1alpha.RunReportResponse() - ); - client.innerApiCalls.runReport = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.runReport( - request, - (err?: Error|null, result?: protos.google.analytics.data.v1alpha.IRunReportResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.runReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes runReport with error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.RunReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.RunReportRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.runReport = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.runReport(request), expectedError); - const actualRequest = (client.innerApiCalls.runReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes runReport with closed client', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.RunReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.RunReportRequest', ['property']); - request.property = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.runReport(request), expectedError); - }); - }); - - describe('getMetadata', () => { - it('invokes getMetadata without error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.GetMetadataRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.GetMetadataRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1alpha.Metadata() - ); - client.innerApiCalls.getMetadata = stubSimpleCall(expectedResponse); - const [response] = await client.getMetadata(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getMetadata as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMetadata as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getMetadata without error using callback', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.GetMetadataRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.GetMetadataRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1alpha.Metadata() - ); - client.innerApiCalls.getMetadata = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getMetadata( - request, - (err?: Error|null, result?: protos.google.analytics.data.v1alpha.IMetadata|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getMetadata as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMetadata as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getMetadata with error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.GetMetadataRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.GetMetadataRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getMetadata = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getMetadata(request), expectedError); - const actualRequest = (client.innerApiCalls.getMetadata as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMetadata as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getMetadata with closed client', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.GetMetadataRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.GetMetadataRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getMetadata(request), expectedError); - }); - }); - - describe('createAudienceList', () => { - it('invokes createAudienceList without error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.CreateAudienceListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.CreateAudienceListRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createAudienceList = stubLongRunningCall(expectedResponse); - const [operation] = await client.createAudienceList(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createAudienceList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createAudienceList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createAudienceList without error using callback', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.CreateAudienceListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.CreateAudienceListRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createAudienceList = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createAudienceList( - 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.createAudienceList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createAudienceList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createAudienceList with call error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.CreateAudienceListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.CreateAudienceListRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createAudienceList = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.createAudienceList(request), expectedError); - const actualRequest = (client.innerApiCalls.createAudienceList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createAudienceList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createAudienceList with LRO error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.CreateAudienceListRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.CreateAudienceListRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createAudienceList = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.createAudienceList(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.createAudienceList as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createAudienceList as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes checkCreateAudienceListProgress without error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - 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.checkCreateAudienceListProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); - - it('invokes checkCreateAudienceListProgress with error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + 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()); + }); - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkCreateAudienceListProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + 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('runFunnelReport', () => { + it('invokes runFunnelReport without error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.RunFunnelReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.RunFunnelReportRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1alpha.RunFunnelReportResponse(), + ); + client.innerApiCalls.runFunnelReport = stubSimpleCall(expectedResponse); + const [response] = await client.runFunnelReport(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runFunnelReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runFunnelReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createReportTask', () => { - it('invokes createReportTask without error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.CreateReportTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.CreateReportTaskRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createReportTask = stubLongRunningCall(expectedResponse); - const [operation] = await client.createReportTask(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createReportTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createReportTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createReportTask without error using callback', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.CreateReportTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.CreateReportTaskRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createReportTask = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createReportTask( - 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.createReportTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createReportTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createReportTask with call error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.CreateReportTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.CreateReportTaskRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createReportTask = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.createReportTask(request), expectedError); - const actualRequest = (client.innerApiCalls.createReportTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createReportTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createReportTask with LRO error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.CreateReportTaskRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.CreateReportTaskRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createReportTask = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.createReportTask(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.createReportTask as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createReportTask as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes checkCreateReportTaskProgress without error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - 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.checkCreateReportTaskProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); - - it('invokes checkCreateReportTaskProgress with error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); + it('invokes runFunnelReport without error using callback', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.RunFunnelReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.RunFunnelReportRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1alpha.RunFunnelReportResponse(), + ); + client.innerApiCalls.runFunnelReport = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.runFunnelReport( + request, + ( + err?: Error | null, + result?: protos.google.analytics.data.v1alpha.IRunFunnelReportResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runFunnelReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runFunnelReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkCreateReportTaskProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes runFunnelReport with error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.RunFunnelReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.RunFunnelReportRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.runFunnelReport = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.runFunnelReport(request), expectedError); + const actualRequest = ( + client.innerApiCalls.runFunnelReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runFunnelReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listAudienceLists', () => { - it('invokes listAudienceLists without error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.ListAudienceListsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.ListAudienceListsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.data.v1alpha.AudienceList()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.AudienceList()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.AudienceList()), - ]; - client.innerApiCalls.listAudienceLists = stubSimpleCall(expectedResponse); - const [response] = await client.listAudienceLists(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listAudienceLists as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listAudienceLists as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listAudienceLists without error using callback', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.ListAudienceListsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.ListAudienceListsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.data.v1alpha.AudienceList()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.AudienceList()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.AudienceList()), - ]; - client.innerApiCalls.listAudienceLists = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listAudienceLists( - request, - (err?: Error|null, result?: protos.google.analytics.data.v1alpha.IAudienceList[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listAudienceLists as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listAudienceLists as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listAudienceLists with error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.ListAudienceListsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.ListAudienceListsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listAudienceLists = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listAudienceLists(request), expectedError); - const actualRequest = (client.innerApiCalls.listAudienceLists as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listAudienceLists as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listAudienceListsStream without error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.ListAudienceListsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.ListAudienceListsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.data.v1alpha.AudienceList()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.AudienceList()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.AudienceList()), - ]; - client.descriptors.page.listAudienceLists.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listAudienceListsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.data.v1alpha.AudienceList[] = []; - stream.on('data', (response: protos.google.analytics.data.v1alpha.AudienceList) => { - 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.listAudienceLists.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listAudienceLists, request)); - assert( - (client.descriptors.page.listAudienceLists.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('invokes listAudienceListsStream with error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.ListAudienceListsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.ListAudienceListsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listAudienceLists.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listAudienceListsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.data.v1alpha.AudienceList[] = []; - stream.on('data', (response: protos.google.analytics.data.v1alpha.AudienceList) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listAudienceLists.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listAudienceLists, request)); - assert( - (client.descriptors.page.listAudienceLists.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listAudienceLists without error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.ListAudienceListsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.ListAudienceListsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.data.v1alpha.AudienceList()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.AudienceList()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.AudienceList()), - ]; - client.descriptors.page.listAudienceLists.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.data.v1alpha.IAudienceList[] = []; - const iterable = client.listAudienceListsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes runFunnelReport with closed client', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.RunFunnelReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.RunFunnelReportRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.runFunnelReport(request), expectedError); + }); + }); + + describe('queryAudienceList', () => { + it('invokes queryAudienceList without error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.QueryAudienceListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.QueryAudienceListRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1alpha.QueryAudienceListResponse(), + ); + client.innerApiCalls.queryAudienceList = stubSimpleCall(expectedResponse); + const [response] = await client.queryAudienceList(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.queryAudienceList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.queryAudienceList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes queryAudienceList without error using callback', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.QueryAudienceListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.QueryAudienceListRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1alpha.QueryAudienceListResponse(), + ); + client.innerApiCalls.queryAudienceList = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.queryAudienceList( + request, + ( + err?: Error | null, + result?: protos.google.analytics.data.v1alpha.IQueryAudienceListResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listAudienceLists.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listAudienceLists.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listAudienceLists with error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.ListAudienceListsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.ListAudienceListsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listAudienceLists.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listAudienceListsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.data.v1alpha.IAudienceList[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listAudienceLists.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listAudienceLists.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - }); - - describe('listRecurringAudienceLists', () => { - it('invokes listRecurringAudienceLists without error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.data.v1alpha.RecurringAudienceList()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.RecurringAudienceList()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.RecurringAudienceList()), - ]; - client.innerApiCalls.listRecurringAudienceLists = stubSimpleCall(expectedResponse); - const [response] = await client.listRecurringAudienceLists(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listRecurringAudienceLists as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listRecurringAudienceLists as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listRecurringAudienceLists without error using callback', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.data.v1alpha.RecurringAudienceList()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.RecurringAudienceList()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.RecurringAudienceList()), - ]; - client.innerApiCalls.listRecurringAudienceLists = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listRecurringAudienceLists( - request, - (err?: Error|null, result?: protos.google.analytics.data.v1alpha.IRecurringAudienceList[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listRecurringAudienceLists as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listRecurringAudienceLists as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listRecurringAudienceLists with error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listRecurringAudienceLists = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listRecurringAudienceLists(request), expectedError); - const actualRequest = (client.innerApiCalls.listRecurringAudienceLists as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listRecurringAudienceLists as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listRecurringAudienceListsStream without error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.data.v1alpha.RecurringAudienceList()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.RecurringAudienceList()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.RecurringAudienceList()), - ]; - client.descriptors.page.listRecurringAudienceLists.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listRecurringAudienceListsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.data.v1alpha.RecurringAudienceList[] = []; - stream.on('data', (response: protos.google.analytics.data.v1alpha.RecurringAudienceList) => { - 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.listRecurringAudienceLists.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listRecurringAudienceLists, request)); - assert( - (client.descriptors.page.listRecurringAudienceLists.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('invokes listRecurringAudienceListsStream with error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listRecurringAudienceLists.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listRecurringAudienceListsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.data.v1alpha.RecurringAudienceList[] = []; - stream.on('data', (response: protos.google.analytics.data.v1alpha.RecurringAudienceList) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listRecurringAudienceLists.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listRecurringAudienceLists, request)); - assert( - (client.descriptors.page.listRecurringAudienceLists.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listRecurringAudienceLists without error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.data.v1alpha.RecurringAudienceList()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.RecurringAudienceList()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.RecurringAudienceList()), - ]; - client.descriptors.page.listRecurringAudienceLists.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.data.v1alpha.IRecurringAudienceList[] = []; - const iterable = client.listRecurringAudienceListsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.queryAudienceList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.queryAudienceList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes queryAudienceList with error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.QueryAudienceListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.QueryAudienceListRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.queryAudienceList = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.queryAudienceList(request), expectedError); + const actualRequest = ( + client.innerApiCalls.queryAudienceList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.queryAudienceList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes queryAudienceList with closed client', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.QueryAudienceListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.QueryAudienceListRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.queryAudienceList(request), expectedError); + }); + }); + + describe('getAudienceList', () => { + it('invokes getAudienceList without error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.GetAudienceListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.GetAudienceListRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1alpha.AudienceList(), + ); + client.innerApiCalls.getAudienceList = stubSimpleCall(expectedResponse); + const [response] = await client.getAudienceList(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAudienceList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAudienceList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getAudienceList without error using callback', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.GetAudienceListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.GetAudienceListRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1alpha.AudienceList(), + ); + client.innerApiCalls.getAudienceList = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getAudienceList( + request, + ( + err?: Error | null, + result?: protos.google.analytics.data.v1alpha.IAudienceList | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listRecurringAudienceLists.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listRecurringAudienceLists.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listRecurringAudienceLists with error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listRecurringAudienceLists.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listRecurringAudienceListsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.data.v1alpha.IRecurringAudienceList[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listRecurringAudienceLists.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listRecurringAudienceLists.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - }); - - describe('listReportTasks', () => { - it('invokes listReportTasks without error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.ListReportTasksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.ListReportTasksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.data.v1alpha.ReportTask()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.ReportTask()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.ReportTask()), - ]; - client.innerApiCalls.listReportTasks = stubSimpleCall(expectedResponse); - const [response] = await client.listReportTasks(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listReportTasks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listReportTasks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listReportTasks without error using callback', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.ListReportTasksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.ListReportTasksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.data.v1alpha.ReportTask()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.ReportTask()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.ReportTask()), - ]; - client.innerApiCalls.listReportTasks = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listReportTasks( - request, - (err?: Error|null, result?: protos.google.analytics.data.v1alpha.IReportTask[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listReportTasks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listReportTasks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listReportTasks with error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.ListReportTasksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.ListReportTasksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listReportTasks = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listReportTasks(request), expectedError); - const actualRequest = (client.innerApiCalls.listReportTasks as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listReportTasks as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listReportTasksStream without error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.ListReportTasksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.ListReportTasksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.data.v1alpha.ReportTask()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.ReportTask()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.ReportTask()), - ]; - client.descriptors.page.listReportTasks.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listReportTasksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.data.v1alpha.ReportTask[] = []; - stream.on('data', (response: protos.google.analytics.data.v1alpha.ReportTask) => { - 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.listReportTasks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listReportTasks, request)); - assert( - (client.descriptors.page.listReportTasks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('invokes listReportTasksStream with error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.ListReportTasksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.ListReportTasksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listReportTasks.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listReportTasksStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.data.v1alpha.ReportTask[] = []; - stream.on('data', (response: protos.google.analytics.data.v1alpha.ReportTask) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listReportTasks.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listReportTasks, request)); - assert( - (client.descriptors.page.listReportTasks.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listReportTasks without error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.ListReportTasksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.ListReportTasksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.data.v1alpha.ReportTask()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.ReportTask()), - generateSampleMessage(new protos.google.analytics.data.v1alpha.ReportTask()), - ]; - client.descriptors.page.listReportTasks.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.data.v1alpha.IReportTask[] = []; - const iterable = client.listReportTasksAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAudienceList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAudienceList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getAudienceList with error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.GetAudienceListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.GetAudienceListRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getAudienceList = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getAudienceList(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getAudienceList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAudienceList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getAudienceList with closed client', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.GetAudienceListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.GetAudienceListRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getAudienceList(request), expectedError); + }); + }); + + describe('createRecurringAudienceList', () => { + it('invokes createRecurringAudienceList without error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.CreateRecurringAudienceListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.CreateRecurringAudienceListRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1alpha.RecurringAudienceList(), + ); + client.innerApiCalls.createRecurringAudienceList = + stubSimpleCall(expectedResponse); + const [response] = await client.createRecurringAudienceList(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createRecurringAudienceList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createRecurringAudienceList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createRecurringAudienceList without error using callback', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.CreateRecurringAudienceListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.CreateRecurringAudienceListRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1alpha.RecurringAudienceList(), + ); + client.innerApiCalls.createRecurringAudienceList = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createRecurringAudienceList( + request, + ( + err?: Error | null, + result?: protos.google.analytics.data.v1alpha.IRecurringAudienceList | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listReportTasks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listReportTasks.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listReportTasks with error', async () => { - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1alpha.ListReportTasksRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1alpha.ListReportTasksRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listReportTasks.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listReportTasksAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.data.v1alpha.IReportTask[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listReportTasks.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listReportTasks.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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - 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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - 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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - 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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - 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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - 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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - 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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - 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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - 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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - 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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - 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); + const actualRequest = ( + client.innerApiCalls.createRecurringAudienceList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createRecurringAudienceList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createRecurringAudienceList with error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.CreateRecurringAudienceListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.CreateRecurringAudienceListRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createRecurringAudienceList = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createRecurringAudienceList(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createRecurringAudienceList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createRecurringAudienceList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createRecurringAudienceList with closed client', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.CreateRecurringAudienceListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.CreateRecurringAudienceListRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createRecurringAudienceList(request), + expectedError, + ); + }); + }); + + describe('getRecurringAudienceList', () => { + it('invokes getRecurringAudienceList without error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.GetRecurringAudienceListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.GetRecurringAudienceListRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1alpha.RecurringAudienceList(), + ); + client.innerApiCalls.getRecurringAudienceList = + stubSimpleCall(expectedResponse); + const [response] = await client.getRecurringAudienceList(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getRecurringAudienceList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRecurringAudienceList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getRecurringAudienceList without error using callback', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.GetRecurringAudienceListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.GetRecurringAudienceListRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1alpha.RecurringAudienceList(), + ); + client.innerApiCalls.getRecurringAudienceList = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getRecurringAudienceList( + request, + ( + err?: Error | null, + result?: protos.google.analytics.data.v1alpha.IRecurringAudienceList | 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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - 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); - }); + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getRecurringAudienceList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRecurringAudienceList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { + it('invokes getRecurringAudienceList with error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.GetRecurringAudienceListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.GetRecurringAudienceListRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getRecurringAudienceList = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getRecurringAudienceList(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getRecurringAudienceList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getRecurringAudienceList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('audienceList', async () => { - const fakePath = "/rendered/path/audienceList"; - const expectedParameters = { - property: "propertyValue", - audience_list: "audienceListValue", - }; - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.audienceListPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.audienceListPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('audienceListPath', () => { - const result = client.audienceListPath("propertyValue", "audienceListValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.audienceListPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes getRecurringAudienceList with closed client', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.GetRecurringAudienceListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.GetRecurringAudienceListRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getRecurringAudienceList(request), + expectedError, + ); + }); + }); + + describe('getPropertyQuotasSnapshot', () => { + it('invokes getPropertyQuotasSnapshot without error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.GetPropertyQuotasSnapshotRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.GetPropertyQuotasSnapshotRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1alpha.PropertyQuotasSnapshot(), + ); + client.innerApiCalls.getPropertyQuotasSnapshot = + stubSimpleCall(expectedResponse); + const [response] = await client.getPropertyQuotasSnapshot(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getPropertyQuotasSnapshot as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getPropertyQuotasSnapshot as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchPropertyFromAudienceListName', () => { - const result = client.matchPropertyFromAudienceListName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.audienceListPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes getPropertyQuotasSnapshot without error using callback', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.GetPropertyQuotasSnapshotRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.GetPropertyQuotasSnapshotRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1alpha.PropertyQuotasSnapshot(), + ); + client.innerApiCalls.getPropertyQuotasSnapshot = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getPropertyQuotasSnapshot( + request, + ( + err?: Error | null, + result?: protos.google.analytics.data.v1alpha.IPropertyQuotasSnapshot | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getPropertyQuotasSnapshot as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getPropertyQuotasSnapshot as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchAudienceListFromAudienceListName', () => { - const result = client.matchAudienceListFromAudienceListName(fakePath); - assert.strictEqual(result, "audienceListValue"); - assert((client.pathTemplates.audienceListPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes getPropertyQuotasSnapshot with error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.GetPropertyQuotasSnapshotRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.GetPropertyQuotasSnapshotRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getPropertyQuotasSnapshot = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getPropertyQuotasSnapshot(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getPropertyQuotasSnapshot as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getPropertyQuotasSnapshot as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('metadata', async () => { - const fakePath = "/rendered/path/metadata"; - const expectedParameters = { - property: "propertyValue", - }; - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.metadataPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.metadataPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('metadataPath', () => { - const result = client.metadataPath("propertyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.metadataPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes getPropertyQuotasSnapshot with closed client', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.GetPropertyQuotasSnapshotRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.GetPropertyQuotasSnapshotRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getPropertyQuotasSnapshot(request), + expectedError, + ); + }); + }); + + describe('queryReportTask', () => { + it('invokes queryReportTask without error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.QueryReportTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.QueryReportTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1alpha.QueryReportTaskResponse(), + ); + client.innerApiCalls.queryReportTask = stubSimpleCall(expectedResponse); + const [response] = await client.queryReportTask(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.queryReportTask as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.queryReportTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchPropertyFromMetadataName', () => { - const result = client.matchPropertyFromMetadataName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.metadataPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes queryReportTask without error using callback', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.QueryReportTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.QueryReportTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1alpha.QueryReportTaskResponse(), + ); + client.innerApiCalls.queryReportTask = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.queryReportTask( + request, + ( + err?: Error | null, + result?: protos.google.analytics.data.v1alpha.IQueryReportTaskResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.queryReportTask as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.queryReportTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('property', async () => { - const fakePath = "/rendered/path/property"; - const expectedParameters = { - property: "propertyValue", - }; - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.propertyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.propertyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('propertyPath', () => { - const result = client.propertyPath("propertyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.propertyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes queryReportTask with error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.QueryReportTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.QueryReportTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.queryReportTask = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.queryReportTask(request), expectedError); + const actualRequest = ( + client.innerApiCalls.queryReportTask as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.queryReportTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchPropertyFromPropertyName', () => { - const result = client.matchPropertyFromPropertyName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.propertyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes queryReportTask with closed client', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.QueryReportTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.QueryReportTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.queryReportTask(request), expectedError); + }); + }); + + describe('getReportTask', () => { + it('invokes getReportTask without error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.GetReportTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.GetReportTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1alpha.ReportTask(), + ); + client.innerApiCalls.getReportTask = stubSimpleCall(expectedResponse); + const [response] = await client.getReportTask(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getReportTask as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getReportTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('propertyQuotasSnapshot', async () => { - const fakePath = "/rendered/path/propertyQuotasSnapshot"; - const expectedParameters = { - property: "propertyValue", - }; - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.propertyQuotasSnapshotPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.propertyQuotasSnapshotPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('propertyQuotasSnapshotPath', () => { - const result = client.propertyQuotasSnapshotPath("propertyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.propertyQuotasSnapshotPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes getReportTask without error using callback', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.GetReportTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.GetReportTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1alpha.ReportTask(), + ); + client.innerApiCalls.getReportTask = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getReportTask( + request, + ( + err?: Error | null, + result?: protos.google.analytics.data.v1alpha.IReportTask | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getReportTask as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getReportTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchPropertyFromPropertyQuotasSnapshotName', () => { - const result = client.matchPropertyFromPropertyQuotasSnapshotName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.propertyQuotasSnapshotPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes getReportTask with error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.GetReportTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.GetReportTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getReportTask = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getReportTask(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getReportTask as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getReportTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('recurringAudienceList', async () => { - const fakePath = "/rendered/path/recurringAudienceList"; - const expectedParameters = { - property: "propertyValue", - recurring_audience_list: "recurringAudienceListValue", - }; - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.recurringAudienceListPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.recurringAudienceListPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('recurringAudienceListPath', () => { - const result = client.recurringAudienceListPath("propertyValue", "recurringAudienceListValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.recurringAudienceListPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes getReportTask with closed client', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.GetReportTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.GetReportTaskRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getReportTask(request), expectedError); + }); + }); + + describe('runReport', () => { + it('invokes runReport without error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.RunReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.RunReportRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1alpha.RunReportResponse(), + ); + client.innerApiCalls.runReport = stubSimpleCall(expectedResponse); + const [response] = await client.runReport(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchPropertyFromRecurringAudienceListName', () => { - const result = client.matchPropertyFromRecurringAudienceListName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.recurringAudienceListPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes runReport without error using callback', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.RunReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.RunReportRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1alpha.RunReportResponse(), + ); + client.innerApiCalls.runReport = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.runReport( + request, + ( + err?: Error | null, + result?: protos.google.analytics.data.v1alpha.IRunReportResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchRecurringAudienceListFromRecurringAudienceListName', () => { - const result = client.matchRecurringAudienceListFromRecurringAudienceListName(fakePath); - assert.strictEqual(result, "recurringAudienceListValue"); - assert((client.pathTemplates.recurringAudienceListPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes runReport with error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.RunReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.RunReportRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.runReport = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.runReport(request), expectedError); + const actualRequest = ( + client.innerApiCalls.runReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - describe('reportTask', async () => { - const fakePath = "/rendered/path/reportTask"; - const expectedParameters = { - property: "propertyValue", - report_task: "reportTaskValue", - }; - const client = new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.reportTaskPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.reportTaskPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('reportTaskPath', () => { - const result = client.reportTaskPath("propertyValue", "reportTaskValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.reportTaskPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + it('invokes runReport with closed client', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.RunReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.RunReportRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.runReport(request), expectedError); + }); + }); + + describe('getMetadata', () => { + it('invokes getMetadata without error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.GetMetadataRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.GetMetadataRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1alpha.Metadata(), + ); + client.innerApiCalls.getMetadata = stubSimpleCall(expectedResponse); + const [response] = await client.getMetadata(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getMetadata as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMetadata as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchPropertyFromReportTaskName', () => { - const result = client.matchPropertyFromReportTaskName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.reportTaskPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); + it('invokes getMetadata without error using callback', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.GetMetadataRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.GetMetadataRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1alpha.Metadata(), + ); + client.innerApiCalls.getMetadata = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getMetadata( + request, + ( + err?: Error | null, + result?: protos.google.analytics.data.v1alpha.IMetadata | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getMetadata as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMetadata as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('matchReportTaskFromReportTaskName', () => { - const result = client.matchReportTaskFromReportTaskName(fakePath); - assert.strictEqual(result, "reportTaskValue"); - assert((client.pathTemplates.reportTaskPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes getMetadata with error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.GetMetadataRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.GetMetadataRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getMetadata = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getMetadata(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getMetadata as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMetadata as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes getMetadata with closed client', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.GetMetadataRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.GetMetadataRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getMetadata(request), expectedError); + }); + }); + + describe('createAudienceList', () => { + it('invokes createAudienceList without error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.CreateAudienceListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.CreateAudienceListRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createAudienceList = + stubLongRunningCall(expectedResponse); + const [operation] = await client.createAudienceList(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createAudienceList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createAudienceList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createAudienceList without error using callback', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.CreateAudienceListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.CreateAudienceListRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createAudienceList = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createAudienceList( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.analytics.data.v1alpha.IAudienceList, + protos.google.analytics.data.v1alpha.IAudienceListMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.analytics.data.v1alpha.IAudienceList, + protos.google.analytics.data.v1alpha.IAudienceListMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createAudienceList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createAudienceList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createAudienceList with call error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.CreateAudienceListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.CreateAudienceListRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createAudienceList = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.createAudienceList(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createAudienceList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createAudienceList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createAudienceList with LRO error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.CreateAudienceListRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.CreateAudienceListRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createAudienceList = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.createAudienceList(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.createAudienceList as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createAudienceList as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkCreateAudienceListProgress without error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + 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.checkCreateAudienceListProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkCreateAudienceListProgress with error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + 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.checkCreateAudienceListProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('createReportTask', () => { + it('invokes createReportTask without error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.CreateReportTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.CreateReportTaskRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createReportTask = + stubLongRunningCall(expectedResponse); + const [operation] = await client.createReportTask(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createReportTask as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createReportTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createReportTask without error using callback', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.CreateReportTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.CreateReportTaskRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createReportTask = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createReportTask( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.analytics.data.v1alpha.IReportTask, + protos.google.analytics.data.v1alpha.IReportTaskMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.analytics.data.v1alpha.IReportTask, + protos.google.analytics.data.v1alpha.IReportTaskMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createReportTask as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createReportTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createReportTask with call error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.CreateReportTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.CreateReportTaskRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createReportTask = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.createReportTask(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createReportTask as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createReportTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createReportTask with LRO error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.CreateReportTaskRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.CreateReportTaskRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createReportTask = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.createReportTask(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.createReportTask as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createReportTask as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkCreateReportTaskProgress without error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + 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.checkCreateReportTaskProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkCreateReportTaskProgress with error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + 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.checkCreateReportTaskProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('listAudienceLists', () => { + it('invokes listAudienceLists without error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.ListAudienceListsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.ListAudienceListsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.data.v1alpha.AudienceList(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.AudienceList(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.AudienceList(), + ), + ]; + client.innerApiCalls.listAudienceLists = stubSimpleCall(expectedResponse); + const [response] = await client.listAudienceLists(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listAudienceLists as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listAudienceLists as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listAudienceLists without error using callback', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.ListAudienceListsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.ListAudienceListsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.data.v1alpha.AudienceList(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.AudienceList(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.AudienceList(), + ), + ]; + client.innerApiCalls.listAudienceLists = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listAudienceLists( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.data.v1alpha.IAudienceList[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listAudienceLists as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listAudienceLists as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listAudienceLists with error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.ListAudienceListsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.ListAudienceListsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listAudienceLists = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listAudienceLists(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listAudienceLists as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listAudienceLists as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listAudienceListsStream without error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.ListAudienceListsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.ListAudienceListsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.data.v1alpha.AudienceList(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.AudienceList(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.AudienceList(), + ), + ]; + client.descriptors.page.listAudienceLists.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listAudienceListsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.data.v1alpha.AudienceList[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.data.v1alpha.AudienceList) => { + 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.listAudienceLists.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listAudienceLists, request), + ); + assert( + (client.descriptors.page.listAudienceLists.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listAudienceListsStream with error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.ListAudienceListsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.ListAudienceListsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listAudienceLists.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listAudienceListsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.data.v1alpha.AudienceList[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.data.v1alpha.AudienceList) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listAudienceLists.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listAudienceLists, request), + ); + assert( + (client.descriptors.page.listAudienceLists.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listAudienceLists without error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.ListAudienceListsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.ListAudienceListsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.data.v1alpha.AudienceList(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.AudienceList(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.AudienceList(), + ), + ]; + client.descriptors.page.listAudienceLists.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.data.v1alpha.IAudienceList[] = + []; + const iterable = client.listAudienceListsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listAudienceLists.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listAudienceLists.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listAudienceLists with error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.ListAudienceListsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.ListAudienceListsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listAudienceLists.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listAudienceListsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.data.v1alpha.IAudienceList[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listAudienceLists.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listAudienceLists.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listRecurringAudienceLists', () => { + it('invokes listRecurringAudienceLists without error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.data.v1alpha.RecurringAudienceList(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.RecurringAudienceList(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.RecurringAudienceList(), + ), + ]; + client.innerApiCalls.listRecurringAudienceLists = + stubSimpleCall(expectedResponse); + const [response] = await client.listRecurringAudienceLists(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listRecurringAudienceLists as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listRecurringAudienceLists as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listRecurringAudienceLists without error using callback', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.data.v1alpha.RecurringAudienceList(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.RecurringAudienceList(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.RecurringAudienceList(), + ), + ]; + client.innerApiCalls.listRecurringAudienceLists = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listRecurringAudienceLists( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.data.v1alpha.IRecurringAudienceList[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listRecurringAudienceLists as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listRecurringAudienceLists as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listRecurringAudienceLists with error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listRecurringAudienceLists = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.listRecurringAudienceLists(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.listRecurringAudienceLists as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listRecurringAudienceLists as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listRecurringAudienceListsStream without error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.data.v1alpha.RecurringAudienceList(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.RecurringAudienceList(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.RecurringAudienceList(), + ), + ]; + client.descriptors.page.listRecurringAudienceLists.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listRecurringAudienceListsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.data.v1alpha.RecurringAudienceList[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.data.v1alpha.RecurringAudienceList, + ) => { + 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.listRecurringAudienceLists + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listRecurringAudienceLists, request), + ); + assert( + ( + client.descriptors.page.listRecurringAudienceLists + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('invokes listRecurringAudienceListsStream with error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listRecurringAudienceLists.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listRecurringAudienceListsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.data.v1alpha.RecurringAudienceList[] = + []; + stream.on( + 'data', + ( + response: protos.google.analytics.data.v1alpha.RecurringAudienceList, + ) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + ( + client.descriptors.page.listRecurringAudienceLists + .createStream as SinonStub + ) + .getCall(0) + .calledWith(client.innerApiCalls.listRecurringAudienceLists, request), + ); + assert( + ( + client.descriptors.page.listRecurringAudienceLists + .createStream as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listRecurringAudienceLists without error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.data.v1alpha.RecurringAudienceList(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.RecurringAudienceList(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.RecurringAudienceList(), + ), + ]; + client.descriptors.page.listRecurringAudienceLists.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.data.v1alpha.IRecurringAudienceList[] = + []; + const iterable = client.listRecurringAudienceListsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listRecurringAudienceLists + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listRecurringAudienceLists + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + + it('uses async iteration with listRecurringAudienceLists with error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.ListRecurringAudienceListsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listRecurringAudienceLists.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listRecurringAudienceListsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.data.v1alpha.IRecurringAudienceList[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listRecurringAudienceLists + .asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + ( + client.descriptors.page.listRecurringAudienceLists + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams, + ), + ); + }); + }); + + describe('listReportTasks', () => { + it('invokes listReportTasks without error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.ListReportTasksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.ListReportTasksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.data.v1alpha.ReportTask(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.ReportTask(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.ReportTask(), + ), + ]; + client.innerApiCalls.listReportTasks = stubSimpleCall(expectedResponse); + const [response] = await client.listReportTasks(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listReportTasks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listReportTasks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listReportTasks without error using callback', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.ListReportTasksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.ListReportTasksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.data.v1alpha.ReportTask(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.ReportTask(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.ReportTask(), + ), + ]; + client.innerApiCalls.listReportTasks = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listReportTasks( + request, + ( + err?: Error | null, + result?: protos.google.analytics.data.v1alpha.IReportTask[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listReportTasks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listReportTasks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listReportTasks with error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.ListReportTasksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.ListReportTasksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listReportTasks = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listReportTasks(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listReportTasks as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listReportTasks as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listReportTasksStream without error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.ListReportTasksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.ListReportTasksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.data.v1alpha.ReportTask(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.ReportTask(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.ReportTask(), + ), + ]; + client.descriptors.page.listReportTasks.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listReportTasksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.data.v1alpha.ReportTask[] = []; + stream.on( + 'data', + (response: protos.google.analytics.data.v1alpha.ReportTask) => { + 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.listReportTasks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listReportTasks, request), + ); + assert( + (client.descriptors.page.listReportTasks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('invokes listReportTasksStream with error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.ListReportTasksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.ListReportTasksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listReportTasks.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listReportTasksStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.data.v1alpha.ReportTask[] = []; + stream.on( + 'data', + (response: protos.google.analytics.data.v1alpha.ReportTask) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listReportTasks.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listReportTasks, request), + ); + assert( + (client.descriptors.page.listReportTasks.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listReportTasks without error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.ListReportTasksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.ListReportTasksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.data.v1alpha.ReportTask(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.ReportTask(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1alpha.ReportTask(), + ), + ]; + client.descriptors.page.listReportTasks.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.data.v1alpha.IReportTask[] = []; + const iterable = client.listReportTasksAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listReportTasks.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listReportTasks.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + + it('uses async iteration with listReportTasks with error', async () => { + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1alpha.ListReportTasksRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1alpha.ListReportTasksRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listReportTasks.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listReportTasksAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.data.v1alpha.IReportTask[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listReportTasks.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listReportTasks.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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + 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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + 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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + 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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + 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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + 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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + 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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + 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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + 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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + 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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + 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 alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + 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('audienceList', async () => { + const fakePath = '/rendered/path/audienceList'; + const expectedParameters = { + property: 'propertyValue', + audience_list: 'audienceListValue', + }; + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.audienceListPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.audienceListPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('audienceListPath', () => { + const result = client.audienceListPath( + 'propertyValue', + 'audienceListValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.audienceListPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromAudienceListName', () => { + const result = client.matchPropertyFromAudienceListName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.audienceListPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAudienceListFromAudienceListName', () => { + const result = client.matchAudienceListFromAudienceListName(fakePath); + assert.strictEqual(result, 'audienceListValue'); + assert( + (client.pathTemplates.audienceListPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('metadata', async () => { + const fakePath = '/rendered/path/metadata'; + const expectedParameters = { + property: 'propertyValue', + }; + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.metadataPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.metadataPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('metadataPath', () => { + const result = client.metadataPath('propertyValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.metadataPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromMetadataName', () => { + const result = client.matchPropertyFromMetadataName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.metadataPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('property', async () => { + const fakePath = '/rendered/path/property'; + const expectedParameters = { + property: 'propertyValue', + }; + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.propertyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.propertyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('propertyPath', () => { + const result = client.propertyPath('propertyValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.propertyPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromPropertyName', () => { + const result = client.matchPropertyFromPropertyName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.propertyPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('propertyQuotasSnapshot', async () => { + const fakePath = '/rendered/path/propertyQuotasSnapshot'; + const expectedParameters = { + property: 'propertyValue', + }; + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.propertyQuotasSnapshotPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.propertyQuotasSnapshotPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('propertyQuotasSnapshotPath', () => { + const result = client.propertyQuotasSnapshotPath('propertyValue'); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.propertyQuotasSnapshotPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromPropertyQuotasSnapshotName', () => { + const result = + client.matchPropertyFromPropertyQuotasSnapshotName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + ( + client.pathTemplates.propertyQuotasSnapshotPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('recurringAudienceList', async () => { + const fakePath = '/rendered/path/recurringAudienceList'; + const expectedParameters = { + property: 'propertyValue', + recurring_audience_list: 'recurringAudienceListValue', + }; + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.recurringAudienceListPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.recurringAudienceListPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('recurringAudienceListPath', () => { + const result = client.recurringAudienceListPath( + 'propertyValue', + 'recurringAudienceListValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.recurringAudienceListPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromRecurringAudienceListName', () => { + const result = + client.matchPropertyFromRecurringAudienceListName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + ( + client.pathTemplates.recurringAudienceListPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchRecurringAudienceListFromRecurringAudienceListName', () => { + const result = + client.matchRecurringAudienceListFromRecurringAudienceListName( + fakePath, + ); + assert.strictEqual(result, 'recurringAudienceListValue'); + assert( + ( + client.pathTemplates.recurringAudienceListPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); + + describe('reportTask', async () => { + const fakePath = '/rendered/path/reportTask'; + const expectedParameters = { + property: 'propertyValue', + report_task: 'reportTaskValue', + }; + const client = + new alphaanalyticsdataModule.v1alpha.AlphaAnalyticsDataClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.reportTaskPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.reportTaskPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('reportTaskPath', () => { + const result = client.reportTaskPath( + 'propertyValue', + 'reportTaskValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.reportTaskPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromReportTaskName', () => { + const result = client.matchPropertyFromReportTaskName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.reportTaskPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchReportTaskFromReportTaskName', () => { + const result = client.matchReportTaskFromReportTaskName(fakePath); + assert.strictEqual(result, 'reportTaskValue'); + assert( + (client.pathTemplates.reportTaskPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-analytics-data/test/gapic_beta_analytics_data_v1beta.ts b/packages/google-analytics-data/test/gapic_beta_analytics_data_v1beta.ts index 3c15d128123a..cea82605a5c8 100644 --- a/packages/google-analytics-data/test/gapic_beta_analytics_data_v1beta.ts +++ b/packages/google-analytics-data/test/gapic_beta_analytics_data_v1beta.ts @@ -19,1986 +19,2639 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as betaanalyticsdataModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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('v1beta.BetaAnalyticsDataClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'analyticsdata.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient(); - 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 = betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient.servicePath; - assert.strictEqual(servicePath, 'analyticsdata.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'analyticsdata.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'analyticsdata.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'analyticsdata.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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'analyticsdata.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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'analyticsdata.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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.betaAnalyticsDataStub, undefined); - await client.initialize(); - assert(client.betaAnalyticsDataStub); - }); - - it('has close method for the initialized client', done => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.betaAnalyticsDataStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.betaAnalyticsDataStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - 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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - 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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'analyticsdata.googleapis.com'); }); - describe('runReport', () => { - it('invokes runReport without error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.RunReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.RunReportRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1beta.RunReportResponse() - ); - client.innerApiCalls.runReport = stubSimpleCall(expectedResponse); - const [response] = await client.runReport(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.runReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has universeDomain', () => { + const client = + new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('invokes runReport without error using callback', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.RunReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.RunReportRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1beta.RunReportResponse() - ); - client.innerApiCalls.runReport = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.runReport( - request, - (err?: Error|null, result?: protos.google.analytics.data.v1beta.IRunReportResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.runReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runReport 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 = + betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient.servicePath; + assert.strictEqual(servicePath, 'analyticsdata.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'analyticsdata.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { universeDomain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'analyticsdata.example.com'); + }); - it('invokes runReport with error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.RunReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.RunReportRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.runReport = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.runReport(request), expectedError); - const actualRequest = (client.innerApiCalls.runReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { universe_domain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'analyticsdata.example.com'); + }); - it('invokes runReport with closed client', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.RunReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.RunReportRequest', ['property']); - request.property = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.runReport(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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'analyticsdata.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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'analyticsdata.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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('runPivotReport', () => { - it('invokes runPivotReport without error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.RunPivotReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.RunPivotReportRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1beta.RunPivotReportResponse() - ); - client.innerApiCalls.runPivotReport = stubSimpleCall(expectedResponse); - const [response] = await client.runPivotReport(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.runPivotReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runPivotReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes runPivotReport without error using callback', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.RunPivotReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.RunPivotReportRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1beta.RunPivotReportResponse() - ); - client.innerApiCalls.runPivotReport = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.runPivotReport( - request, - (err?: Error|null, result?: protos.google.analytics.data.v1beta.IRunPivotReportResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.runPivotReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runPivotReport 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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient(); + assert(client); + }); - it('invokes runPivotReport with error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.RunPivotReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.RunPivotReportRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.runPivotReport = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.runPivotReport(request), expectedError); - const actualRequest = (client.innerApiCalls.runPivotReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runPivotReport 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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + fallback: true, + }, + ); + assert(client); + }); - it('invokes runPivotReport with closed client', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.RunPivotReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.RunPivotReportRequest', ['property']); - request.property = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.runPivotReport(request), expectedError); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.betaAnalyticsDataStub, undefined); + await client.initialize(); + assert(client.betaAnalyticsDataStub); }); - describe('batchRunReports', () => { - it('invokes batchRunReports without error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.BatchRunReportsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.BatchRunReportsRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1beta.BatchRunReportsResponse() - ); - client.innerApiCalls.batchRunReports = stubSimpleCall(expectedResponse); - const [response] = await client.batchRunReports(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchRunReports as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchRunReports 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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + assert(client.betaAnalyticsDataStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes batchRunReports without error using callback', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.BatchRunReportsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.BatchRunReportsRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1beta.BatchRunReportsResponse() - ); - client.innerApiCalls.batchRunReports = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchRunReports( - request, - (err?: Error|null, result?: protos.google.analytics.data.v1beta.IBatchRunReportsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchRunReports as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchRunReports 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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.betaAnalyticsDataStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes batchRunReports with error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.BatchRunReportsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.BatchRunReportsRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchRunReports = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchRunReports(request), expectedError); - const actualRequest = (client.innerApiCalls.batchRunReports as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchRunReports 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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + 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 batchRunReports with closed client', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.BatchRunReportsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.BatchRunReportsRequest', ['property']); - request.property = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchRunReports(request), expectedError); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + 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('runReport', () => { + it('invokes runReport without error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.RunReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.RunReportRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1beta.RunReportResponse(), + ); + client.innerApiCalls.runReport = stubSimpleCall(expectedResponse); + const [response] = await client.runReport(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('batchRunPivotReports', () => { - it('invokes batchRunPivotReports without error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.BatchRunPivotReportsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.BatchRunPivotReportsRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1beta.BatchRunPivotReportsResponse() - ); - client.innerApiCalls.batchRunPivotReports = stubSimpleCall(expectedResponse); - const [response] = await client.batchRunPivotReports(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchRunPivotReports as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchRunPivotReports as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes runReport without error using callback', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.RunReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.RunReportRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1beta.RunReportResponse(), + ); + client.innerApiCalls.runReport = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.runReport( + request, + ( + err?: Error | null, + result?: protos.google.analytics.data.v1beta.IRunReportResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchRunPivotReports without error using callback', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.BatchRunPivotReportsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.BatchRunPivotReportsRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1beta.BatchRunPivotReportsResponse() - ); - client.innerApiCalls.batchRunPivotReports = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchRunPivotReports( - request, - (err?: Error|null, result?: protos.google.analytics.data.v1beta.IBatchRunPivotReportsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchRunPivotReports as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchRunPivotReports as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes runReport with error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.RunReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.RunReportRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.runReport = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.runReport(request), expectedError); + const actualRequest = ( + client.innerApiCalls.runReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchRunPivotReports with error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.BatchRunPivotReportsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.BatchRunPivotReportsRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchRunPivotReports = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchRunPivotReports(request), expectedError); - const actualRequest = (client.innerApiCalls.batchRunPivotReports as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchRunPivotReports as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes runReport with closed client', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.RunReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.RunReportRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.runReport(request), expectedError); + }); + }); + + describe('runPivotReport', () => { + it('invokes runPivotReport without error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.RunPivotReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.RunPivotReportRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1beta.RunPivotReportResponse(), + ); + client.innerApiCalls.runPivotReport = stubSimpleCall(expectedResponse); + const [response] = await client.runPivotReport(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runPivotReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runPivotReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchRunPivotReports with closed client', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.BatchRunPivotReportsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.BatchRunPivotReportsRequest', ['property']); - request.property = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchRunPivotReports(request), expectedError); - }); + it('invokes runPivotReport without error using callback', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.RunPivotReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.RunPivotReportRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1beta.RunPivotReportResponse(), + ); + client.innerApiCalls.runPivotReport = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.runPivotReport( + request, + ( + err?: Error | null, + result?: protos.google.analytics.data.v1beta.IRunPivotReportResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runPivotReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runPivotReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getMetadata', () => { - it('invokes getMetadata without error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.GetMetadataRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.GetMetadataRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1beta.Metadata() - ); - client.innerApiCalls.getMetadata = stubSimpleCall(expectedResponse); - const [response] = await client.getMetadata(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getMetadata as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMetadata as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes runPivotReport with error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.RunPivotReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.RunPivotReportRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.runPivotReport = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.runPivotReport(request), expectedError); + const actualRequest = ( + client.innerApiCalls.runPivotReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runPivotReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getMetadata without error using callback', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.GetMetadataRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.GetMetadataRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1beta.Metadata() - ); - client.innerApiCalls.getMetadata = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getMetadata( - request, - (err?: Error|null, result?: protos.google.analytics.data.v1beta.IMetadata|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getMetadata as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMetadata as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes runPivotReport with closed client', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.RunPivotReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.RunPivotReportRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.runPivotReport(request), expectedError); + }); + }); + + describe('batchRunReports', () => { + it('invokes batchRunReports without error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.BatchRunReportsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.BatchRunReportsRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1beta.BatchRunReportsResponse(), + ); + client.innerApiCalls.batchRunReports = stubSimpleCall(expectedResponse); + const [response] = await client.batchRunReports(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchRunReports as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchRunReports as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getMetadata with error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.GetMetadataRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.GetMetadataRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getMetadata = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getMetadata(request), expectedError); - const actualRequest = (client.innerApiCalls.getMetadata as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getMetadata as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchRunReports without error using callback', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.BatchRunReportsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.BatchRunReportsRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1beta.BatchRunReportsResponse(), + ); + client.innerApiCalls.batchRunReports = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchRunReports( + request, + ( + err?: Error | null, + result?: protos.google.analytics.data.v1beta.IBatchRunReportsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchRunReports as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchRunReports as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getMetadata with closed client', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.GetMetadataRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.GetMetadataRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getMetadata(request), expectedError); - }); + it('invokes batchRunReports with error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.BatchRunReportsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.BatchRunReportsRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchRunReports = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.batchRunReports(request), expectedError); + const actualRequest = ( + client.innerApiCalls.batchRunReports as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchRunReports as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('runRealtimeReport', () => { - it('invokes runRealtimeReport without error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.RunRealtimeReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.RunRealtimeReportRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1beta.RunRealtimeReportResponse() - ); - client.innerApiCalls.runRealtimeReport = stubSimpleCall(expectedResponse); - const [response] = await client.runRealtimeReport(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.runRealtimeReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runRealtimeReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchRunReports with closed client', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.BatchRunReportsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.BatchRunReportsRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.batchRunReports(request), expectedError); + }); + }); + + describe('batchRunPivotReports', () => { + it('invokes batchRunPivotReports without error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.BatchRunPivotReportsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.BatchRunPivotReportsRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1beta.BatchRunPivotReportsResponse(), + ); + client.innerApiCalls.batchRunPivotReports = + stubSimpleCall(expectedResponse); + const [response] = await client.batchRunPivotReports(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchRunPivotReports as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchRunPivotReports as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes runRealtimeReport without error using callback', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.RunRealtimeReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.RunRealtimeReportRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1beta.RunRealtimeReportResponse() - ); - client.innerApiCalls.runRealtimeReport = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.runRealtimeReport( - request, - (err?: Error|null, result?: protos.google.analytics.data.v1beta.IRunRealtimeReportResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.runRealtimeReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runRealtimeReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchRunPivotReports without error using callback', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.BatchRunPivotReportsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.BatchRunPivotReportsRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1beta.BatchRunPivotReportsResponse(), + ); + client.innerApiCalls.batchRunPivotReports = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchRunPivotReports( + request, + ( + err?: Error | null, + result?: protos.google.analytics.data.v1beta.IBatchRunPivotReportsResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchRunPivotReports as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchRunPivotReports as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes runRealtimeReport with error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.RunRealtimeReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.RunRealtimeReportRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.runRealtimeReport = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.runRealtimeReport(request), expectedError); - const actualRequest = (client.innerApiCalls.runRealtimeReport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runRealtimeReport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchRunPivotReports with error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.BatchRunPivotReportsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.BatchRunPivotReportsRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchRunPivotReports = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.batchRunPivotReports(request), expectedError); + const actualRequest = ( + client.innerApiCalls.batchRunPivotReports as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchRunPivotReports as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes runRealtimeReport with closed client', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.RunRealtimeReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.RunRealtimeReportRequest', ['property']); - request.property = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.runRealtimeReport(request), expectedError); - }); + it('invokes batchRunPivotReports with closed client', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.BatchRunPivotReportsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.BatchRunPivotReportsRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.batchRunPivotReports(request), expectedError); + }); + }); + + describe('getMetadata', () => { + it('invokes getMetadata without error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.GetMetadataRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.GetMetadataRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1beta.Metadata(), + ); + client.innerApiCalls.getMetadata = stubSimpleCall(expectedResponse); + const [response] = await client.getMetadata(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getMetadata as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMetadata as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('checkCompatibility', () => { - it('invokes checkCompatibility without error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.CheckCompatibilityRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.CheckCompatibilityRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1beta.CheckCompatibilityResponse() - ); - client.innerApiCalls.checkCompatibility = stubSimpleCall(expectedResponse); - const [response] = await client.checkCompatibility(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.checkCompatibility as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.checkCompatibility as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getMetadata without error using callback', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.GetMetadataRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.GetMetadataRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1beta.Metadata(), + ); + client.innerApiCalls.getMetadata = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getMetadata( + request, + ( + err?: Error | null, + result?: protos.google.analytics.data.v1beta.IMetadata | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getMetadata as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMetadata as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCompatibility without error using callback', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.CheckCompatibilityRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.CheckCompatibilityRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1beta.CheckCompatibilityResponse() - ); - client.innerApiCalls.checkCompatibility = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.checkCompatibility( - request, - (err?: Error|null, result?: protos.google.analytics.data.v1beta.ICheckCompatibilityResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.checkCompatibility as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.checkCompatibility as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getMetadata with error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.GetMetadataRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.GetMetadataRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getMetadata = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getMetadata(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getMetadata as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getMetadata as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCompatibility with error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.CheckCompatibilityRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.CheckCompatibilityRequest', ['property']); - request.property = defaultValue1; - const expectedHeaderRequestParams = `property=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.checkCompatibility = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkCompatibility(request), expectedError); - const actualRequest = (client.innerApiCalls.checkCompatibility as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.checkCompatibility as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getMetadata with closed client', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.GetMetadataRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.GetMetadataRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getMetadata(request), expectedError); + }); + }); + + describe('runRealtimeReport', () => { + it('invokes runRealtimeReport without error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.RunRealtimeReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.RunRealtimeReportRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1beta.RunRealtimeReportResponse(), + ); + client.innerApiCalls.runRealtimeReport = stubSimpleCall(expectedResponse); + const [response] = await client.runRealtimeReport(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runRealtimeReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runRealtimeReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCompatibility with closed client', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.CheckCompatibilityRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.CheckCompatibilityRequest', ['property']); - request.property = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.checkCompatibility(request), expectedError); - }); + it('invokes runRealtimeReport without error using callback', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.RunRealtimeReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.RunRealtimeReportRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1beta.RunRealtimeReportResponse(), + ); + client.innerApiCalls.runRealtimeReport = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.runRealtimeReport( + request, + ( + err?: Error | null, + result?: protos.google.analytics.data.v1beta.IRunRealtimeReportResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runRealtimeReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runRealtimeReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('queryAudienceExport', () => { - it('invokes queryAudienceExport without error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.QueryAudienceExportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.QueryAudienceExportRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1beta.QueryAudienceExportResponse() - ); - client.innerApiCalls.queryAudienceExport = stubSimpleCall(expectedResponse); - const [response] = await client.queryAudienceExport(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.queryAudienceExport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.queryAudienceExport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes runRealtimeReport with error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.RunRealtimeReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.RunRealtimeReportRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.runRealtimeReport = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.runRealtimeReport(request), expectedError); + const actualRequest = ( + client.innerApiCalls.runRealtimeReport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runRealtimeReport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes queryAudienceExport without error using callback', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.QueryAudienceExportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.QueryAudienceExportRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1beta.QueryAudienceExportResponse() - ); - client.innerApiCalls.queryAudienceExport = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.queryAudienceExport( - request, - (err?: Error|null, result?: protos.google.analytics.data.v1beta.IQueryAudienceExportResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.queryAudienceExport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.queryAudienceExport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes runRealtimeReport with closed client', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.RunRealtimeReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.RunRealtimeReportRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.runRealtimeReport(request), expectedError); + }); + }); + + describe('checkCompatibility', () => { + it('invokes checkCompatibility without error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.CheckCompatibilityRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.CheckCompatibilityRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1beta.CheckCompatibilityResponse(), + ); + client.innerApiCalls.checkCompatibility = + stubSimpleCall(expectedResponse); + const [response] = await client.checkCompatibility(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.checkCompatibility as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.checkCompatibility as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes queryAudienceExport with error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.QueryAudienceExportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.QueryAudienceExportRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.queryAudienceExport = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.queryAudienceExport(request), expectedError); - const actualRequest = (client.innerApiCalls.queryAudienceExport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.queryAudienceExport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkCompatibility without error using callback', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.CheckCompatibilityRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.CheckCompatibilityRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1beta.CheckCompatibilityResponse(), + ); + client.innerApiCalls.checkCompatibility = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.checkCompatibility( + request, + ( + err?: Error | null, + result?: protos.google.analytics.data.v1beta.ICheckCompatibilityResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.checkCompatibility as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.checkCompatibility as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes queryAudienceExport with closed client', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.QueryAudienceExportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.QueryAudienceExportRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.queryAudienceExport(request), expectedError); - }); + it('invokes checkCompatibility with error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.CheckCompatibilityRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.CheckCompatibilityRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedHeaderRequestParams = `property=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.checkCompatibility = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.checkCompatibility(request), expectedError); + const actualRequest = ( + client.innerApiCalls.checkCompatibility as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.checkCompatibility as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getAudienceExport', () => { - it('invokes getAudienceExport without error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.GetAudienceExportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.GetAudienceExportRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1beta.AudienceExport() - ); - client.innerApiCalls.getAudienceExport = stubSimpleCall(expectedResponse); - const [response] = await client.getAudienceExport(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAudienceExport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAudienceExport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkCompatibility with closed client', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.CheckCompatibilityRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.CheckCompatibilityRequest', + ['property'], + ); + request.property = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.checkCompatibility(request), expectedError); + }); + }); + + describe('queryAudienceExport', () => { + it('invokes queryAudienceExport without error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.QueryAudienceExportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.QueryAudienceExportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1beta.QueryAudienceExportResponse(), + ); + client.innerApiCalls.queryAudienceExport = + stubSimpleCall(expectedResponse); + const [response] = await client.queryAudienceExport(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.queryAudienceExport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.queryAudienceExport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getAudienceExport without error using callback', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.GetAudienceExportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.GetAudienceExportRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.analytics.data.v1beta.AudienceExport() - ); - client.innerApiCalls.getAudienceExport = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getAudienceExport( - request, - (err?: Error|null, result?: protos.google.analytics.data.v1beta.IAudienceExport|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getAudienceExport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAudienceExport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes queryAudienceExport without error using callback', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.QueryAudienceExportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.QueryAudienceExportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1beta.QueryAudienceExportResponse(), + ); + client.innerApiCalls.queryAudienceExport = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.queryAudienceExport( + request, + ( + err?: Error | null, + result?: protos.google.analytics.data.v1beta.IQueryAudienceExportResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.queryAudienceExport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.queryAudienceExport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getAudienceExport with error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.GetAudienceExportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.GetAudienceExportRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getAudienceExport = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getAudienceExport(request), expectedError); - const actualRequest = (client.innerApiCalls.getAudienceExport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getAudienceExport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes queryAudienceExport with error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.QueryAudienceExportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.QueryAudienceExportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.queryAudienceExport = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.queryAudienceExport(request), expectedError); + const actualRequest = ( + client.innerApiCalls.queryAudienceExport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.queryAudienceExport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getAudienceExport with closed client', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.GetAudienceExportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.GetAudienceExportRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getAudienceExport(request), expectedError); - }); + it('invokes queryAudienceExport with closed client', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.QueryAudienceExportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.QueryAudienceExportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.queryAudienceExport(request), expectedError); + }); + }); + + describe('getAudienceExport', () => { + it('invokes getAudienceExport without error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.GetAudienceExportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.GetAudienceExportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1beta.AudienceExport(), + ); + client.innerApiCalls.getAudienceExport = stubSimpleCall(expectedResponse); + const [response] = await client.getAudienceExport(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAudienceExport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAudienceExport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createAudienceExport', () => { - it('invokes createAudienceExport without error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.CreateAudienceExportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.CreateAudienceExportRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createAudienceExport = stubLongRunningCall(expectedResponse); - const [operation] = await client.createAudienceExport(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createAudienceExport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createAudienceExport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getAudienceExport without error using callback', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.GetAudienceExportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.GetAudienceExportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.analytics.data.v1beta.AudienceExport(), + ); + client.innerApiCalls.getAudienceExport = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getAudienceExport( + request, + ( + err?: Error | null, + result?: protos.google.analytics.data.v1beta.IAudienceExport | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getAudienceExport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAudienceExport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createAudienceExport without error using callback', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.CreateAudienceExportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.CreateAudienceExportRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createAudienceExport = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createAudienceExport( - 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.createAudienceExport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createAudienceExport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getAudienceExport with error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.GetAudienceExportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.GetAudienceExportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getAudienceExport = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getAudienceExport(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getAudienceExport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getAudienceExport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createAudienceExport with call error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.CreateAudienceExportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.CreateAudienceExportRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createAudienceExport = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.createAudienceExport(request), expectedError); - const actualRequest = (client.innerApiCalls.createAudienceExport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createAudienceExport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getAudienceExport with closed client', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.GetAudienceExportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.GetAudienceExportRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getAudienceExport(request), expectedError); + }); + }); + + describe('createAudienceExport', () => { + it('invokes createAudienceExport without error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.CreateAudienceExportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.CreateAudienceExportRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createAudienceExport = + stubLongRunningCall(expectedResponse); + const [operation] = await client.createAudienceExport(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createAudienceExport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createAudienceExport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createAudienceExport with LRO error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.CreateAudienceExportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.CreateAudienceExportRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createAudienceExport = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.createAudienceExport(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.createAudienceExport as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createAudienceExport as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createAudienceExport without error using callback', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.CreateAudienceExportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.CreateAudienceExportRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createAudienceExport = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createAudienceExport( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.analytics.data.v1beta.IAudienceExport, + protos.google.analytics.data.v1beta.IAudienceExportMetadata + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.analytics.data.v1beta.IAudienceExport, + protos.google.analytics.data.v1beta.IAudienceExportMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createAudienceExport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createAudienceExport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateAudienceExportProgress without error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - 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.checkCreateAudienceExportProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes createAudienceExport with call error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.CreateAudienceExportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.CreateAudienceExportRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createAudienceExport = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.createAudienceExport(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createAudienceExport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createAudienceExport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateAudienceExportProgress with error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); + it('invokes createAudienceExport with LRO error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.CreateAudienceExportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.CreateAudienceExportRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createAudienceExport = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.createAudienceExport(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.createAudienceExport as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createAudienceExport as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkCreateAudienceExportProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes checkCreateAudienceExportProgress without error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + 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.checkCreateAudienceExportProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); }); - describe('listAudienceExports', () => { - it('invokes listAudienceExports without error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.ListAudienceExportsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.ListAudienceExportsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.data.v1beta.AudienceExport()), - generateSampleMessage(new protos.google.analytics.data.v1beta.AudienceExport()), - generateSampleMessage(new protos.google.analytics.data.v1beta.AudienceExport()), - ]; - client.innerApiCalls.listAudienceExports = stubSimpleCall(expectedResponse); - const [response] = await client.listAudienceExports(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listAudienceExports as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listAudienceExports as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkCreateAudienceExportProgress with error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + 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.checkCreateAudienceExportProgress(''), + expectedError, + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('listAudienceExports', () => { + it('invokes listAudienceExports without error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.ListAudienceExportsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.ListAudienceExportsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.data.v1beta.AudienceExport(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1beta.AudienceExport(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1beta.AudienceExport(), + ), + ]; + client.innerApiCalls.listAudienceExports = + stubSimpleCall(expectedResponse); + const [response] = await client.listAudienceExports(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listAudienceExports as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listAudienceExports as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listAudienceExports without error using callback', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.ListAudienceExportsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.ListAudienceExportsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.data.v1beta.AudienceExport()), - generateSampleMessage(new protos.google.analytics.data.v1beta.AudienceExport()), - generateSampleMessage(new protos.google.analytics.data.v1beta.AudienceExport()), - ]; - client.innerApiCalls.listAudienceExports = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listAudienceExports( - request, - (err?: Error|null, result?: protos.google.analytics.data.v1beta.IAudienceExport[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listAudienceExports as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listAudienceExports as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listAudienceExports without error using callback', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.ListAudienceExportsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.ListAudienceExportsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.data.v1beta.AudienceExport(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1beta.AudienceExport(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1beta.AudienceExport(), + ), + ]; + client.innerApiCalls.listAudienceExports = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listAudienceExports( + request, + ( + err?: Error | null, + result?: + | protos.google.analytics.data.v1beta.IAudienceExport[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listAudienceExports as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listAudienceExports as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listAudienceExports with error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.ListAudienceExportsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.ListAudienceExportsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listAudienceExports = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listAudienceExports(request), expectedError); - const actualRequest = (client.innerApiCalls.listAudienceExports as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listAudienceExports as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listAudienceExports with error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.ListAudienceExportsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.ListAudienceExportsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listAudienceExports = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listAudienceExports(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listAudienceExports as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listAudienceExports as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listAudienceExportsStream without error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.ListAudienceExportsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.ListAudienceExportsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.data.v1beta.AudienceExport()), - generateSampleMessage(new protos.google.analytics.data.v1beta.AudienceExport()), - generateSampleMessage(new protos.google.analytics.data.v1beta.AudienceExport()), - ]; - client.descriptors.page.listAudienceExports.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listAudienceExportsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.data.v1beta.AudienceExport[] = []; - stream.on('data', (response: protos.google.analytics.data.v1beta.AudienceExport) => { - 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.listAudienceExports.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listAudienceExports, request)); - assert( - (client.descriptors.page.listAudienceExports.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listAudienceExportsStream without error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.ListAudienceExportsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.ListAudienceExportsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.data.v1beta.AudienceExport(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1beta.AudienceExport(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1beta.AudienceExport(), + ), + ]; + client.descriptors.page.listAudienceExports.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listAudienceExportsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.data.v1beta.AudienceExport[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.data.v1beta.AudienceExport) => { + 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.listAudienceExports.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listAudienceExports, request), + ); + assert( + (client.descriptors.page.listAudienceExports.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listAudienceExportsStream with error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.ListAudienceExportsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.ListAudienceExportsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listAudienceExports.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listAudienceExportsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.analytics.data.v1beta.AudienceExport[] = []; - stream.on('data', (response: protos.google.analytics.data.v1beta.AudienceExport) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listAudienceExports.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listAudienceExports, request)); - assert( - (client.descriptors.page.listAudienceExports.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listAudienceExportsStream with error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.ListAudienceExportsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.ListAudienceExportsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listAudienceExports.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listAudienceExportsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.analytics.data.v1beta.AudienceExport[] = + []; + stream.on( + 'data', + (response: protos.google.analytics.data.v1beta.AudienceExport) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listAudienceExports.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listAudienceExports, request), + ); + assert( + (client.descriptors.page.listAudienceExports.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listAudienceExports without error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.ListAudienceExportsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.ListAudienceExportsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.analytics.data.v1beta.AudienceExport()), - generateSampleMessage(new protos.google.analytics.data.v1beta.AudienceExport()), - generateSampleMessage(new protos.google.analytics.data.v1beta.AudienceExport()), - ]; - client.descriptors.page.listAudienceExports.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.analytics.data.v1beta.IAudienceExport[] = []; - const iterable = client.listAudienceExportsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listAudienceExports.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listAudienceExports.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listAudienceExports without error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.ListAudienceExportsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.ListAudienceExportsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.analytics.data.v1beta.AudienceExport(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1beta.AudienceExport(), + ), + generateSampleMessage( + new protos.google.analytics.data.v1beta.AudienceExport(), + ), + ]; + client.descriptors.page.listAudienceExports.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.analytics.data.v1beta.IAudienceExport[] = + []; + const iterable = client.listAudienceExportsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listAudienceExports.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listAudienceExports.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listAudienceExports with error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.analytics.data.v1beta.ListAudienceExportsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.analytics.data.v1beta.ListAudienceExportsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listAudienceExports.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listAudienceExportsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.analytics.data.v1beta.IAudienceExport[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listAudienceExports.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listAudienceExports.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listAudienceExports with error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.analytics.data.v1beta.ListAudienceExportsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.analytics.data.v1beta.ListAudienceExportsRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listAudienceExports.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listAudienceExportsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.analytics.data.v1beta.IAudienceExport[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listAudienceExports.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listAudienceExports.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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - 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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - 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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - 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('getOperation', () => { + it('invokes getOperation without error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + 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('cancelOperation', () => { - it('invokes cancelOperation without error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - 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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - 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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - 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)); - }); + it('invokes getOperation without error using callback', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + 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)); }); - describe('deleteOperation', () => { - it('invokes deleteOperation without error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - 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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - 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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - 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 getOperation with error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + 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('listOperationsAsync', () => { - it('uses async iteration with listOperations without error', async () => { - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - 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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - 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('cancelOperation', () => { + it('invokes cancelOperation without error', async () => { + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + 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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + 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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + 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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + 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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + 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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + 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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + 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 betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + 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('audienceExport', async () => { + const fakePath = '/rendered/path/audienceExport'; + const expectedParameters = { + property: 'propertyValue', + audience_export: 'audienceExportValue', + }; + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.audienceExportPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.audienceExportPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('audienceExportPath', () => { + const result = client.audienceExportPath( + 'propertyValue', + 'audienceExportValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.audienceExportPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromAudienceExportName', () => { + const result = client.matchPropertyFromAudienceExportName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.audienceExportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchAudienceExportFromAudienceExportName', () => { + const result = + client.matchAudienceExportFromAudienceExportName(fakePath); + assert.strictEqual(result, 'audienceExportValue'); + assert( + (client.pathTemplates.audienceExportPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); - describe('Path templates', () => { - - describe('audienceExport', async () => { - const fakePath = "/rendered/path/audienceExport"; - const expectedParameters = { - property: "propertyValue", - audience_export: "audienceExportValue", - }; - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.audienceExportPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.audienceExportPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('audienceExportPath', () => { - const result = client.audienceExportPath("propertyValue", "audienceExportValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.audienceExportPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromAudienceExportName', () => { - const result = client.matchPropertyFromAudienceExportName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.audienceExportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchAudienceExportFromAudienceExportName', () => { - const result = client.matchAudienceExportFromAudienceExportName(fakePath); - assert.strictEqual(result, "audienceExportValue"); - assert((client.pathTemplates.audienceExportPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('metadata', async () => { - const fakePath = "/rendered/path/metadata"; - const expectedParameters = { - property: "propertyValue", - }; - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.metadataPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.metadataPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('metadataPath', () => { - const result = client.metadataPath("propertyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.metadataPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchPropertyFromMetadataName', () => { - const result = client.matchPropertyFromMetadataName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.metadataPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('property', async () => { - const fakePath = "/rendered/path/property"; - const expectedParameters = { - property: "propertyValue", - }; - const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.propertyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.propertyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('propertyPath', () => { - const result = client.propertyPath("propertyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.propertyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); + describe('metadata', async () => { + const fakePath = '/rendered/path/metadata'; + const expectedParameters = { + property: 'propertyValue', + }; + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.metadataPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.metadataPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('metadataPath', () => { + const result = client.metadataPath('propertyValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.metadataPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromMetadataName', () => { + const result = client.matchPropertyFromMetadataName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.metadataPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - it('matchPropertyFromPropertyName', () => { - const result = client.matchPropertyFromPropertyName(fakePath); - assert.strictEqual(result, "propertyValue"); - assert((client.pathTemplates.propertyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('property', async () => { + const fakePath = '/rendered/path/property'; + const expectedParameters = { + property: 'propertyValue', + }; + const client = new betaanalyticsdataModule.v1beta.BetaAnalyticsDataClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.propertyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.propertyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('propertyPath', () => { + const result = client.propertyPath('propertyValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.propertyPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchPropertyFromPropertyName', () => { + const result = client.matchPropertyFromPropertyName(fakePath); + assert.strictEqual(result, 'propertyValue'); + assert( + (client.pathTemplates.propertyPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-api-apikeys/.eslintignore b/packages/google-api-apikeys/.eslintignore new file mode 100644 index 000000000000..cfc348ec4d11 --- /dev/null +++ b/packages/google-api-apikeys/.eslintignore @@ -0,0 +1,7 @@ +**/node_modules +**/.coverage +build/ +docs/ +protos/ +system-test/ +samples/generated/ diff --git a/packages/google-api-apikeys/.eslintrc.json b/packages/google-api-apikeys/.eslintrc.json new file mode 100644 index 000000000000..3e8d97ccb390 --- /dev/null +++ b/packages/google-api-apikeys/.eslintrc.json @@ -0,0 +1,4 @@ +{ + "extends": "./node_modules/gts", + "root": true +} diff --git a/packages/google-api-apikeys/README.md b/packages/google-api-apikeys/README.md index 341dc118404d..9856ac6582d8 100644 --- a/packages/google-api-apikeys/README.md +++ b/packages/google-api-apikeys/README.md @@ -100,7 +100,7 @@ More Information: [Google Cloud Platform Launch Stages][launch_stages] ## Contributing -Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-api-apikeys/CONTRIBUTING.md). +Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/google-cloud-node/blob/main/CONTRIBUTING.md). Please note that this `README.md` and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`) @@ -110,7 +110,7 @@ are generated from a central template. Apache Version 2.0 -See [LICENSE](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-api-apikeys/LICENSE) +See [LICENSE](https://github.com/googleapis/google-cloud-node/blob/main/LICENSE) [shell_img]: https://gstatic.com/cloudssh/images/open-btn.png [projects]: https://console.cloud.google.com/project diff --git a/packages/google-api-apikeys/protos/protos.d.ts b/packages/google-api-apikeys/protos/protos.d.ts index 20e600329464..a85459408ac4 100644 --- a/packages/google-api-apikeys/protos/protos.d.ts +++ b/packages/google-api-apikeys/protos/protos.d.ts @@ -2843,6 +2843,9 @@ export namespace google { /** CommonLanguageSettings destinations */ destinations?: (google.api.ClientLibraryDestination[]|null); + + /** CommonLanguageSettings selectiveGapicGeneration */ + selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); } /** Represents a CommonLanguageSettings. */ @@ -2860,6 +2863,9 @@ export namespace google { /** CommonLanguageSettings destinations. */ public destinations: google.api.ClientLibraryDestination[]; + /** CommonLanguageSettings selectiveGapicGeneration. */ + public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + /** * Creates a new CommonLanguageSettings instance using the specified properties. * @param [properties] Properties to set @@ -3560,6 +3566,9 @@ export namespace google { /** PythonSettings common */ common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures */ + experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); } /** Represents a PythonSettings. */ @@ -3574,6 +3583,9 @@ export namespace google { /** PythonSettings common. */ public common?: (google.api.ICommonLanguageSettings|null); + /** PythonSettings experimentalFeatures. */ + public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + /** * Creates a new PythonSettings instance using the specified properties. * @param [properties] Properties to set @@ -3652,6 +3664,118 @@ 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); + + /** ExperimentalFeatures unversionedPackageDisabled */ + unversionedPackageDisabled?: (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; + + /** ExperimentalFeatures unversionedPackageDisabled. */ + public unversionedPackageDisabled: boolean; + + /** + * Creates a new ExperimentalFeatures instance using the specified properties. + * @param [properties] Properties to set + * @returns ExperimentalFeatures instance + */ + public static create(properties?: google.api.PythonSettings.IExperimentalFeatures): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Encodes the specified ExperimentalFeatures message. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @param message ExperimentalFeatures message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.PythonSettings.IExperimentalFeatures, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExperimentalFeatures message, length delimited. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @param message ExperimentalFeatures message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.PythonSettings.IExperimentalFeatures, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Verifies an ExperimentalFeatures message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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 { @@ -3978,6 +4102,9 @@ export namespace google { /** GoSettings common */ common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); } /** Represents a GoSettings. */ @@ -3992,6 +4119,9 @@ export namespace google { /** GoSettings common. */ public common?: (google.api.ICommonLanguageSettings|null); + /** GoSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + /** * Creates a new GoSettings instance using the specified properties. * @param [properties] Properties to set @@ -4316,6 +4446,109 @@ export namespace google { PACKAGE_MANAGER = 20 } + /** 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 new SelectiveGapicGeneration instance using the specified properties. + * @param [properties] Properties to set + * @returns SelectiveGapicGeneration instance + */ + public static create(properties?: google.api.ISelectiveGapicGeneration): google.api.SelectiveGapicGeneration; + + /** + * Encodes the specified SelectiveGapicGeneration message. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @param message SelectiveGapicGeneration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.ISelectiveGapicGeneration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SelectiveGapicGeneration message, length delimited. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @param message SelectiveGapicGeneration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.ISelectiveGapicGeneration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.SelectiveGapicGeneration; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.SelectiveGapicGeneration; + + /** + * Verifies a SelectiveGapicGeneration message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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. */ enum LaunchStage { LAUNCH_STAGE_UNSPECIFIED = 0, @@ -4432,6 +4665,7 @@ export namespace google { /** Edition enum. */ enum Edition { EDITION_UNKNOWN = 0, + EDITION_LEGACY = 900, EDITION_PROTO2 = 998, EDITION_PROTO3 = 999, EDITION_2023 = 1000, @@ -4462,6 +4696,9 @@ export namespace google { /** FileDescriptorProto weakDependency */ weakDependency?: (number[]|null); + /** FileDescriptorProto optionDependency */ + optionDependency?: (string[]|null); + /** FileDescriptorProto messageType */ messageType?: (google.protobuf.IDescriptorProto[]|null); @@ -4511,6 +4748,9 @@ export namespace google { /** FileDescriptorProto weakDependency. */ public weakDependency: number[]; + /** FileDescriptorProto optionDependency. */ + public optionDependency: string[]; + /** FileDescriptorProto messageType. */ public messageType: google.protobuf.IDescriptorProto[]; @@ -4645,6 +4885,9 @@ export namespace google { /** DescriptorProto reservedName */ reservedName?: (string[]|null); + + /** DescriptorProto visibility */ + visibility?: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility|null); } /** Represents a DescriptorProto. */ @@ -4686,6 +4929,9 @@ export namespace google { /** DescriptorProto reservedName. */ public reservedName: string[]; + /** DescriptorProto visibility. */ + public visibility: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility); + /** * Creates a new DescriptorProto instance using the specified properties. * @param [properties] Properties to set @@ -5533,6 +5779,9 @@ export namespace google { /** EnumDescriptorProto reservedName */ reservedName?: (string[]|null); + + /** EnumDescriptorProto visibility */ + visibility?: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility|null); } /** Represents an EnumDescriptorProto. */ @@ -5559,6 +5808,9 @@ export namespace google { /** EnumDescriptorProto reservedName. */ public reservedName: string[]; + /** EnumDescriptorProto visibility. */ + public visibility: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility); + /** * Creates a new EnumDescriptorProto instance using the specified properties. * @param [properties] Properties to set @@ -6493,6 +6745,9 @@ 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); @@ -6548,6 +6803,9 @@ 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[]; @@ -6768,6 +7026,121 @@ export namespace google { */ public static getTypeUrl(typeUrlPrefix?: string): string; } + + /** Properties of a FeatureSupport. */ + interface IFeatureSupport { + + /** FeatureSupport editionIntroduced */ + editionIntroduced?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + + /** FeatureSupport editionDeprecated */ + editionDeprecated?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + + /** FeatureSupport deprecationWarning */ + deprecationWarning?: (string|null); + + /** FeatureSupport editionRemoved */ + editionRemoved?: (google.protobuf.Edition|keyof typeof 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|keyof typeof google.protobuf.Edition); + + /** FeatureSupport editionDeprecated. */ + public editionDeprecated: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** FeatureSupport deprecationWarning. */ + public deprecationWarning: string; + + /** FeatureSupport editionRemoved. */ + public editionRemoved: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** + * Creates a new FeatureSupport instance using the specified properties. + * @param [properties] Properties to set + * @returns FeatureSupport instance + */ + public static create(properties?: google.protobuf.FieldOptions.IFeatureSupport): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Encodes the specified FeatureSupport message. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @param message FeatureSupport message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.FieldOptions.IFeatureSupport, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FeatureSupport message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @param message FeatureSupport message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.FieldOptions.IFeatureSupport, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Verifies a FeatureSupport message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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. */ @@ -7006,6 +7379,9 @@ export namespace google { /** EnumValueOptions debugRedact */ debugRedact?: (boolean|null); + /** EnumValueOptions featureSupport */ + featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); + /** EnumValueOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } @@ -7028,6 +7404,9 @@ export namespace google { /** EnumValueOptions debugRedact. */ public debugRedact: boolean; + /** EnumValueOptions featureSupport. */ + public featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); + /** EnumValueOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -7620,6 +7999,12 @@ export namespace google { /** FeatureSet jsonFormat */ jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|keyof typeof google.protobuf.FeatureSet.JsonFormat|null); + + /** FeatureSet enforceNamingStyle */ + enforceNamingStyle?: (google.protobuf.FeatureSet.EnforceNamingStyle|keyof typeof google.protobuf.FeatureSet.EnforceNamingStyle|null); + + /** FeatureSet defaultSymbolVisibility */ + defaultSymbolVisibility?: (google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|keyof typeof google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|null); } /** Represents a FeatureSet. */ @@ -7649,6 +8034,12 @@ export namespace google { /** FeatureSet jsonFormat. */ public jsonFormat: (google.protobuf.FeatureSet.JsonFormat|keyof typeof google.protobuf.FeatureSet.JsonFormat); + /** FeatureSet enforceNamingStyle. */ + public enforceNamingStyle: (google.protobuf.FeatureSet.EnforceNamingStyle|keyof typeof google.protobuf.FeatureSet.EnforceNamingStyle); + + /** FeatureSet defaultSymbolVisibility. */ + public defaultSymbolVisibility: (google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|keyof typeof google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility); + /** * Creates a new FeatureSet instance using the specified properties. * @param [properties] Properties to set @@ -7771,6 +8162,116 @@ export namespace google { ALLOW = 1, LEGACY_BEST_EFFORT = 2 } + + /** EnforceNamingStyle enum. */ + enum EnforceNamingStyle { + ENFORCE_NAMING_STYLE_UNKNOWN = 0, + STYLE2024 = 1, + STYLE_LEGACY = 2 + } + + /** Properties of a VisibilityFeature. */ + interface IVisibilityFeature { + } + + /** Represents a VisibilityFeature. */ + class VisibilityFeature implements IVisibilityFeature { + + /** + * Constructs a new VisibilityFeature. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FeatureSet.IVisibilityFeature); + + /** + * Creates a new VisibilityFeature instance using the specified properties. + * @param [properties] Properties to set + * @returns VisibilityFeature instance + */ + public static create(properties?: google.protobuf.FeatureSet.IVisibilityFeature): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Encodes the specified VisibilityFeature message. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @param message VisibilityFeature message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.FeatureSet.IVisibilityFeature, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified VisibilityFeature message, length delimited. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @param message VisibilityFeature message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.FeatureSet.IVisibilityFeature, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Verifies a VisibilityFeature message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a VisibilityFeature message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns VisibilityFeature + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Creates a plain object from a VisibilityFeature message. Also converts values to other types if specified. + * @param message VisibilityFeature + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet.VisibilityFeature, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this VisibilityFeature to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for VisibilityFeature + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace VisibilityFeature { + + /** DefaultSymbolVisibility enum. */ + enum DefaultSymbolVisibility { + DEFAULT_SYMBOL_VISIBILITY_UNKNOWN = 0, + EXPORT_ALL = 1, + EXPORT_TOP_LEVEL = 2, + LOCAL_ALL = 3, + STRICT = 4 + } + } } /** Properties of a FeatureSetDefaults. */ @@ -7890,8 +8391,11 @@ export namespace google { /** FeatureSetEditionDefault edition */ edition?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); - /** FeatureSetEditionDefault features */ - features?: (google.protobuf.IFeatureSet|null); + /** FeatureSetEditionDefault overridableFeatures */ + overridableFeatures?: (google.protobuf.IFeatureSet|null); + + /** FeatureSetEditionDefault fixedFeatures */ + fixedFeatures?: (google.protobuf.IFeatureSet|null); } /** Represents a FeatureSetEditionDefault. */ @@ -7906,8 +8410,11 @@ export namespace google { /** FeatureSetEditionDefault edition. */ public edition: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); - /** FeatureSetEditionDefault features. */ - public features?: (google.protobuf.IFeatureSet|null); + /** FeatureSetEditionDefault overridableFeatures. */ + public overridableFeatures?: (google.protobuf.IFeatureSet|null); + + /** FeatureSetEditionDefault fixedFeatures. */ + public fixedFeatures?: (google.protobuf.IFeatureSet|null); /** * Creates a new FeatureSetEditionDefault instance using the specified properties. @@ -8440,6 +8947,13 @@ export namespace google { } } + /** SymbolVisibility enum. */ + enum SymbolVisibility { + VISIBILITY_UNSET = 0, + VISIBILITY_LOCAL = 1, + VISIBILITY_EXPORT = 2 + } + /** Properties of a Timestamp. */ interface ITimestamp { diff --git a/packages/google-api-apikeys/protos/protos.js b/packages/google-api-apikeys/protos/protos.js index a8f0ad2fab36..424d7a5f1635 100644 --- a/packages/google-api-apikeys/protos/protos.js +++ b/packages/google-api-apikeys/protos/protos.js @@ -6779,6 +6779,7 @@ * @interface ICommonLanguageSettings * @property {string|null} [referenceDocsUri] CommonLanguageSettings referenceDocsUri * @property {Array.|null} [destinations] CommonLanguageSettings destinations + * @property {google.api.ISelectiveGapicGeneration|null} [selectiveGapicGeneration] CommonLanguageSettings selectiveGapicGeneration */ /** @@ -6813,6 +6814,14 @@ */ 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 new CommonLanguageSettings instance using the specified properties. * @function create @@ -6845,6 +6854,8 @@ writer.int32(message.destinations[i]); writer.ldelim(); } + if (message.selectiveGapicGeneration != null && Object.hasOwnProperty.call(message, "selectiveGapicGeneration")) + $root.google.api.SelectiveGapicGeneration.encode(message.selectiveGapicGeneration, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); return writer; }; @@ -6896,6 +6907,10 @@ message.destinations.push(reader.int32()); break; } + case 3: { + message.selectiveGapicGeneration = $root.google.api.SelectiveGapicGeneration.decode(reader, reader.uint32()); + break; + } default: reader.skipType(tag & 7); break; @@ -6947,6 +6962,11 @@ break; } } + if (message.selectiveGapicGeneration != null && message.hasOwnProperty("selectiveGapicGeneration")) { + var error = $root.google.api.SelectiveGapicGeneration.verify(message.selectiveGapicGeneration); + if (error) + return "selectiveGapicGeneration." + error; + } return null; }; @@ -6989,6 +7009,11 @@ 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; }; @@ -7007,8 +7032,10 @@ 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) { @@ -7016,6 +7043,8 @@ 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; }; @@ -8838,6 +8867,7 @@ * @memberof google.api * @interface IPythonSettings * @property {google.api.ICommonLanguageSettings|null} [common] PythonSettings common + * @property {google.api.PythonSettings.IExperimentalFeatures|null} [experimentalFeatures] PythonSettings experimentalFeatures */ /** @@ -8863,6 +8893,14 @@ */ 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 new PythonSettings instance using the specified properties. * @function create @@ -8889,6 +8927,8 @@ writer = $Writer.create(); if (message.common != null && Object.hasOwnProperty.call(message, "common")) $root.google.api.CommonLanguageSettings.encode(message.common, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.experimentalFeatures != null && Object.hasOwnProperty.call(message, "experimentalFeatures")) + $root.google.api.PythonSettings.ExperimentalFeatures.encode(message.experimentalFeatures, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); return writer; }; @@ -8929,6 +8969,10 @@ message.common = $root.google.api.CommonLanguageSettings.decode(reader, reader.uint32()); break; } + case 2: { + message.experimentalFeatures = $root.google.api.PythonSettings.ExperimentalFeatures.decode(reader, reader.uint32()); + break; + } default: reader.skipType(tag & 7); break; @@ -8969,6 +9013,11 @@ if (error) return "common." + error; } + if (message.experimentalFeatures != null && message.hasOwnProperty("experimentalFeatures")) { + var error = $root.google.api.PythonSettings.ExperimentalFeatures.verify(message.experimentalFeatures); + if (error) + return "experimentalFeatures." + error; + } return null; }; @@ -8989,6 +9038,11 @@ 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; }; @@ -9005,10 +9059,14 @@ 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; }; @@ -9038,6 +9096,258 @@ 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 + * @property {boolean|null} [unversionedPackageDisabled] ExperimentalFeatures unversionedPackageDisabled + */ + + /** + * 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; + + /** + * ExperimentalFeatures unversionedPackageDisabled. + * @member {boolean} unversionedPackageDisabled + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @instance + */ + ExperimentalFeatures.prototype.unversionedPackageDisabled = false; + + /** + * Creates a new ExperimentalFeatures instance using the specified properties. + * @function create + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures=} [properties] Properties to set + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures instance + */ + ExperimentalFeatures.create = function create(properties) { + return new ExperimentalFeatures(properties); + }; + + /** + * Encodes the specified ExperimentalFeatures message. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @function encode + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures} message ExperimentalFeatures message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExperimentalFeatures.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.restAsyncIoEnabled != null && Object.hasOwnProperty.call(message, "restAsyncIoEnabled")) + writer.uint32(/* id 1, wireType 0 =*/8).bool(message.restAsyncIoEnabled); + if (message.protobufPythonicTypesEnabled != null && Object.hasOwnProperty.call(message, "protobufPythonicTypesEnabled")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.protobufPythonicTypesEnabled); + if (message.unversionedPackageDisabled != null && Object.hasOwnProperty.call(message, "unversionedPackageDisabled")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.unversionedPackageDisabled); + return writer; + }; + + /** + * Encodes the specified ExperimentalFeatures message, length delimited. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures} message ExperimentalFeatures message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExperimentalFeatures.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer. + * @function decode + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExperimentalFeatures.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.PythonSettings.ExperimentalFeatures(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.restAsyncIoEnabled = reader.bool(); + break; + } + case 2: { + message.protobufPythonicTypesEnabled = reader.bool(); + break; + } + case 3: { + message.unversionedPackageDisabled = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExperimentalFeatures.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ExperimentalFeatures message. + * @function verify + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExperimentalFeatures.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.restAsyncIoEnabled != null && message.hasOwnProperty("restAsyncIoEnabled")) + if (typeof message.restAsyncIoEnabled !== "boolean") + return "restAsyncIoEnabled: boolean expected"; + if (message.protobufPythonicTypesEnabled != null && message.hasOwnProperty("protobufPythonicTypesEnabled")) + if (typeof message.protobufPythonicTypesEnabled !== "boolean") + return "protobufPythonicTypesEnabled: boolean expected"; + if (message.unversionedPackageDisabled != null && message.hasOwnProperty("unversionedPackageDisabled")) + if (typeof message.unversionedPackageDisabled !== "boolean") + return "unversionedPackageDisabled: boolean expected"; + return null; + }; + + /** + * 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); + if (object.unversionedPackageDisabled != null) + message.unversionedPackageDisabled = Boolean(object.unversionedPackageDisabled); + 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; + object.unversionedPackageDisabled = false; + } + if (message.restAsyncIoEnabled != null && message.hasOwnProperty("restAsyncIoEnabled")) + object.restAsyncIoEnabled = message.restAsyncIoEnabled; + if (message.protobufPythonicTypesEnabled != null && message.hasOwnProperty("protobufPythonicTypesEnabled")) + object.protobufPythonicTypesEnabled = message.protobufPythonicTypesEnabled; + if (message.unversionedPackageDisabled != null && message.hasOwnProperty("unversionedPackageDisabled")) + object.unversionedPackageDisabled = message.unversionedPackageDisabled; + 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; })(); @@ -9914,6 +10224,7 @@ * @memberof google.api * @interface IGoSettings * @property {google.api.ICommonLanguageSettings|null} [common] GoSettings common + * @property {Object.|null} [renamedServices] GoSettings renamedServices */ /** @@ -9925,6 +10236,7 @@ * @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) @@ -9939,6 +10251,14 @@ */ GoSettings.prototype.common = null; + /** + * GoSettings renamedServices. + * @member {Object.} renamedServices + * @memberof google.api.GoSettings + * @instance + */ + GoSettings.prototype.renamedServices = $util.emptyObject; + /** * Creates a new GoSettings instance using the specified properties. * @function create @@ -9965,6 +10285,9 @@ writer = $Writer.create(); if (message.common != null && Object.hasOwnProperty.call(message, "common")) $root.google.api.CommonLanguageSettings.encode(message.common, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.renamedServices != null && Object.hasOwnProperty.call(message, "renamedServices")) + for (var keys = Object.keys(message.renamedServices), i = 0; i < keys.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.renamedServices[keys[i]]).ldelim(); return writer; }; @@ -9995,7 +10318,7 @@ GoSettings.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.GoSettings(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.GoSettings(), key, value; while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -10005,6 +10328,29 @@ message.common = $root.google.api.CommonLanguageSettings.decode(reader, reader.uint32()); break; } + case 2: { + if (message.renamedServices === $util.emptyObject) + message.renamedServices = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.renamedServices[key] = value; + break; + } default: reader.skipType(tag & 7); break; @@ -10045,6 +10391,14 @@ if (error) return "common." + error; } + if (message.renamedServices != null && message.hasOwnProperty("renamedServices")) { + if (!$util.isObject(message.renamedServices)) + return "renamedServices: object expected"; + var key = Object.keys(message.renamedServices); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.renamedServices[key[i]])) + return "renamedServices: string{k:string} expected"; + } return null; }; @@ -10065,6 +10419,13 @@ 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; }; @@ -10081,10 +10442,18 @@ 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; }; @@ -10723,29 +11092,274 @@ return values; })(); - /** - * LaunchStage enum. - * @name google.api.LaunchStage - * @enum {number} - * @property {number} LAUNCH_STAGE_UNSPECIFIED=0 LAUNCH_STAGE_UNSPECIFIED value - * @property {number} UNIMPLEMENTED=6 UNIMPLEMENTED value - * @property {number} PRELAUNCH=7 PRELAUNCH value - * @property {number} EARLY_ACCESS=1 EARLY_ACCESS value - * @property {number} ALPHA=2 ALPHA value - * @property {number} BETA=3 BETA value - * @property {number} GA=4 GA value - * @property {number} DEPRECATED=5 DEPRECATED value - */ - api.LaunchStage = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "LAUNCH_STAGE_UNSPECIFIED"] = 0; - values[valuesById[6] = "UNIMPLEMENTED"] = 6; - values[valuesById[7] = "PRELAUNCH"] = 7; - values[valuesById[1] = "EARLY_ACCESS"] = 1; - values[valuesById[2] = "ALPHA"] = 2; - values[valuesById[3] = "BETA"] = 3; - values[valuesById[4] = "GA"] = 4; - values[valuesById[5] = "DEPRECATED"] = 5; + 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 new SelectiveGapicGeneration instance using the specified properties. + * @function create + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration=} [properties] Properties to set + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration instance + */ + SelectiveGapicGeneration.create = function create(properties) { + return new SelectiveGapicGeneration(properties); + }; + + /** + * Encodes the specified SelectiveGapicGeneration message. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @function encode + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration} message SelectiveGapicGeneration message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SelectiveGapicGeneration.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.methods != null && message.methods.length) + for (var i = 0; i < message.methods.length; ++i) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.methods[i]); + if (message.generateOmittedAsInternal != null && Object.hasOwnProperty.call(message, "generateOmittedAsInternal")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.generateOmittedAsInternal); + return writer; + }; + + /** + * Encodes the specified SelectiveGapicGeneration message, length delimited. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration} message SelectiveGapicGeneration message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SelectiveGapicGeneration.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer. + * @function decode + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SelectiveGapicGeneration.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.SelectiveGapicGeneration(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.methods && message.methods.length)) + message.methods = []; + message.methods.push(reader.string()); + break; + } + case 2: { + message.generateOmittedAsInternal = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SelectiveGapicGeneration.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SelectiveGapicGeneration message. + * @function verify + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SelectiveGapicGeneration.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.methods != null && message.hasOwnProperty("methods")) { + if (!Array.isArray(message.methods)) + return "methods: array expected"; + for (var i = 0; i < message.methods.length; ++i) + if (!$util.isString(message.methods[i])) + return "methods: string[] expected"; + } + if (message.generateOmittedAsInternal != null && message.hasOwnProperty("generateOmittedAsInternal")) + if (typeof message.generateOmittedAsInternal !== "boolean") + return "generateOmittedAsInternal: boolean expected"; + return null; + }; + + /** + * 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 + * @enum {number} + * @property {number} LAUNCH_STAGE_UNSPECIFIED=0 LAUNCH_STAGE_UNSPECIFIED value + * @property {number} UNIMPLEMENTED=6 UNIMPLEMENTED value + * @property {number} PRELAUNCH=7 PRELAUNCH value + * @property {number} EARLY_ACCESS=1 EARLY_ACCESS value + * @property {number} ALPHA=2 ALPHA value + * @property {number} BETA=3 BETA value + * @property {number} GA=4 GA value + * @property {number} DEPRECATED=5 DEPRECATED value + */ + api.LaunchStage = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "LAUNCH_STAGE_UNSPECIFIED"] = 0; + values[valuesById[6] = "UNIMPLEMENTED"] = 6; + values[valuesById[7] = "PRELAUNCH"] = 7; + values[valuesById[1] = "EARLY_ACCESS"] = 1; + values[valuesById[2] = "ALPHA"] = 2; + values[valuesById[3] = "BETA"] = 3; + values[valuesById[4] = "GA"] = 4; + values[valuesById[5] = "DEPRECATED"] = 5; return values; })(); @@ -10992,6 +11606,7 @@ * @name google.protobuf.Edition * @enum {number} * @property {number} EDITION_UNKNOWN=0 EDITION_UNKNOWN value + * @property {number} EDITION_LEGACY=900 EDITION_LEGACY value * @property {number} EDITION_PROTO2=998 EDITION_PROTO2 value * @property {number} EDITION_PROTO3=999 EDITION_PROTO3 value * @property {number} EDITION_2023=1000 EDITION_2023 value @@ -11006,6 +11621,7 @@ protobuf.Edition = (function() { var valuesById = {}, values = Object.create(valuesById); values[valuesById[0] = "EDITION_UNKNOWN"] = 0; + values[valuesById[900] = "EDITION_LEGACY"] = 900; values[valuesById[998] = "EDITION_PROTO2"] = 998; values[valuesById[999] = "EDITION_PROTO3"] = 999; values[valuesById[1000] = "EDITION_2023"] = 1000; @@ -11030,6 +11646,7 @@ * @property {Array.|null} [dependency] FileDescriptorProto dependency * @property {Array.|null} [publicDependency] FileDescriptorProto publicDependency * @property {Array.|null} [weakDependency] FileDescriptorProto weakDependency + * @property {Array.|null} [optionDependency] FileDescriptorProto optionDependency * @property {Array.|null} [messageType] FileDescriptorProto messageType * @property {Array.|null} [enumType] FileDescriptorProto enumType * @property {Array.|null} [service] FileDescriptorProto service @@ -11052,6 +11669,7 @@ this.dependency = []; this.publicDependency = []; this.weakDependency = []; + this.optionDependency = []; this.messageType = []; this.enumType = []; this.service = []; @@ -11102,6 +11720,14 @@ */ FileDescriptorProto.prototype.weakDependency = $util.emptyArray; + /** + * FileDescriptorProto optionDependency. + * @member {Array.} optionDependency + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.optionDependency = $util.emptyArray; + /** * FileDescriptorProto messageType. * @member {Array.} messageType @@ -11223,6 +11849,9 @@ writer.uint32(/* id 12, wireType 2 =*/98).string(message.syntax); if (message.edition != null && Object.hasOwnProperty.call(message, "edition")) writer.uint32(/* id 14, wireType 0 =*/112).int32(message.edition); + if (message.optionDependency != null && message.optionDependency.length) + for (var i = 0; i < message.optionDependency.length; ++i) + writer.uint32(/* id 15, wireType 2 =*/122).string(message.optionDependency[i]); return writer; }; @@ -11295,6 +11924,12 @@ message.weakDependency.push(reader.int32()); break; } + case 15: { + if (!(message.optionDependency && message.optionDependency.length)) + message.optionDependency = []; + message.optionDependency.push(reader.string()); + break; + } case 4: { if (!(message.messageType && message.messageType.length)) message.messageType = []; @@ -11397,6 +12032,13 @@ if (!$util.isInteger(message.weakDependency[i])) return "weakDependency: integer[] expected"; } + if (message.optionDependency != null && message.hasOwnProperty("optionDependency")) { + if (!Array.isArray(message.optionDependency)) + return "optionDependency: array expected"; + for (var i = 0; i < message.optionDependency.length; ++i) + if (!$util.isString(message.optionDependency[i])) + return "optionDependency: string[] expected"; + } if (message.messageType != null && message.hasOwnProperty("messageType")) { if (!Array.isArray(message.messageType)) return "messageType: array expected"; @@ -11451,6 +12093,7 @@ default: return "edition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -11503,6 +12146,13 @@ for (var i = 0; i < object.weakDependency.length; ++i) message.weakDependency[i] = object.weakDependency[i] | 0; } + if (object.optionDependency) { + if (!Array.isArray(object.optionDependency)) + throw TypeError(".google.protobuf.FileDescriptorProto.optionDependency: array expected"); + message.optionDependency = []; + for (var i = 0; i < object.optionDependency.length; ++i) + message.optionDependency[i] = String(object.optionDependency[i]); + } if (object.messageType) { if (!Array.isArray(object.messageType)) throw TypeError(".google.protobuf.FileDescriptorProto.messageType: array expected"); @@ -11566,6 +12216,10 @@ case 0: message.edition = 0; break; + case "EDITION_LEGACY": + case 900: + message.edition = 900; + break; case "EDITION_PROTO2": case 998: message.edition = 998; @@ -11631,6 +12285,7 @@ object.extension = []; object.publicDependency = []; object.weakDependency = []; + object.optionDependency = []; } if (options.defaults) { object.name = ""; @@ -11687,6 +12342,11 @@ 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; + if (message.optionDependency && message.optionDependency.length) { + object.optionDependency = []; + for (var j = 0; j < message.optionDependency.length; ++j) + object.optionDependency[j] = message.optionDependency[j]; + } return object; }; @@ -11735,6 +12395,7 @@ * @property {google.protobuf.IMessageOptions|null} [options] DescriptorProto options * @property {Array.|null} [reservedRange] DescriptorProto reservedRange * @property {Array.|null} [reservedName] DescriptorProto reservedName + * @property {google.protobuf.SymbolVisibility|null} [visibility] DescriptorProto visibility */ /** @@ -11840,6 +12501,14 @@ */ DescriptorProto.prototype.reservedName = $util.emptyArray; + /** + * DescriptorProto visibility. + * @member {google.protobuf.SymbolVisibility} visibility + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.visibility = 0; + /** * Creates a new DescriptorProto instance using the specified properties. * @function create @@ -11892,6 +12561,8 @@ if (message.reservedName != null && message.reservedName.length) for (var i = 0; i < message.reservedName.length; ++i) writer.uint32(/* id 10, wireType 2 =*/82).string(message.reservedName[i]); + if (message.visibility != null && Object.hasOwnProperty.call(message, "visibility")) + writer.uint32(/* id 11, wireType 0 =*/88).int32(message.visibility); return writer; }; @@ -11984,6 +12655,10 @@ message.reservedName.push(reader.string()); break; } + case 11: { + message.visibility = reader.int32(); + break; + } default: reader.skipType(tag & 7); break; @@ -12097,6 +12772,15 @@ if (!$util.isString(message.reservedName[i])) return "reservedName: string[] expected"; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + switch (message.visibility) { + default: + return "visibility: enum value expected"; + case 0: + case 1: + case 2: + break; + } return null; }; @@ -12196,6 +12880,26 @@ for (var i = 0; i < object.reservedName.length; ++i) message.reservedName[i] = String(object.reservedName[i]); } + switch (object.visibility) { + default: + if (typeof object.visibility === "number") { + message.visibility = object.visibility; + break; + } + break; + case "VISIBILITY_UNSET": + case 0: + message.visibility = 0; + break; + case "VISIBILITY_LOCAL": + case 1: + message.visibility = 1; + break; + case "VISIBILITY_EXPORT": + case 2: + message.visibility = 2; + break; + } return message; }; @@ -12225,6 +12929,7 @@ if (options.defaults) { object.name = ""; object.options = null; + object.visibility = options.enums === String ? "VISIBILITY_UNSET" : 0; } if (message.name != null && message.hasOwnProperty("name")) object.name = message.name; @@ -12270,6 +12975,8 @@ for (var j = 0; j < message.reservedName.length; ++j) object.reservedName[j] = message.reservedName[j]; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + object.visibility = options.enums === String ? $root.google.protobuf.SymbolVisibility[message.visibility] === undefined ? message.visibility : $root.google.protobuf.SymbolVisibility[message.visibility] : message.visibility; return object; }; @@ -14314,6 +15021,7 @@ * @property {google.protobuf.IEnumOptions|null} [options] EnumDescriptorProto options * @property {Array.|null} [reservedRange] EnumDescriptorProto reservedRange * @property {Array.|null} [reservedName] EnumDescriptorProto reservedName + * @property {google.protobuf.SymbolVisibility|null} [visibility] EnumDescriptorProto visibility */ /** @@ -14374,6 +15082,14 @@ */ EnumDescriptorProto.prototype.reservedName = $util.emptyArray; + /** + * EnumDescriptorProto visibility. + * @member {google.protobuf.SymbolVisibility} visibility + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.visibility = 0; + /** * Creates a new EnumDescriptorProto instance using the specified properties. * @function create @@ -14411,6 +15127,8 @@ if (message.reservedName != null && message.reservedName.length) for (var i = 0; i < message.reservedName.length; ++i) writer.uint32(/* id 5, wireType 2 =*/42).string(message.reservedName[i]); + if (message.visibility != null && Object.hasOwnProperty.call(message, "visibility")) + writer.uint32(/* id 6, wireType 0 =*/48).int32(message.visibility); return writer; }; @@ -14473,6 +15191,10 @@ message.reservedName.push(reader.string()); break; } + case 6: { + message.visibility = reader.int32(); + break; + } default: reader.skipType(tag & 7); break; @@ -14541,6 +15263,15 @@ if (!$util.isString(message.reservedName[i])) return "reservedName: string[] expected"; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + switch (message.visibility) { + default: + return "visibility: enum value expected"; + case 0: + case 1: + case 2: + break; + } return null; }; @@ -14590,6 +15321,26 @@ for (var i = 0; i < object.reservedName.length; ++i) message.reservedName[i] = String(object.reservedName[i]); } + switch (object.visibility) { + default: + if (typeof object.visibility === "number") { + message.visibility = object.visibility; + break; + } + break; + case "VISIBILITY_UNSET": + case 0: + message.visibility = 0; + break; + case "VISIBILITY_LOCAL": + case 1: + message.visibility = 1; + break; + case "VISIBILITY_EXPORT": + case 2: + message.visibility = 2; + break; + } return message; }; @@ -14614,6 +15365,7 @@ if (options.defaults) { object.name = ""; object.options = null; + object.visibility = options.enums === String ? "VISIBILITY_UNSET" : 0; } if (message.name != null && message.hasOwnProperty("name")) object.name = message.name; @@ -14634,6 +15386,8 @@ for (var j = 0; j < message.reservedName.length; ++j) object.reservedName[j] = message.reservedName[j]; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + object.visibility = options.enums === String ? $root.google.protobuf.SymbolVisibility[message.visibility] === undefined ? message.visibility : $root.google.protobuf.SymbolVisibility[message.visibility] : message.visibility; return object; }; @@ -16952,6 +17706,7 @@ * @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 @@ -17072,6 +17827,14 @@ */ 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 @@ -17146,6 +17909,8 @@ $root.google.protobuf.FieldOptions.EditionDefault.encode(message.editionDefaults[i], writer.uint32(/* id 20, wireType 2 =*/162).fork()).ldelim(); if (message.features != null && Object.hasOwnProperty.call(message, "features")) $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 21, wireType 2 =*/170).fork()).ldelim(); + if (message.featureSupport != null && Object.hasOwnProperty.call(message, "featureSupport")) + $root.google.protobuf.FieldOptions.FeatureSupport.encode(message.featureSupport, writer.uint32(/* id 22, wireType 2 =*/178).fork()).ldelim(); if (message.uninterpretedOption != null && message.uninterpretedOption.length) for (var i = 0; i < message.uninterpretedOption.length; ++i) $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); @@ -17247,6 +18012,10 @@ message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); break; } + case 22: { + message.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.decode(reader, reader.uint32()); + break; + } case 999: { if (!(message.uninterpretedOption && message.uninterpretedOption.length)) message.uninterpretedOption = []; @@ -17382,6 +18151,11 @@ if (error) return "features." + error; } + if (message.featureSupport != null && message.hasOwnProperty("featureSupport")) { + var error = $root.google.protobuf.FieldOptions.FeatureSupport.verify(message.featureSupport); + if (error) + return "featureSupport." + error; + } if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { if (!Array.isArray(message.uninterpretedOption)) return "uninterpretedOption: array expected"; @@ -17570,6 +18344,11 @@ 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"); @@ -17667,6 +18446,7 @@ 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")) @@ -17699,6 +18479,8 @@ } 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) @@ -17971,6 +18753,7 @@ default: return "edition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -18012,103 +18795,589 @@ 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.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. + * @function toObject + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {google.protobuf.FieldOptions.EditionDefault} message EditionDefault + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EditionDefault.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.value = ""; + object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; + } + 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 EditionDefault to JSON. + * @function toJSON + * @memberof google.protobuf.FieldOptions.EditionDefault + * @instance + * @returns {Object.} JSON object + */ + EditionDefault.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * 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; + })(); + + 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 new FeatureSupport instance using the specified properties. + * @function create + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport=} [properties] Properties to set + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport instance + */ + FeatureSupport.create = function create(properties) { + return new FeatureSupport(properties); + }; + + /** + * Encodes the specified FeatureSupport message. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport} message FeatureSupport message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FeatureSupport.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.editionIntroduced != null && Object.hasOwnProperty.call(message, "editionIntroduced")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.editionIntroduced); + if (message.editionDeprecated != null && Object.hasOwnProperty.call(message, "editionDeprecated")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.editionDeprecated); + if (message.deprecationWarning != null && Object.hasOwnProperty.call(message, "deprecationWarning")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.deprecationWarning); + if (message.editionRemoved != null && Object.hasOwnProperty.call(message, "editionRemoved")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.editionRemoved); + return writer; + }; + + /** + * Encodes the specified FeatureSupport message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport} message FeatureSupport message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FeatureSupport.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FeatureSupport.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FieldOptions.FeatureSupport(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.editionIntroduced = reader.int32(); + break; + } + case 2: { + message.editionDeprecated = reader.int32(); + break; + } + case 3: { + message.deprecationWarning = reader.string(); + break; + } + case 4: { + message.editionRemoved = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FeatureSupport.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FeatureSupport message. + * @function verify + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FeatureSupport.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.editionIntroduced != null && message.hasOwnProperty("editionIntroduced")) + switch (message.editionIntroduced) { + default: + return "editionIntroduced: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + if (message.editionDeprecated != null && message.hasOwnProperty("editionDeprecated")) + switch (message.editionDeprecated) { + default: + return "editionDeprecated: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + if (message.deprecationWarning != null && message.hasOwnProperty("deprecationWarning")) + if (!$util.isString(message.deprecationWarning)) + return "deprecationWarning: string expected"; + if (message.editionRemoved != null && message.hasOwnProperty("editionRemoved")) + switch (message.editionRemoved) { + default: + return "editionRemoved: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + return null; + }; + + /** + * 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.edition = 998; + message.editionRemoved = 998; break; case "EDITION_PROTO3": case 999: - message.edition = 999; + message.editionRemoved = 999; break; case "EDITION_2023": case 1000: - message.edition = 1000; + message.editionRemoved = 1000; break; case "EDITION_2024": case 1001: - message.edition = 1001; + message.editionRemoved = 1001; break; case "EDITION_1_TEST_ONLY": case 1: - message.edition = 1; + message.editionRemoved = 1; break; case "EDITION_2_TEST_ONLY": case 2: - message.edition = 2; + message.editionRemoved = 2; break; case "EDITION_99997_TEST_ONLY": case 99997: - message.edition = 99997; + message.editionRemoved = 99997; break; case "EDITION_99998_TEST_ONLY": case 99998: - message.edition = 99998; + message.editionRemoved = 99998; break; case "EDITION_99999_TEST_ONLY": case 99999: - message.edition = 99999; + message.editionRemoved = 99999; break; case "EDITION_MAX": case 2147483647: - message.edition = 2147483647; + message.editionRemoved = 2147483647; break; } - 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 FeatureSupport message. Also converts values to other types if specified. * @function toObject - * @memberof google.protobuf.FieldOptions.EditionDefault + * @memberof google.protobuf.FieldOptions.FeatureSupport * @static - * @param {google.protobuf.FieldOptions.EditionDefault} message EditionDefault + * @param {google.protobuf.FieldOptions.FeatureSupport} message FeatureSupport * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - EditionDefault.toObject = function toObject(message, options) { + FeatureSupport.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { - object.value = ""; - object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; + 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.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.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 EditionDefault to JSON. + * Converts this FeatureSupport to JSON. * @function toJSON - * @memberof google.protobuf.FieldOptions.EditionDefault + * @memberof google.protobuf.FieldOptions.FeatureSupport * @instance * @returns {Object.} JSON object */ - EditionDefault.prototype.toJSON = function toJSON() { + FeatureSupport.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 FeatureSupport * @function getTypeUrl - * @memberof google.protobuf.FieldOptions.EditionDefault + * @memberof google.protobuf.FieldOptions.FeatureSupport * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - EditionDefault.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + FeatureSupport.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.protobuf.FieldOptions.EditionDefault"; + return typeUrlPrefix + "/google.protobuf.FieldOptions.FeatureSupport"; }; - return EditionDefault; + return FeatureSupport; })(); return FieldOptions; @@ -18703,6 +19972,7 @@ * @property {boolean|null} [deprecated] EnumValueOptions deprecated * @property {google.protobuf.IFeatureSet|null} [features] EnumValueOptions features * @property {boolean|null} [debugRedact] EnumValueOptions debugRedact + * @property {google.protobuf.FieldOptions.IFeatureSupport|null} [featureSupport] EnumValueOptions featureSupport * @property {Array.|null} [uninterpretedOption] EnumValueOptions uninterpretedOption */ @@ -18746,6 +20016,14 @@ */ EnumValueOptions.prototype.debugRedact = false; + /** + * EnumValueOptions featureSupport. + * @member {google.protobuf.FieldOptions.IFeatureSupport|null|undefined} featureSupport + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.featureSupport = null; + /** * EnumValueOptions uninterpretedOption. * @member {Array.} uninterpretedOption @@ -18784,6 +20062,8 @@ $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); if (message.debugRedact != null && Object.hasOwnProperty.call(message, "debugRedact")) writer.uint32(/* id 3, wireType 0 =*/24).bool(message.debugRedact); + if (message.featureSupport != null && Object.hasOwnProperty.call(message, "featureSupport")) + $root.google.protobuf.FieldOptions.FeatureSupport.encode(message.featureSupport, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); if (message.uninterpretedOption != null && message.uninterpretedOption.length) for (var i = 0; i < message.uninterpretedOption.length; ++i) $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); @@ -18835,6 +20115,10 @@ message.debugRedact = reader.bool(); break; } + case 4: { + message.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.decode(reader, reader.uint32()); + break; + } case 999: { if (!(message.uninterpretedOption && message.uninterpretedOption.length)) message.uninterpretedOption = []; @@ -18887,6 +20171,11 @@ if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) if (typeof message.debugRedact !== "boolean") return "debugRedact: boolean expected"; + if (message.featureSupport != null && message.hasOwnProperty("featureSupport")) { + var error = $root.google.protobuf.FieldOptions.FeatureSupport.verify(message.featureSupport); + if (error) + return "featureSupport." + error; + } if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { if (!Array.isArray(message.uninterpretedOption)) return "uninterpretedOption: array expected"; @@ -18920,6 +20209,11 @@ } if (object.debugRedact != null) message.debugRedact = Boolean(object.debugRedact); + if (object.featureSupport != null) { + if (typeof object.featureSupport !== "object") + throw TypeError(".google.protobuf.EnumValueOptions.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.EnumValueOptions.uninterpretedOption: array expected"); @@ -18952,6 +20246,7 @@ object.deprecated = false; object.features = null; object.debugRedact = false; + object.featureSupport = null; } if (message.deprecated != null && message.hasOwnProperty("deprecated")) object.deprecated = message.deprecated; @@ -18959,6 +20254,8 @@ object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) object.debugRedact = message.debugRedact; + 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) @@ -20426,6 +21723,8 @@ * @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 + * @property {google.protobuf.FeatureSet.EnforceNamingStyle|null} [enforceNamingStyle] FeatureSet enforceNamingStyle + * @property {google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|null} [defaultSymbolVisibility] FeatureSet defaultSymbolVisibility */ /** @@ -20491,6 +21790,22 @@ */ FeatureSet.prototype.jsonFormat = 0; + /** + * FeatureSet enforceNamingStyle. + * @member {google.protobuf.FeatureSet.EnforceNamingStyle} enforceNamingStyle + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.enforceNamingStyle = 0; + + /** + * FeatureSet defaultSymbolVisibility. + * @member {google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility} defaultSymbolVisibility + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.defaultSymbolVisibility = 0; + /** * Creates a new FeatureSet instance using the specified properties. * @function create @@ -20527,6 +21842,10 @@ writer.uint32(/* id 5, wireType 0 =*/40).int32(message.messageEncoding); if (message.jsonFormat != null && Object.hasOwnProperty.call(message, "jsonFormat")) writer.uint32(/* id 6, wireType 0 =*/48).int32(message.jsonFormat); + if (message.enforceNamingStyle != null && Object.hasOwnProperty.call(message, "enforceNamingStyle")) + writer.uint32(/* id 7, wireType 0 =*/56).int32(message.enforceNamingStyle); + if (message.defaultSymbolVisibility != null && Object.hasOwnProperty.call(message, "defaultSymbolVisibility")) + writer.uint32(/* id 8, wireType 0 =*/64).int32(message.defaultSymbolVisibility); return writer; }; @@ -20587,6 +21906,14 @@ message.jsonFormat = reader.int32(); break; } + case 7: { + message.enforceNamingStyle = reader.int32(); + break; + } + case 8: { + message.defaultSymbolVisibility = reader.int32(); + break; + } default: reader.skipType(tag & 7); break; @@ -20677,6 +22004,26 @@ case 2: break; } + if (message.enforceNamingStyle != null && message.hasOwnProperty("enforceNamingStyle")) + switch (message.enforceNamingStyle) { + default: + return "enforceNamingStyle: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.defaultSymbolVisibility != null && message.hasOwnProperty("defaultSymbolVisibility")) + switch (message.defaultSymbolVisibility) { + default: + return "defaultSymbolVisibility: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + break; + } return null; }; @@ -20816,6 +22163,54 @@ message.jsonFormat = 2; break; } + switch (object.enforceNamingStyle) { + default: + if (typeof object.enforceNamingStyle === "number") { + message.enforceNamingStyle = object.enforceNamingStyle; + break; + } + break; + case "ENFORCE_NAMING_STYLE_UNKNOWN": + case 0: + message.enforceNamingStyle = 0; + break; + case "STYLE2024": + case 1: + message.enforceNamingStyle = 1; + break; + case "STYLE_LEGACY": + case 2: + message.enforceNamingStyle = 2; + break; + } + switch (object.defaultSymbolVisibility) { + default: + if (typeof object.defaultSymbolVisibility === "number") { + message.defaultSymbolVisibility = object.defaultSymbolVisibility; + break; + } + break; + case "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN": + case 0: + message.defaultSymbolVisibility = 0; + break; + case "EXPORT_ALL": + case 1: + message.defaultSymbolVisibility = 1; + break; + case "EXPORT_TOP_LEVEL": + case 2: + message.defaultSymbolVisibility = 2; + break; + case "LOCAL_ALL": + case 3: + message.defaultSymbolVisibility = 3; + break; + case "STRICT": + case 4: + message.defaultSymbolVisibility = 4; + break; + } return message; }; @@ -20839,6 +22234,8 @@ 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; + object.enforceNamingStyle = options.enums === String ? "ENFORCE_NAMING_STYLE_UNKNOWN" : 0; + object.defaultSymbolVisibility = options.enums === String ? "DEFAULT_SYMBOL_VISIBILITY_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; @@ -20852,6 +22249,10 @@ 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; + if (message.enforceNamingStyle != null && message.hasOwnProperty("enforceNamingStyle")) + object.enforceNamingStyle = options.enums === String ? $root.google.protobuf.FeatureSet.EnforceNamingStyle[message.enforceNamingStyle] === undefined ? message.enforceNamingStyle : $root.google.protobuf.FeatureSet.EnforceNamingStyle[message.enforceNamingStyle] : message.enforceNamingStyle; + if (message.defaultSymbolVisibility != null && message.hasOwnProperty("defaultSymbolVisibility")) + object.defaultSymbolVisibility = options.enums === String ? $root.google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility[message.defaultSymbolVisibility] === undefined ? message.defaultSymbolVisibility : $root.google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility[message.defaultSymbolVisibility] : message.defaultSymbolVisibility; return object; }; @@ -20979,6 +22380,219 @@ return values; })(); + /** + * EnforceNamingStyle enum. + * @name google.protobuf.FeatureSet.EnforceNamingStyle + * @enum {number} + * @property {number} ENFORCE_NAMING_STYLE_UNKNOWN=0 ENFORCE_NAMING_STYLE_UNKNOWN value + * @property {number} STYLE2024=1 STYLE2024 value + * @property {number} STYLE_LEGACY=2 STYLE_LEGACY value + */ + FeatureSet.EnforceNamingStyle = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ENFORCE_NAMING_STYLE_UNKNOWN"] = 0; + values[valuesById[1] = "STYLE2024"] = 1; + values[valuesById[2] = "STYLE_LEGACY"] = 2; + return values; + })(); + + FeatureSet.VisibilityFeature = (function() { + + /** + * Properties of a VisibilityFeature. + * @memberof google.protobuf.FeatureSet + * @interface IVisibilityFeature + */ + + /** + * Constructs a new VisibilityFeature. + * @memberof google.protobuf.FeatureSet + * @classdesc Represents a VisibilityFeature. + * @implements IVisibilityFeature + * @constructor + * @param {google.protobuf.FeatureSet.IVisibilityFeature=} [properties] Properties to set + */ + function VisibilityFeature(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 new VisibilityFeature instance using the specified properties. + * @function create + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature=} [properties] Properties to set + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature instance + */ + VisibilityFeature.create = function create(properties) { + return new VisibilityFeature(properties); + }; + + /** + * Encodes the specified VisibilityFeature message. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature} message VisibilityFeature message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + VisibilityFeature.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + return writer; + }; + + /** + * Encodes the specified VisibilityFeature message, length delimited. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature} message VisibilityFeature message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + VisibilityFeature.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + VisibilityFeature.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FeatureSet.VisibilityFeature(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + VisibilityFeature.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a VisibilityFeature message. + * @function verify + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + VisibilityFeature.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + return null; + }; + + /** + * Creates a VisibilityFeature message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + */ + VisibilityFeature.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FeatureSet.VisibilityFeature) + return object; + return new $root.google.protobuf.FeatureSet.VisibilityFeature(); + }; + + /** + * Creates a plain object from a VisibilityFeature message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.VisibilityFeature} message VisibilityFeature + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + VisibilityFeature.toObject = function toObject() { + return {}; + }; + + /** + * Converts this VisibilityFeature to JSON. + * @function toJSON + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @instance + * @returns {Object.} JSON object + */ + VisibilityFeature.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for VisibilityFeature + * @function getTypeUrl + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + VisibilityFeature.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FeatureSet.VisibilityFeature"; + }; + + /** + * DefaultSymbolVisibility enum. + * @name google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility + * @enum {number} + * @property {number} DEFAULT_SYMBOL_VISIBILITY_UNKNOWN=0 DEFAULT_SYMBOL_VISIBILITY_UNKNOWN value + * @property {number} EXPORT_ALL=1 EXPORT_ALL value + * @property {number} EXPORT_TOP_LEVEL=2 EXPORT_TOP_LEVEL value + * @property {number} LOCAL_ALL=3 LOCAL_ALL value + * @property {number} STRICT=4 STRICT value + */ + VisibilityFeature.DefaultSymbolVisibility = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN"] = 0; + values[valuesById[1] = "EXPORT_ALL"] = 1; + values[valuesById[2] = "EXPORT_TOP_LEVEL"] = 2; + values[valuesById[3] = "LOCAL_ALL"] = 3; + values[valuesById[4] = "STRICT"] = 4; + return values; + })(); + + return VisibilityFeature; + })(); + return FeatureSet; })(); @@ -21163,6 +22777,7 @@ default: return "minimumEdition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -21180,6 +22795,7 @@ default: return "maximumEdition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -21228,6 +22844,10 @@ case 0: message.minimumEdition = 0; break; + case "EDITION_LEGACY": + case 900: + message.minimumEdition = 900; + break; case "EDITION_PROTO2": case 998: message.minimumEdition = 998; @@ -21280,6 +22900,10 @@ case 0: message.maximumEdition = 0; break; + case "EDITION_LEGACY": + case 900: + message.maximumEdition = 900; + break; case "EDITION_PROTO2": case 998: message.maximumEdition = 998; @@ -21388,7 +23012,8 @@ * @memberof google.protobuf.FeatureSetDefaults * @interface IFeatureSetEditionDefault * @property {google.protobuf.Edition|null} [edition] FeatureSetEditionDefault edition - * @property {google.protobuf.IFeatureSet|null} [features] FeatureSetEditionDefault features + * @property {google.protobuf.IFeatureSet|null} [overridableFeatures] FeatureSetEditionDefault overridableFeatures + * @property {google.protobuf.IFeatureSet|null} [fixedFeatures] FeatureSetEditionDefault fixedFeatures */ /** @@ -21415,12 +23040,20 @@ FeatureSetEditionDefault.prototype.edition = 0; /** - * FeatureSetEditionDefault features. - * @member {google.protobuf.IFeatureSet|null|undefined} features + * 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 * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault * @instance */ - FeatureSetEditionDefault.prototype.features = null; + FeatureSetEditionDefault.prototype.fixedFeatures = null; /** * Creates a new FeatureSetEditionDefault instance using the specified properties. @@ -21446,10 +23079,12 @@ FeatureSetEditionDefault.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); - if (message.features != null && Object.hasOwnProperty.call(message, "features")) - $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); if (message.edition != null && Object.hasOwnProperty.call(message, "edition")) writer.uint32(/* id 3, wireType 0 =*/24).int32(message.edition); + if (message.overridableFeatures != null && Object.hasOwnProperty.call(message, "overridableFeatures")) + $root.google.protobuf.FeatureSet.encode(message.overridableFeatures, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.fixedFeatures != null && Object.hasOwnProperty.call(message, "fixedFeatures")) + $root.google.protobuf.FeatureSet.encode(message.fixedFeatures, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); return writer; }; @@ -21490,8 +23125,12 @@ message.edition = reader.int32(); break; } - case 2: { - message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + case 4: { + message.overridableFeatures = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + break; + } + case 5: { + message.fixedFeatures = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); break; } default: @@ -21534,6 +23173,7 @@ default: return "edition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -21546,10 +23186,15 @@ case 2147483647: break; } - if (message.features != null && message.hasOwnProperty("features")) { - var error = $root.google.protobuf.FeatureSet.verify(message.features); + if (message.overridableFeatures != null && message.hasOwnProperty("overridableFeatures")) { + var error = $root.google.protobuf.FeatureSet.verify(message.overridableFeatures); + if (error) + return "overridableFeatures." + error; + } + if (message.fixedFeatures != null && message.hasOwnProperty("fixedFeatures")) { + var error = $root.google.protobuf.FeatureSet.verify(message.fixedFeatures); if (error) - return "features." + error; + return "fixedFeatures." + error; } return null; }; @@ -21577,6 +23222,10 @@ case 0: message.edition = 0; break; + case "EDITION_LEGACY": + case 900: + message.edition = 900; + break; case "EDITION_PROTO2": case 998: message.edition = 998; @@ -21618,10 +23267,15 @@ message.edition = 2147483647; break; } - 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); + 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); } return message; }; @@ -21640,13 +23294,16 @@ 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; }; @@ -22861,6 +24518,22 @@ return GeneratedCodeInfo; })(); + /** + * SymbolVisibility enum. + * @name google.protobuf.SymbolVisibility + * @enum {number} + * @property {number} VISIBILITY_UNSET=0 VISIBILITY_UNSET value + * @property {number} VISIBILITY_LOCAL=1 VISIBILITY_LOCAL value + * @property {number} VISIBILITY_EXPORT=2 VISIBILITY_EXPORT value + */ + protobuf.SymbolVisibility = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "VISIBILITY_UNSET"] = 0; + values[valuesById[1] = "VISIBILITY_LOCAL"] = 1; + values[valuesById[2] = "VISIBILITY_EXPORT"] = 2; + return values; + })(); + protobuf.Timestamp = (function() { /** diff --git a/packages/google-api-apikeys/protos/protos.json b/packages/google-api-apikeys/protos/protos.json index a0d4bc39a29d..886de77c508a 100644 --- a/packages/google-api-apikeys/protos/protos.json +++ b/packages/google-api-apikeys/protos/protos.json @@ -8,8 +8,7 @@ "java_multiple_files": true, "java_outer_classname": "LaunchStageProto", "java_package": "com.google.api", - "objc_class_prefix": "GAPI", - "cc_enable_arenas": true + "objc_class_prefix": "GAPI" }, "nested": { "apikeys": { @@ -773,6 +772,10 @@ "rule": "repeated", "type": "ClientLibraryDestination", "id": 2 + }, + "selectiveGapicGeneration": { + "type": "SelectiveGapicGeneration", + "id": 3 } } }, @@ -913,6 +916,28 @@ "common": { "type": "CommonLanguageSettings", "id": 1 + }, + "experimentalFeatures": { + "type": "ExperimentalFeatures", + "id": 2 + } + }, + "nested": { + "ExperimentalFeatures": { + "fields": { + "restAsyncIoEnabled": { + "type": "bool", + "id": 1 + }, + "protobufPythonicTypesEnabled": { + "type": "bool", + "id": 2 + }, + "unversionedPackageDisabled": { + "type": "bool", + "id": 3 + } + } } } }, @@ -970,6 +995,11 @@ "common": { "type": "CommonLanguageSettings", "id": 1 + }, + "renamedServices": { + "keyType": "string", + "type": "string", + "id": 2 } } }, @@ -1031,6 +1061,19 @@ "PACKAGE_MANAGER": 20 } }, + "SelectiveGapicGeneration": { + "fields": { + "methods": { + "rule": "repeated", + "type": "string", + "id": 1 + }, + "generateOmittedAsInternal": { + "type": "bool", + "id": 2 + } + } + }, "LaunchStage": { "values": { "LAUNCH_STAGE_UNSPECIFIED": 0, @@ -1064,12 +1107,19 @@ "type": "FileDescriptorProto", "id": 1 } - } + }, + "extensions": [ + [ + 536000000, + 536000000 + ] + ] }, "Edition": { "edition": "proto2", "values": { "EDITION_UNKNOWN": 0, + "EDITION_LEGACY": 900, "EDITION_PROTO2": 998, "EDITION_PROTO3": 999, "EDITION_2023": 1000, @@ -1108,6 +1158,11 @@ "type": "int32", "id": 11 }, + "optionDependency": { + "rule": "repeated", + "type": "string", + "id": 15 + }, "messageType": { "rule": "repeated", "type": "DescriptorProto", @@ -1196,6 +1251,10 @@ "rule": "repeated", "type": "string", "id": 10 + }, + "visibility": { + "type": "SymbolVisibility", + "id": 11 } }, "nested": { @@ -1421,6 +1480,10 @@ "rule": "repeated", "type": "string", "id": 5 + }, + "visibility": { + "type": "SymbolVisibility", + "id": 6 } }, "nested": { @@ -1471,7 +1534,14 @@ "type": "ServiceOptions", "id": 3 } - } + }, + "reserved": [ + [ + 4, + 4 + ], + "stream" + ] }, "MethodDescriptorProto": { "edition": "proto2", @@ -1635,6 +1705,7 @@ 42, 42 ], + "php_generic_services", [ 38, 38 @@ -1770,7 +1841,8 @@ "type": "bool", "id": 10, "options": { - "default": false + "default": false, + "deprecated": true } }, "debugRedact": { @@ -1798,6 +1870,10 @@ "type": "FeatureSet", "id": 21 }, + "featureSupport": { + "type": "FeatureSupport", + "id": 22 + }, "uninterpretedOption": { "rule": "repeated", "type": "UninterpretedOption", @@ -1867,6 +1943,26 @@ "id": 2 } } + }, + "FeatureSupport": { + "fields": { + "editionIntroduced": { + "type": "Edition", + "id": 1 + }, + "editionDeprecated": { + "type": "Edition", + "id": 2 + }, + "deprecationWarning": { + "type": "string", + "id": 3 + }, + "editionRemoved": { + "type": "Edition", + "id": 4 + } + } } } }, @@ -1955,6 +2051,10 @@ "default": false } }, + "featureSupport": { + "type": "FieldOptions.FeatureSupport", + "id": 4 + }, "uninterpretedOption": { "rule": "repeated", "type": "UninterpretedOption", @@ -2097,6 +2197,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_2023", "edition_defaults.value": "EXPLICIT" } @@ -2107,6 +2208,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "OPEN" } @@ -2117,6 +2219,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "PACKED" } @@ -2127,6 +2230,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "VERIFY" } @@ -2137,7 +2241,8 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", - "edition_defaults.edition": "EDITION_PROTO2", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_LEGACY", "edition_defaults.value": "LENGTH_PREFIXED" } }, @@ -2147,27 +2252,38 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "ALLOW" } + }, + "enforceNamingStyle": { + "type": "EnforceNamingStyle", + "id": 7, + "options": { + "retention": "RETENTION_SOURCE", + "targets": "TARGET_TYPE_METHOD", + "feature_support.edition_introduced": "EDITION_2024", + "edition_defaults.edition": "EDITION_2024", + "edition_defaults.value": "STYLE2024" + } + }, + "defaultSymbolVisibility": { + "type": "VisibilityFeature.DefaultSymbolVisibility", + "id": 8, + "options": { + "retention": "RETENTION_SOURCE", + "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2024", + "edition_defaults.edition": "EDITION_2024", + "edition_defaults.value": "EXPORT_TOP_LEVEL" + } } }, "extensions": [ [ 1000, - 1000 - ], - [ - 1001, - 1001 - ], - [ - 1002, - 1002 - ], - [ - 9990, - 9990 + 9994 ], [ 9995, @@ -2212,7 +2328,13 @@ "UTF8_VALIDATION_UNKNOWN": 0, "VERIFY": 2, "NONE": 3 - } + }, + "reserved": [ + [ + 1, + 1 + ] + ] }, "MessageEncoding": { "values": { @@ -2227,6 +2349,33 @@ "ALLOW": 1, "LEGACY_BEST_EFFORT": 2 } + }, + "EnforceNamingStyle": { + "values": { + "ENFORCE_NAMING_STYLE_UNKNOWN": 0, + "STYLE2024": 1, + "STYLE_LEGACY": 2 + } + }, + "VisibilityFeature": { + "fields": {}, + "reserved": [ + [ + 1, + 536870911 + ] + ], + "nested": { + "DefaultSymbolVisibility": { + "values": { + "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN": 0, + "EXPORT_ALL": 1, + "EXPORT_TOP_LEVEL": 2, + "LOCAL_ALL": 3, + "STRICT": 4 + } + } + } } } }, @@ -2254,11 +2403,26 @@ "type": "Edition", "id": 3 }, - "features": { + "overridableFeatures": { "type": "FeatureSet", - "id": 2 + "id": 4 + }, + "fixedFeatures": { + "type": "FeatureSet", + "id": 5 } - } + }, + "reserved": [ + [ + 1, + 1 + ], + [ + 2, + 2 + ], + "features" + ] } } }, @@ -2271,6 +2435,12 @@ "id": 1 } }, + "extensions": [ + [ + 536000000, + 536000000 + ] + ], "nested": { "Location": { "fields": { @@ -2356,6 +2526,14 @@ } } }, + "SymbolVisibility": { + "edition": "proto2", + "values": { + "VISIBILITY_UNSET": 0, + "VISIBILITY_LOCAL": 1, + "VISIBILITY_EXPORT": 2 + } + }, "Timestamp": { "fields": { "seconds": { @@ -2414,6 +2592,7 @@ "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/packages/google-api-apikeys/samples/generated/v2/snippet_metadata_google.api.apikeys.v2.json b/packages/google-api-apikeys/samples/generated/v2/snippet_metadata_google.api.apikeys.v2.json index a9368098ad0d..49f0adaef00b 100644 --- a/packages/google-api-apikeys/samples/generated/v2/snippet_metadata_google.api.apikeys.v2.json +++ b/packages/google-api-apikeys/samples/generated/v2/snippet_metadata_google.api.apikeys.v2.json @@ -1,7 +1,7 @@ { "clientLibrary": { "name": "nodejs-apikeys", - "version": "2.2.1", + "version": "0.1.0", "language": "TYPESCRIPT", "apis": [ { diff --git a/packages/google-api-apikeys/src/v2/api_keys_client.ts b/packages/google-api-apikeys/src/v2/api_keys_client.ts index f6f975cb3f76..6b3b6b90abf8 100644 --- a/packages/google-api-apikeys/src/v2/api_keys_client.ts +++ b/packages/google-api-apikeys/src/v2/api_keys_client.ts @@ -18,11 +18,20 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -44,7 +53,7 @@ export class ApiKeysClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('apikeys'); @@ -57,10 +66,10 @@ export class ApiKeysClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; operationsClient: gax.OperationsClient; - apiKeysStub?: Promise<{[name: string]: Function}>; + apiKeysStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ApiKeysClient. @@ -101,21 +110,42 @@ export class ApiKeysClient { * const client = new ApiKeysClient({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 ApiKeysClient; - 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 = 'apikeys.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -140,7 +170,7 @@ export class ApiKeysClient { 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; @@ -154,10 +184,7 @@ export class ApiKeysClient { } // 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 { @@ -179,13 +206,13 @@ export class ApiKeysClient { // Create useful helper objects for these. this.pathTemplates = { keyPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/keys/{key}' + 'projects/{project}/locations/{location}/keys/{key}', ), locationPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}' + 'projects/{project}/locations/{location}', ), projectPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}' + 'projects/{project}', ), }; @@ -193,8 +220,11 @@ export class ApiKeysClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listKeys: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'keys') + listKeys: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'keys', + ), }; const protoFilesRoot = this._gaxModule.protobufFromJSON(jsonProtos); @@ -203,53 +233,75 @@ export class ApiKeysClient { // 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.GetOperation',get: '/v2/{name=operations/*}',}]; + lroOptions.httpRules = [ + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v2/{name=operations/*}', + }, + ]; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const createKeyResponse = protoFilesRoot.lookup( - '.google.api.apikeys.v2.Key') as gax.protobuf.Type; + '.google.api.apikeys.v2.Key', + ) as gax.protobuf.Type; const createKeyMetadata = protoFilesRoot.lookup( - '.google.protobuf.Empty') as gax.protobuf.Type; + '.google.protobuf.Empty', + ) as gax.protobuf.Type; const updateKeyResponse = protoFilesRoot.lookup( - '.google.api.apikeys.v2.Key') as gax.protobuf.Type; + '.google.api.apikeys.v2.Key', + ) as gax.protobuf.Type; const updateKeyMetadata = protoFilesRoot.lookup( - '.google.protobuf.Empty') as gax.protobuf.Type; + '.google.protobuf.Empty', + ) as gax.protobuf.Type; const deleteKeyResponse = protoFilesRoot.lookup( - '.google.api.apikeys.v2.Key') as gax.protobuf.Type; + '.google.api.apikeys.v2.Key', + ) as gax.protobuf.Type; const deleteKeyMetadata = protoFilesRoot.lookup( - '.google.protobuf.Empty') as gax.protobuf.Type; + '.google.protobuf.Empty', + ) as gax.protobuf.Type; const undeleteKeyResponse = protoFilesRoot.lookup( - '.google.api.apikeys.v2.Key') as gax.protobuf.Type; + '.google.api.apikeys.v2.Key', + ) as gax.protobuf.Type; const undeleteKeyMetadata = protoFilesRoot.lookup( - '.google.protobuf.Empty') as gax.protobuf.Type; + '.google.protobuf.Empty', + ) as gax.protobuf.Type; this.descriptors.longrunning = { createKey: new this._gaxModule.LongrunningDescriptor( this.operationsClient, createKeyResponse.decode.bind(createKeyResponse), - createKeyMetadata.decode.bind(createKeyMetadata)), + createKeyMetadata.decode.bind(createKeyMetadata), + ), updateKey: new this._gaxModule.LongrunningDescriptor( this.operationsClient, updateKeyResponse.decode.bind(updateKeyResponse), - updateKeyMetadata.decode.bind(updateKeyMetadata)), + updateKeyMetadata.decode.bind(updateKeyMetadata), + ), deleteKey: new this._gaxModule.LongrunningDescriptor( this.operationsClient, deleteKeyResponse.decode.bind(deleteKeyResponse), - deleteKeyMetadata.decode.bind(deleteKeyMetadata)), + deleteKeyMetadata.decode.bind(deleteKeyMetadata), + ), undeleteKey: new this._gaxModule.LongrunningDescriptor( this.operationsClient, undeleteKeyResponse.decode.bind(undeleteKeyResponse), - undeleteKeyMetadata.decode.bind(undeleteKeyMetadata)) + undeleteKeyMetadata.decode.bind(undeleteKeyMetadata), + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.api.apikeys.v2.ApiKeys', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.api.apikeys.v2.ApiKeys', + 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 @@ -280,28 +332,42 @@ export class ApiKeysClient { // Put together the "service stub" for // google.api.apikeys.v2.ApiKeys. this.apiKeysStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.api.apikeys.v2.ApiKeys') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.api.apikeys.v2.ApiKeys', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.api.apikeys.v2.ApiKeys, - 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 apiKeysStubMethods = - ['createKey', 'listKeys', 'getKey', 'getKeyString', 'updateKey', 'deleteKey', 'undeleteKey', 'lookupKey']; + const apiKeysStubMethods = [ + 'createKey', + 'listKeys', + 'getKey', + 'getKeyString', + 'updateKey', + 'deleteKey', + 'undeleteKey', + 'lookupKey', + ]; for (const methodName of apiKeysStubMethods) { const callPromise = this.apiKeysStub.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] || @@ -311,7 +377,7 @@ export class ApiKeysClient { callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -326,8 +392,14 @@ export class ApiKeysClient { * @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 'apikeys.googleapis.com'; } @@ -338,8 +410,14 @@ export class ApiKeysClient { * @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 'apikeys.googleapis.com'; } @@ -372,7 +450,7 @@ export class ApiKeysClient { static get scopes() { return [ 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only' + 'https://www.googleapis.com/auth/cloud-platform.read-only', ]; } @@ -382,8 +460,9 @@ export class ApiKeysClient { * 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; @@ -394,852 +473,1194 @@ export class ApiKeysClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets the metadata for an API key. The key string of the API key - * isn't included in the response. - * - * NOTE: Key is a global resource; hence the only supported value for - * location is `global`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the API key to get. - * @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.api.apikeys.v2.Key|Key}. - * 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/v2/api_keys.get_key.js - * region_tag:apikeys_v2_generated_ApiKeys_GetKey_async - */ + /** + * Gets the metadata for an API key. The key string of the API key + * isn't included in the response. + * + * NOTE: Key is a global resource; hence the only supported value for + * location is `global`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the API key to get. + * @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.api.apikeys.v2.Key|Key}. + * 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/v2/api_keys.get_key.js + * region_tag:apikeys_v2_generated_ApiKeys_GetKey_async + */ getKey( - request?: protos.google.api.apikeys.v2.IGetKeyRequest, - options?: CallOptions): - Promise<[ - protos.google.api.apikeys.v2.IKey, - protos.google.api.apikeys.v2.IGetKeyRequest|undefined, {}|undefined - ]>; + request?: protos.google.api.apikeys.v2.IGetKeyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.apikeys.v2.IKey, + protos.google.api.apikeys.v2.IGetKeyRequest | undefined, + {} | undefined, + ] + >; getKey( - request: protos.google.api.apikeys.v2.IGetKeyRequest, - options: CallOptions, - callback: Callback< - protos.google.api.apikeys.v2.IKey, - protos.google.api.apikeys.v2.IGetKeyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.apikeys.v2.IGetKeyRequest, + options: CallOptions, + callback: Callback< + protos.google.api.apikeys.v2.IKey, + protos.google.api.apikeys.v2.IGetKeyRequest | null | undefined, + {} | null | undefined + >, + ): void; getKey( - request: protos.google.api.apikeys.v2.IGetKeyRequest, - callback: Callback< - protos.google.api.apikeys.v2.IKey, - protos.google.api.apikeys.v2.IGetKeyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.apikeys.v2.IGetKeyRequest, + callback: Callback< + protos.google.api.apikeys.v2.IKey, + protos.google.api.apikeys.v2.IGetKeyRequest | null | undefined, + {} | null | undefined + >, + ): void; getKey( - request?: protos.google.api.apikeys.v2.IGetKeyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.api.apikeys.v2.IKey, - protos.google.api.apikeys.v2.IGetKeyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.api.apikeys.v2.IGetKeyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.apikeys.v2.IKey, - protos.google.api.apikeys.v2.IGetKeyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.apikeys.v2.IKey, - protos.google.api.apikeys.v2.IGetKeyRequest|undefined, {}|undefined - ]>|void { + protos.google.api.apikeys.v2.IGetKeyRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.apikeys.v2.IKey, + protos.google.api.apikeys.v2.IGetKeyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.apikeys.v2.IKey, + protos.google.api.apikeys.v2.IGetKeyRequest | 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('getKey request %j', request); - const wrappedCallback: Callback< - protos.google.api.apikeys.v2.IKey, - protos.google.api.apikeys.v2.IGetKeyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.apikeys.v2.IKey, + protos.google.api.apikeys.v2.IGetKeyRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getKey response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getKey(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.apikeys.v2.IKey, - protos.google.api.apikeys.v2.IGetKeyRequest|undefined, - {}|undefined - ]) => { - this._log.info('getKey response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getKey(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.apikeys.v2.IKey, + protos.google.api.apikeys.v2.IGetKeyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getKey response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Get the key string for an API key. - * - * NOTE: Key is a global resource; hence the only supported value for - * location is `global`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the API key to be retrieved. - * @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.api.apikeys.v2.GetKeyStringResponse|GetKeyStringResponse}. - * 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/v2/api_keys.get_key_string.js - * region_tag:apikeys_v2_generated_ApiKeys_GetKeyString_async - */ + /** + * Get the key string for an API key. + * + * NOTE: Key is a global resource; hence the only supported value for + * location is `global`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the API key to be retrieved. + * @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.api.apikeys.v2.GetKeyStringResponse|GetKeyStringResponse}. + * 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/v2/api_keys.get_key_string.js + * region_tag:apikeys_v2_generated_ApiKeys_GetKeyString_async + */ getKeyString( - request?: protos.google.api.apikeys.v2.IGetKeyStringRequest, - options?: CallOptions): - Promise<[ - protos.google.api.apikeys.v2.IGetKeyStringResponse, - protos.google.api.apikeys.v2.IGetKeyStringRequest|undefined, {}|undefined - ]>; + request?: protos.google.api.apikeys.v2.IGetKeyStringRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.apikeys.v2.IGetKeyStringResponse, + protos.google.api.apikeys.v2.IGetKeyStringRequest | undefined, + {} | undefined, + ] + >; getKeyString( - request: protos.google.api.apikeys.v2.IGetKeyStringRequest, - options: CallOptions, - callback: Callback< - protos.google.api.apikeys.v2.IGetKeyStringResponse, - protos.google.api.apikeys.v2.IGetKeyStringRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.apikeys.v2.IGetKeyStringRequest, + options: CallOptions, + callback: Callback< + protos.google.api.apikeys.v2.IGetKeyStringResponse, + protos.google.api.apikeys.v2.IGetKeyStringRequest | null | undefined, + {} | null | undefined + >, + ): void; getKeyString( - request: protos.google.api.apikeys.v2.IGetKeyStringRequest, - callback: Callback< - protos.google.api.apikeys.v2.IGetKeyStringResponse, - protos.google.api.apikeys.v2.IGetKeyStringRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.apikeys.v2.IGetKeyStringRequest, + callback: Callback< + protos.google.api.apikeys.v2.IGetKeyStringResponse, + protos.google.api.apikeys.v2.IGetKeyStringRequest | null | undefined, + {} | null | undefined + >, + ): void; getKeyString( - request?: protos.google.api.apikeys.v2.IGetKeyStringRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.api.apikeys.v2.IGetKeyStringResponse, - protos.google.api.apikeys.v2.IGetKeyStringRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.api.apikeys.v2.IGetKeyStringRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.apikeys.v2.IGetKeyStringResponse, - protos.google.api.apikeys.v2.IGetKeyStringRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.apikeys.v2.IGetKeyStringResponse, - protos.google.api.apikeys.v2.IGetKeyStringRequest|undefined, {}|undefined - ]>|void { + protos.google.api.apikeys.v2.IGetKeyStringRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.apikeys.v2.IGetKeyStringResponse, + protos.google.api.apikeys.v2.IGetKeyStringRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.apikeys.v2.IGetKeyStringResponse, + protos.google.api.apikeys.v2.IGetKeyStringRequest | 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('getKeyString request %j', request); - const wrappedCallback: Callback< - protos.google.api.apikeys.v2.IGetKeyStringResponse, - protos.google.api.apikeys.v2.IGetKeyStringRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.apikeys.v2.IGetKeyStringResponse, + protos.google.api.apikeys.v2.IGetKeyStringRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getKeyString response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getKeyString(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.apikeys.v2.IGetKeyStringResponse, - protos.google.api.apikeys.v2.IGetKeyStringRequest|undefined, - {}|undefined - ]) => { - this._log.info('getKeyString response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getKeyString(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.apikeys.v2.IGetKeyStringResponse, + protos.google.api.apikeys.v2.IGetKeyStringRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getKeyString response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Find the parent project and resource name of the API - * key that matches the key string in the request. If the API key has been - * purged, resource name will not be set. - * The service account must have the `apikeys.keys.lookup` permission - * on the parent project. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.keyString - * Required. Finds the project that owns the key string value. - * @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.api.apikeys.v2.LookupKeyResponse|LookupKeyResponse}. - * 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/v2/api_keys.lookup_key.js - * region_tag:apikeys_v2_generated_ApiKeys_LookupKey_async - */ + /** + * Find the parent project and resource name of the API + * key that matches the key string in the request. If the API key has been + * purged, resource name will not be set. + * The service account must have the `apikeys.keys.lookup` permission + * on the parent project. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.keyString + * Required. Finds the project that owns the key string value. + * @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.api.apikeys.v2.LookupKeyResponse|LookupKeyResponse}. + * 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/v2/api_keys.lookup_key.js + * region_tag:apikeys_v2_generated_ApiKeys_LookupKey_async + */ lookupKey( - request?: protos.google.api.apikeys.v2.ILookupKeyRequest, - options?: CallOptions): - Promise<[ - protos.google.api.apikeys.v2.ILookupKeyResponse, - protos.google.api.apikeys.v2.ILookupKeyRequest|undefined, {}|undefined - ]>; + request?: protos.google.api.apikeys.v2.ILookupKeyRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.apikeys.v2.ILookupKeyResponse, + protos.google.api.apikeys.v2.ILookupKeyRequest | undefined, + {} | undefined, + ] + >; lookupKey( - request: protos.google.api.apikeys.v2.ILookupKeyRequest, - options: CallOptions, - callback: Callback< - protos.google.api.apikeys.v2.ILookupKeyResponse, - protos.google.api.apikeys.v2.ILookupKeyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.apikeys.v2.ILookupKeyRequest, + options: CallOptions, + callback: Callback< + protos.google.api.apikeys.v2.ILookupKeyResponse, + protos.google.api.apikeys.v2.ILookupKeyRequest | null | undefined, + {} | null | undefined + >, + ): void; lookupKey( - request: protos.google.api.apikeys.v2.ILookupKeyRequest, - callback: Callback< - protos.google.api.apikeys.v2.ILookupKeyResponse, - protos.google.api.apikeys.v2.ILookupKeyRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.apikeys.v2.ILookupKeyRequest, + callback: Callback< + protos.google.api.apikeys.v2.ILookupKeyResponse, + protos.google.api.apikeys.v2.ILookupKeyRequest | null | undefined, + {} | null | undefined + >, + ): void; lookupKey( - request?: protos.google.api.apikeys.v2.ILookupKeyRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.api.apikeys.v2.ILookupKeyResponse, - protos.google.api.apikeys.v2.ILookupKeyRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.api.apikeys.v2.ILookupKeyRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.apikeys.v2.ILookupKeyResponse, - protos.google.api.apikeys.v2.ILookupKeyRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.apikeys.v2.ILookupKeyResponse, - protos.google.api.apikeys.v2.ILookupKeyRequest|undefined, {}|undefined - ]>|void { + protos.google.api.apikeys.v2.ILookupKeyRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.apikeys.v2.ILookupKeyResponse, + protos.google.api.apikeys.v2.ILookupKeyRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.apikeys.v2.ILookupKeyResponse, + protos.google.api.apikeys.v2.ILookupKeyRequest | 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 || {}; - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('lookupKey request %j', request); - const wrappedCallback: Callback< - protos.google.api.apikeys.v2.ILookupKeyResponse, - protos.google.api.apikeys.v2.ILookupKeyRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.apikeys.v2.ILookupKeyResponse, + protos.google.api.apikeys.v2.ILookupKeyRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('lookupKey response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.lookupKey(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.apikeys.v2.ILookupKeyResponse, - protos.google.api.apikeys.v2.ILookupKeyRequest|undefined, - {}|undefined - ]) => { - this._log.info('lookupKey response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .lookupKey(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.apikeys.v2.ILookupKeyResponse, + protos.google.api.apikeys.v2.ILookupKeyRequest | undefined, + {} | undefined, + ]) => { + this._log.info('lookupKey response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new API key. - * - * NOTE: Key is a global resource; hence the only supported value for - * location is `global`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The project in which the API key is created. - * @param {google.api.apikeys.v2.Key} request.key - * Required. The API key fields to set at creation time. - * You can configure only the `display_name`, `restrictions`, and - * `annotations` fields. - * @param {string} request.keyId - * User specified key id (optional). If specified, it will become the final - * component of the key resource name. - * - * The id must be unique within the project, must conform with RFC-1034, - * is restricted to lower-cased letters, and has a maximum length of 63 - * characters. In another word, the id must match the regular - * expression: `[a-z]([a-z0-9-]{0,61}[a-z0-9])?`. - * - * The id must NOT be a UUID-like string. - * @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/v2/api_keys.create_key.js - * region_tag:apikeys_v2_generated_ApiKeys_CreateKey_async - */ + /** + * Creates a new API key. + * + * NOTE: Key is a global resource; hence the only supported value for + * location is `global`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The project in which the API key is created. + * @param {google.api.apikeys.v2.Key} request.key + * Required. The API key fields to set at creation time. + * You can configure only the `display_name`, `restrictions`, and + * `annotations` fields. + * @param {string} request.keyId + * User specified key id (optional). If specified, it will become the final + * component of the key resource name. + * + * The id must be unique within the project, must conform with RFC-1034, + * is restricted to lower-cased letters, and has a maximum length of 63 + * characters. In another word, the id must match the regular + * expression: `[a-z]([a-z0-9-]{0,61}[a-z0-9])?`. + * + * The id must NOT be a UUID-like string. + * @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/v2/api_keys.create_key.js + * region_tag:apikeys_v2_generated_ApiKeys_CreateKey_async + */ createKey( - request?: protos.google.api.apikeys.v2.ICreateKeyRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.api.apikeys.v2.ICreateKeyRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; createKey( - request: protos.google.api.apikeys.v2.ICreateKeyRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.apikeys.v2.ICreateKeyRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createKey( - request: protos.google.api.apikeys.v2.ICreateKeyRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.apikeys.v2.ICreateKeyRequest, + callback: Callback< + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; createKey( - request?: protos.google.api.apikeys.v2.ICreateKeyRequest, - 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.api.apikeys.v2.ICreateKeyRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + 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.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('createKey response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('createKey request %j', request); - return this.innerApiCalls.createKey(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('createKey response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .createKey(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createKey response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `createKey()`. - * @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/v2/api_keys.create_key.js - * region_tag:apikeys_v2_generated_ApiKeys_CreateKey_async - */ - async checkCreateKeyProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `createKey()`. + * @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/v2/api_keys.create_key.js + * region_tag:apikeys_v2_generated_ApiKeys_CreateKey_async + */ + async checkCreateKeyProgress( + name: string, + ): Promise< + LROperation + > { this._log.info('createKey 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.createKey, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createKey, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.api.apikeys.v2.Key, + protos.google.protobuf.Empty + >; } -/** - * Patches the modifiable fields of an API key. - * The key string of the API key isn't included in the response. - * - * NOTE: Key is a global resource; hence the only supported value for - * location is `global`. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.api.apikeys.v2.Key} request.key - * Required. Set the `name` field to the resource name of the API key to be - * updated. You can update only the `display_name`, `restrictions`, and - * `annotations` fields. - * @param {google.protobuf.FieldMask} request.updateMask - * The field mask specifies which fields to be updated as part of this - * request. All other fields are ignored. - * Mutable fields are: `display_name`, `restrictions`, and `annotations`. - * If an update mask is not provided, the service treats it as an implied mask - * equivalent to all allowed fields that are set on the wire. If the field - * mask has a special value "*", the service treats it equivalent to replace - * all allowed mutable fields. - * @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/v2/api_keys.update_key.js - * region_tag:apikeys_v2_generated_ApiKeys_UpdateKey_async - */ + /** + * Patches the modifiable fields of an API key. + * The key string of the API key isn't included in the response. + * + * NOTE: Key is a global resource; hence the only supported value for + * location is `global`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.api.apikeys.v2.Key} request.key + * Required. Set the `name` field to the resource name of the API key to be + * updated. You can update only the `display_name`, `restrictions`, and + * `annotations` fields. + * @param {google.protobuf.FieldMask} request.updateMask + * The field mask specifies which fields to be updated as part of this + * request. All other fields are ignored. + * Mutable fields are: `display_name`, `restrictions`, and `annotations`. + * If an update mask is not provided, the service treats it as an implied mask + * equivalent to all allowed fields that are set on the wire. If the field + * mask has a special value "*", the service treats it equivalent to replace + * all allowed mutable fields. + * @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/v2/api_keys.update_key.js + * region_tag:apikeys_v2_generated_ApiKeys_UpdateKey_async + */ updateKey( - request?: protos.google.api.apikeys.v2.IUpdateKeyRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.api.apikeys.v2.IUpdateKeyRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; updateKey( - request: protos.google.api.apikeys.v2.IUpdateKeyRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.apikeys.v2.IUpdateKeyRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; updateKey( - request: protos.google.api.apikeys.v2.IUpdateKeyRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.apikeys.v2.IUpdateKeyRequest, + callback: Callback< + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; updateKey( - request?: protos.google.api.apikeys.v2.IUpdateKeyRequest, - 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.api.apikeys.v2.IUpdateKeyRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + 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({ - 'key.name': request.key!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'key.name': request.key!.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.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('updateKey response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('updateKey request %j', request); - return this.innerApiCalls.updateKey(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('updateKey response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .updateKey(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('updateKey response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `updateKey()`. - * @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/v2/api_keys.update_key.js - * region_tag:apikeys_v2_generated_ApiKeys_UpdateKey_async - */ - async checkUpdateKeyProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `updateKey()`. + * @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/v2/api_keys.update_key.js + * region_tag:apikeys_v2_generated_ApiKeys_UpdateKey_async + */ + async checkUpdateKeyProgress( + name: string, + ): Promise< + LROperation + > { this._log.info('updateKey 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.updateKey, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.updateKey, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.api.apikeys.v2.Key, + protos.google.protobuf.Empty + >; } -/** - * Deletes an API key. Deleted key can be retrieved within 30 days of - * deletion. Afterward, key will be purged from the project. - * - * NOTE: Key is a global resource; hence the only supported value for - * location is `global`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the API key to be deleted. - * @param {string} [request.etag] - * Optional. The etag known to the client for the expected state of the key. - * This is to be used for optimistic concurrency. - * @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/v2/api_keys.delete_key.js - * region_tag:apikeys_v2_generated_ApiKeys_DeleteKey_async - */ + /** + * Deletes an API key. Deleted key can be retrieved within 30 days of + * deletion. Afterward, key will be purged from the project. + * + * NOTE: Key is a global resource; hence the only supported value for + * location is `global`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the API key to be deleted. + * @param {string} [request.etag] + * Optional. The etag known to the client for the expected state of the key. + * This is to be used for optimistic concurrency. + * @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/v2/api_keys.delete_key.js + * region_tag:apikeys_v2_generated_ApiKeys_DeleteKey_async + */ deleteKey( - request?: protos.google.api.apikeys.v2.IDeleteKeyRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.api.apikeys.v2.IDeleteKeyRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; deleteKey( - request: protos.google.api.apikeys.v2.IDeleteKeyRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.apikeys.v2.IDeleteKeyRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; deleteKey( - request: protos.google.api.apikeys.v2.IDeleteKeyRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.apikeys.v2.IDeleteKeyRequest, + callback: Callback< + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; deleteKey( - request?: protos.google.api.apikeys.v2.IDeleteKeyRequest, - 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.api.apikeys.v2.IDeleteKeyRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + 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.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('deleteKey response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('deleteKey request %j', request); - return this.innerApiCalls.deleteKey(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('deleteKey response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .deleteKey(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('deleteKey response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `deleteKey()`. - * @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/v2/api_keys.delete_key.js - * region_tag:apikeys_v2_generated_ApiKeys_DeleteKey_async - */ - async checkDeleteKeyProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `deleteKey()`. + * @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/v2/api_keys.delete_key.js + * region_tag:apikeys_v2_generated_ApiKeys_DeleteKey_async + */ + async checkDeleteKeyProgress( + name: string, + ): Promise< + LROperation + > { this._log.info('deleteKey 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.deleteKey, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.deleteKey, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.api.apikeys.v2.Key, + protos.google.protobuf.Empty + >; } -/** - * Undeletes an API key which was deleted within 30 days. - * - * NOTE: Key is a global resource; hence the only supported value for - * location is `global`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the API key to be undeleted. - * @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/v2/api_keys.undelete_key.js - * region_tag:apikeys_v2_generated_ApiKeys_UndeleteKey_async - */ + /** + * Undeletes an API key which was deleted within 30 days. + * + * NOTE: Key is a global resource; hence the only supported value for + * location is `global`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the API key to be undeleted. + * @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/v2/api_keys.undelete_key.js + * region_tag:apikeys_v2_generated_ApiKeys_UndeleteKey_async + */ undeleteKey( - request?: protos.google.api.apikeys.v2.IUndeleteKeyRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.api.apikeys.v2.IUndeleteKeyRequest, + options?: CallOptions, + ): Promise< + [ + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; undeleteKey( - request: protos.google.api.apikeys.v2.IUndeleteKeyRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.apikeys.v2.IUndeleteKeyRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; undeleteKey( - request: protos.google.api.apikeys.v2.IUndeleteKeyRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.apikeys.v2.IUndeleteKeyRequest, + callback: Callback< + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): void; undeleteKey( - request?: protos.google.api.apikeys.v2.IUndeleteKeyRequest, - 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.api.apikeys.v2.IUndeleteKeyRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + 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.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('undeleteKey response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('undeleteKey request %j', request); - return this.innerApiCalls.undeleteKey(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('undeleteKey response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .undeleteKey(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('undeleteKey response %j', rawResponse); + return [response, rawResponse, _]; + }, + ); } -/** - * Check the status of the long running operation returned by `undeleteKey()`. - * @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/v2/api_keys.undelete_key.js - * region_tag:apikeys_v2_generated_ApiKeys_UndeleteKey_async - */ - async checkUndeleteKeyProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `undeleteKey()`. + * @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/v2/api_keys.undelete_key.js + * region_tag:apikeys_v2_generated_ApiKeys_UndeleteKey_async + */ + async checkUndeleteKeyProgress( + name: string, + ): Promise< + LROperation + > { this._log.info('undeleteKey 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.undeleteKey, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.undeleteKey, + this._gaxModule.createDefaultBackoffSettings(), + ); + return decodeOperation as LROperation< + protos.google.api.apikeys.v2.Key, + protos.google.protobuf.Empty + >; } - /** - * Lists the API keys owned by a project. The key string of the API key - * isn't included in the response. - * - * NOTE: Key is a global resource; hence the only supported value for - * location is `global`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Lists all API keys associated with this project. - * @param {number} [request.pageSize] - * Optional. Specifies the maximum number of results to be returned at a time. - * @param {string} [request.pageToken] - * Optional. Requests a specific page of results. - * @param {boolean} [request.showDeleted] - * Optional. Indicate that keys deleted in the past 30 days should also 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 Array of {@link protos.google.api.apikeys.v2.Key|Key}. - * 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 `listKeysAsync()` - * 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 API keys owned by a project. The key string of the API key + * isn't included in the response. + * + * NOTE: Key is a global resource; hence the only supported value for + * location is `global`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Lists all API keys associated with this project. + * @param {number} [request.pageSize] + * Optional. Specifies the maximum number of results to be returned at a time. + * @param {string} [request.pageToken] + * Optional. Requests a specific page of results. + * @param {boolean} [request.showDeleted] + * Optional. Indicate that keys deleted in the past 30 days should also 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 Array of {@link protos.google.api.apikeys.v2.Key|Key}. + * 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 `listKeysAsync()` + * 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. + */ listKeys( - request?: protos.google.api.apikeys.v2.IListKeysRequest, - options?: CallOptions): - Promise<[ - protos.google.api.apikeys.v2.IKey[], - protos.google.api.apikeys.v2.IListKeysRequest|null, - protos.google.api.apikeys.v2.IListKeysResponse - ]>; + request?: protos.google.api.apikeys.v2.IListKeysRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.apikeys.v2.IKey[], + protos.google.api.apikeys.v2.IListKeysRequest | null, + protos.google.api.apikeys.v2.IListKeysResponse, + ] + >; listKeys( - request: protos.google.api.apikeys.v2.IListKeysRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.api.apikeys.v2.IListKeysRequest, - protos.google.api.apikeys.v2.IListKeysResponse|null|undefined, - protos.google.api.apikeys.v2.IKey>): void; + request: protos.google.api.apikeys.v2.IListKeysRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.api.apikeys.v2.IListKeysRequest, + protos.google.api.apikeys.v2.IListKeysResponse | null | undefined, + protos.google.api.apikeys.v2.IKey + >, + ): void; listKeys( - request: protos.google.api.apikeys.v2.IListKeysRequest, - callback: PaginationCallback< - protos.google.api.apikeys.v2.IListKeysRequest, - protos.google.api.apikeys.v2.IListKeysResponse|null|undefined, - protos.google.api.apikeys.v2.IKey>): void; + request: protos.google.api.apikeys.v2.IListKeysRequest, + callback: PaginationCallback< + protos.google.api.apikeys.v2.IListKeysRequest, + protos.google.api.apikeys.v2.IListKeysResponse | null | undefined, + protos.google.api.apikeys.v2.IKey + >, + ): void; listKeys( - request?: protos.google.api.apikeys.v2.IListKeysRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.api.apikeys.v2.IListKeysRequest, - protos.google.api.apikeys.v2.IListKeysResponse|null|undefined, - protos.google.api.apikeys.v2.IKey>, - callback?: PaginationCallback< + request?: protos.google.api.apikeys.v2.IListKeysRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.api.apikeys.v2.IListKeysRequest, - protos.google.api.apikeys.v2.IListKeysResponse|null|undefined, - protos.google.api.apikeys.v2.IKey>): - Promise<[ - protos.google.api.apikeys.v2.IKey[], - protos.google.api.apikeys.v2.IListKeysRequest|null, - protos.google.api.apikeys.v2.IListKeysResponse - ]>|void { + protos.google.api.apikeys.v2.IListKeysResponse | null | undefined, + protos.google.api.apikeys.v2.IKey + >, + callback?: PaginationCallback< + protos.google.api.apikeys.v2.IListKeysRequest, + protos.google.api.apikeys.v2.IListKeysResponse | null | undefined, + protos.google.api.apikeys.v2.IKey + >, + ): Promise< + [ + protos.google.api.apikeys.v2.IKey[], + protos.google.api.apikeys.v2.IListKeysRequest | null, + protos.google.api.apikeys.v2.IListKeysResponse, + ] + > | 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.api.apikeys.v2.IListKeysRequest, - protos.google.api.apikeys.v2.IListKeysResponse|null|undefined, - protos.google.api.apikeys.v2.IKey>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.api.apikeys.v2.IListKeysRequest, + protos.google.api.apikeys.v2.IListKeysResponse | null | undefined, + protos.google.api.apikeys.v2.IKey + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listKeys values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1248,115 +1669,119 @@ export class ApiKeysClient { this._log.info('listKeys request %j', request); return this.innerApiCalls .listKeys(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.api.apikeys.v2.IKey[], - protos.google.api.apikeys.v2.IListKeysRequest|null, - protos.google.api.apikeys.v2.IListKeysResponse - ]) => { - this._log.info('listKeys values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.api.apikeys.v2.IKey[], + protos.google.api.apikeys.v2.IListKeysRequest | null, + protos.google.api.apikeys.v2.IListKeysResponse, + ]) => { + this._log.info('listKeys values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listKeys`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Lists all API keys associated with this project. - * @param {number} [request.pageSize] - * Optional. Specifies the maximum number of results to be returned at a time. - * @param {string} [request.pageToken] - * Optional. Requests a specific page of results. - * @param {boolean} [request.showDeleted] - * Optional. Indicate that keys deleted in the past 30 days should also 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 an object representing {@link protos.google.api.apikeys.v2.Key|Key} 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 `listKeysAsync()` - * 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 `listKeys`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Lists all API keys associated with this project. + * @param {number} [request.pageSize] + * Optional. Specifies the maximum number of results to be returned at a time. + * @param {string} [request.pageToken] + * Optional. Requests a specific page of results. + * @param {boolean} [request.showDeleted] + * Optional. Indicate that keys deleted in the past 30 days should also 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 an object representing {@link protos.google.api.apikeys.v2.Key|Key} 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 `listKeysAsync()` + * 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. + */ listKeysStream( - request?: protos.google.api.apikeys.v2.IListKeysRequest, - options?: CallOptions): - Transform{ + request?: protos.google.api.apikeys.v2.IListKeysRequest, + 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['listKeys']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listKeys stream %j', request); return this.descriptors.page.listKeys.createStream( this.innerApiCalls.listKeys as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listKeys`, 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. Lists all API keys associated with this project. - * @param {number} [request.pageSize] - * Optional. Specifies the maximum number of results to be returned at a time. - * @param {string} [request.pageToken] - * Optional. Requests a specific page of results. - * @param {boolean} [request.showDeleted] - * Optional. Indicate that keys deleted in the past 30 days should also be - * returned. - * @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.api.apikeys.v2.Key|Key}. 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 include:samples/generated/v2/api_keys.list_keys.js - * region_tag:apikeys_v2_generated_ApiKeys_ListKeys_async - */ + /** + * Equivalent to `listKeys`, 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. Lists all API keys associated with this project. + * @param {number} [request.pageSize] + * Optional. Specifies the maximum number of results to be returned at a time. + * @param {string} [request.pageToken] + * Optional. Requests a specific page of results. + * @param {boolean} [request.showDeleted] + * Optional. Indicate that keys deleted in the past 30 days should also be + * returned. + * @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.api.apikeys.v2.Key|Key}. 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 include:samples/generated/v2/api_keys.list_keys.js + * region_tag:apikeys_v2_generated_ApiKeys_ListKeys_async + */ listKeysAsync( - request?: protos.google.api.apikeys.v2.IListKeysRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.api.apikeys.v2.IListKeysRequest, + 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['listKeys']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listKeys iterate %j', request); return this.descriptors.page.listKeys.asyncIterate( this.innerApiCalls['listKeys'] as GaxCall, request as {}, - callSettings + callSettings, ) as 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. @@ -1399,22 +1824,22 @@ export class ApiKeysClient { protos.google.longrunning.Operation, protos.google.longrunning.GetOperationRequest, {} | 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); } /** @@ -1449,15 +1874,15 @@ export class ApiKeysClient { */ listOperationsAsync( request: protos.google.longrunning.ListOperationsRequest, - options?: gax.CallOptions + 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); } /** @@ -1491,7 +1916,7 @@ export class ApiKeysClient { * await client.cancelOperation({name: ''}); * ``` */ - cancelOperation( + cancelOperation( request: protos.google.longrunning.CancelOperationRequest, optionsOrCallback?: | gax.CallOptions @@ -1504,25 +1929,24 @@ export class ApiKeysClient { protos.google.longrunning.CancelOperationRequest, protos.google.protobuf.Empty, {} | 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); } - /** * Deletes a long-running operation. This method indicates that the client is * no longer interested in the operation result. It does not cancel the @@ -1561,22 +1985,22 @@ export class ApiKeysClient { protos.google.protobuf.Empty, protos.google.longrunning.DeleteOperationRequest, {} | 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); } @@ -1592,7 +2016,7 @@ export class ApiKeysClient { * @param {string} key * @returns {string} Resource name string. */ - keyPath(project:string,location:string,key:string) { + keyPath(project: string, location: string, key: string) { return this.pathTemplates.keyPathTemplate.render({ project: project, location: location, @@ -1640,7 +2064,7 @@ export class ApiKeysClient { * @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, @@ -1675,7 +2099,7 @@ export class ApiKeysClient { * @param {string} project * @returns {string} Resource name string. */ - projectPath(project:string) { + projectPath(project: string) { return this.pathTemplates.projectPathTemplate.render({ project: project, }); @@ -1700,7 +2124,7 @@ export class ApiKeysClient { */ close(): Promise { if (this.apiKeysStub && !this._terminated) { - return this.apiKeysStub.then(stub => { + return this.apiKeysStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1709,4 +2133,4 @@ export class ApiKeysClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-api-apikeys/src/v2/index.ts b/packages/google-api-apikeys/src/v2/index.ts index c747227d34a6..db0d76873684 100644 --- a/packages/google-api-apikeys/src/v2/index.ts +++ b/packages/google-api-apikeys/src/v2/index.ts @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {ApiKeysClient} from './api_keys_client'; +export { ApiKeysClient } from './api_keys_client'; diff --git a/packages/google-api-apikeys/system-test/fixtures/sample/src/index.ts b/packages/google-api-apikeys/system-test/fixtures/sample/src/index.ts index 12650afb003e..1a319d09fcc2 100644 --- a/packages/google-api-apikeys/system-test/fixtures/sample/src/index.ts +++ b/packages/google-api-apikeys/system-test/fixtures/sample/src/index.ts @@ -16,7 +16,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {ApiKeysClient} from '@google-cloud/apikeys'; +import { ApiKeysClient } from '@google-cloud/apikeys'; // check that the client class type name can be used function doStuffWithApiKeysClient(client: ApiKeysClient) { diff --git a/packages/google-api-apikeys/system-test/install.ts b/packages/google-api-apikeys/system-test/install.ts index 394f3362d203..ccf167042d2e 100644 --- a/packages/google-api-apikeys/system-test/install.ts +++ b/packages/google-api-apikeys/system-test/install.ts @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - ts: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/packages/google-api-apikeys/test/gapic_api_keys_v2.ts b/packages/google-api-apikeys/test/gapic_api_keys_v2.ts index 094980d2a0f0..66135b68f228 100644 --- a/packages/google-api-apikeys/test/gapic_api_keys_v2.ts +++ b/packages/google-api-apikeys/test/gapic_api_keys_v2.ts @@ -19,1787 +19,2200 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as apikeysModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf, LROperation, operationsProtos} from 'google-gax'; +import { protobuf, LROperation, operationsProtos } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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('v2.ApiKeysClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new apikeysModule.v2.ApiKeysClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'apikeys.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new apikeysModule.v2.ApiKeysClient(); - 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 = apikeysModule.v2.ApiKeysClient.servicePath; - assert.strictEqual(servicePath, 'apikeys.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = apikeysModule.v2.ApiKeysClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'apikeys.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new apikeysModule.v2.ApiKeysClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'apikeys.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new apikeysModule.v2.ApiKeysClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'apikeys.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 apikeysModule.v2.ApiKeysClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'apikeys.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 apikeysModule.v2.ApiKeysClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'apikeys.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 apikeysModule.v2.ApiKeysClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = apikeysModule.v2.ApiKeysClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new apikeysModule.v2.ApiKeysClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new apikeysModule.v2.ApiKeysClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.apiKeysStub, undefined); - await client.initialize(); - assert(client.apiKeysStub); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new apikeysModule.v2.ApiKeysClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'apikeys.googleapis.com'); + }); - it('has close method for the initialized client', done => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.apiKeysStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has universeDomain', () => { + const client = new apikeysModule.v2.ApiKeysClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('has close method for the non-initialized client', done => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.apiKeysStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = apikeysModule.v2.ApiKeysClient.servicePath; + assert.strictEqual(servicePath, 'apikeys.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = apikeysModule.v2.ApiKeysClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'apikeys.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new apikeysModule.v2.ApiKeysClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'apikeys.example.com'); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new apikeysModule.v2.ApiKeysClient({ - 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('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new apikeysModule.v2.ApiKeysClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'apikeys.example.com'); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new apikeysModule.v2.ApiKeysClient({ - 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); + 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 apikeysModule.v2.ApiKeysClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'apikeys.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 apikeysModule.v2.ApiKeysClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'apikeys.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 apikeysModule.v2.ApiKeysClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('getKey', () => { - it('invokes getKey without error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.GetKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.GetKeyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.apikeys.v2.Key() - ); - client.innerApiCalls.getKey = stubSimpleCall(expectedResponse); - const [response] = await client.getKey(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = apikeysModule.v2.ApiKeysClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes getKey without error using callback', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.GetKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.GetKeyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.apikeys.v2.Key() - ); - client.innerApiCalls.getKey = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getKey( - request, - (err?: Error|null, result?: protos.google.api.apikeys.v2.IKey|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getKey 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 apikeysModule.v2.ApiKeysClient(); + assert(client); + }); - it('invokes getKey with error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.GetKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.GetKeyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getKey = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getKey(request), expectedError); - const actualRequest = (client.innerApiCalls.getKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getKey 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 apikeysModule.v2.ApiKeysClient({ + fallback: true, + }); + assert(client); + }); - it('invokes getKey with closed client', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.GetKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.GetKeyRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getKey(request), expectedError); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.apiKeysStub, undefined); + await client.initialize(); + assert(client.apiKeysStub); }); - describe('getKeyString', () => { - it('invokes getKeyString without error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.GetKeyStringRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.GetKeyStringRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.apikeys.v2.GetKeyStringResponse() - ); - client.innerApiCalls.getKeyString = stubSimpleCall(expectedResponse); - const [response] = await client.getKeyString(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getKeyString as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getKeyString 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 apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.apiKeysStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getKeyString without error using callback', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.GetKeyStringRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.GetKeyStringRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.apikeys.v2.GetKeyStringResponse() - ); - client.innerApiCalls.getKeyString = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getKeyString( - request, - (err?: Error|null, result?: protos.google.api.apikeys.v2.IGetKeyStringResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getKeyString as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getKeyString 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 apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.apiKeysStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getKeyString with error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.GetKeyStringRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.GetKeyStringRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getKeyString = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getKeyString(request), expectedError); - const actualRequest = (client.innerApiCalls.getKeyString as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getKeyString 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 apikeysModule.v2.ApiKeysClient({ + 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 getKeyString with closed client', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.GetKeyStringRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.GetKeyStringRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getKeyString(request), expectedError); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new apikeysModule.v2.ApiKeysClient({ + 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('getKey', () => { + it('invokes getKey without error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.GetKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.GetKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.apikeys.v2.Key(), + ); + client.innerApiCalls.getKey = stubSimpleCall(expectedResponse); + const [response] = await client.getKey(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getKey as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('lookupKey', () => { - it('invokes lookupKey without error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.LookupKeyRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.api.apikeys.v2.LookupKeyResponse() - ); - client.innerApiCalls.lookupKey = stubSimpleCall(expectedResponse); - const [response] = await client.lookupKey(request); - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes getKey without error using callback', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.GetKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.GetKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.apikeys.v2.Key(), + ); + client.innerApiCalls.getKey = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getKey( + request, + ( + err?: Error | null, + result?: protos.google.api.apikeys.v2.IKey | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getKey as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes lookupKey without error using callback', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.LookupKeyRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.api.apikeys.v2.LookupKeyResponse() - ); - client.innerApiCalls.lookupKey = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.lookupKey( - request, - (err?: Error|null, result?: protos.google.api.apikeys.v2.ILookupKeyResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - }); + it('invokes getKey with error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.GetKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.GetKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getKey = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getKey(request), expectedError); + const actualRequest = (client.innerApiCalls.getKey as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes lookupKey with error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.LookupKeyRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.lookupKey = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.lookupKey(request), expectedError); - }); + it('invokes getKey with closed client', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.GetKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.GetKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getKey(request), expectedError); + }); + }); + + describe('getKeyString', () => { + it('invokes getKeyString without error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.GetKeyStringRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.GetKeyStringRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.apikeys.v2.GetKeyStringResponse(), + ); + client.innerApiCalls.getKeyString = stubSimpleCall(expectedResponse); + const [response] = await client.getKeyString(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getKeyString as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getKeyString as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes lookupKey with closed client', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.LookupKeyRequest() - ); - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.lookupKey(request), expectedError); - }); + it('invokes getKeyString without error using callback', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.GetKeyStringRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.GetKeyStringRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.apikeys.v2.GetKeyStringResponse(), + ); + client.innerApiCalls.getKeyString = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getKeyString( + request, + ( + err?: Error | null, + result?: protos.google.api.apikeys.v2.IGetKeyStringResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getKeyString as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getKeyString as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createKey', () => { - it('invokes createKey without error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.CreateKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.CreateKeyRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createKey = stubLongRunningCall(expectedResponse); - const [operation] = await client.createKey(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getKeyString with error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.GetKeyStringRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.GetKeyStringRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getKeyString = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getKeyString(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getKeyString as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getKeyString as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createKey without error using callback', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.CreateKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.CreateKeyRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createKey = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createKey( - 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.createKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getKeyString with closed client', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.GetKeyStringRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.GetKeyStringRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getKeyString(request), expectedError); + }); + }); + + describe('lookupKey', () => { + it('invokes lookupKey without error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.LookupKeyRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.api.apikeys.v2.LookupKeyResponse(), + ); + client.innerApiCalls.lookupKey = stubSimpleCall(expectedResponse); + const [response] = await client.lookupKey(request); + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createKey with call error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.CreateKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.CreateKeyRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createKey = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.createKey(request), expectedError); - const actualRequest = (client.innerApiCalls.createKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes lookupKey without error using callback', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.LookupKeyRequest(), + ); + const expectedResponse = generateSampleMessage( + new protos.google.api.apikeys.v2.LookupKeyResponse(), + ); + client.innerApiCalls.lookupKey = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.lookupKey( + request, + ( + err?: Error | null, + result?: protos.google.api.apikeys.v2.ILookupKeyResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + }); - it('invokes createKey with LRO error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.CreateKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.CreateKeyRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createKey = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.createKey(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.createKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes lookupKey with error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.LookupKeyRequest(), + ); + const expectedError = new Error('expected'); + client.innerApiCalls.lookupKey = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.lookupKey(request), expectedError); + }); - it('invokes checkCreateKeyProgress without error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - 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.checkCreateKeyProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes lookupKey with closed client', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.LookupKeyRequest(), + ); + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.lookupKey(request), expectedError); + }); + }); + + describe('createKey', () => { + it('invokes createKey without error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.CreateKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.CreateKeyRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createKey = stubLongRunningCall(expectedResponse); + const [operation] = await client.createKey(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateKeyProgress with error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - 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.checkCreateKeyProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes createKey without error using callback', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.CreateKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.CreateKeyRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.createKey = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createKey( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateKey', () => { - it('invokes updateKey without error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.UpdateKeyRequest() - ); - request.key ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.UpdateKeyRequest', ['key', 'name']); - request.key.name = defaultValue1; - const expectedHeaderRequestParams = `key.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.updateKey = stubLongRunningCall(expectedResponse); - const [operation] = await client.updateKey(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createKey with call error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.CreateKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.CreateKeyRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createKey = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.createKey(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateKey without error using callback', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.UpdateKeyRequest() - ); - request.key ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.UpdateKeyRequest', ['key', 'name']); - request.key.name = defaultValue1; - const expectedHeaderRequestParams = `key.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.updateKey = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateKey( - 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.updateKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createKey with LRO error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.CreateKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.CreateKeyRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createKey = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.createKey(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.createKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateKey with call error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.UpdateKeyRequest() - ); - request.key ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.UpdateKeyRequest', ['key', 'name']); - request.key.name = defaultValue1; - const expectedHeaderRequestParams = `key.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateKey = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.updateKey(request), expectedError); - const actualRequest = (client.innerApiCalls.updateKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkCreateKeyProgress without error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + 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.checkCreateKeyProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes updateKey with LRO error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.UpdateKeyRequest() - ); - request.key ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.UpdateKeyRequest', ['key', 'name']); - request.key.name = defaultValue1; - const expectedHeaderRequestParams = `key.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateKey = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.updateKey(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.updateKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkCreateKeyProgress with error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + 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.checkCreateKeyProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('updateKey', () => { + it('invokes updateKey without error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.UpdateKeyRequest(), + ); + request.key ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.UpdateKeyRequest', + ['key', 'name'], + ); + request.key.name = defaultValue1; + const expectedHeaderRequestParams = `key.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.updateKey = stubLongRunningCall(expectedResponse); + const [operation] = await client.updateKey(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkUpdateKeyProgress without error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - 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.checkUpdateKeyProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes updateKey without error using callback', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.UpdateKeyRequest(), + ); + request.key ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.UpdateKeyRequest', + ['key', 'name'], + ); + request.key.name = defaultValue1; + const expectedHeaderRequestParams = `key.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.updateKey = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateKey( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkUpdateKeyProgress with error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - 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.checkUpdateKeyProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes updateKey with call error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.UpdateKeyRequest(), + ); + request.key ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.UpdateKeyRequest', + ['key', 'name'], + ); + request.key.name = defaultValue1; + const expectedHeaderRequestParams = `key.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateKey = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.updateKey(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteKey', () => { - it('invokes deleteKey without error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.DeleteKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.DeleteKeyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.deleteKey = stubLongRunningCall(expectedResponse); - const [operation] = await client.deleteKey(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateKey with LRO error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.UpdateKeyRequest(), + ); + request.key ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.UpdateKeyRequest', + ['key', 'name'], + ); + request.key.name = defaultValue1; + const expectedHeaderRequestParams = `key.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateKey = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.updateKey(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.updateKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteKey without error using callback', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.DeleteKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.DeleteKeyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.deleteKey = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteKey( - 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.deleteKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkUpdateKeyProgress without error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + 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.checkUpdateKeyProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes deleteKey with call error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.DeleteKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.DeleteKeyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteKey = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.deleteKey(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkUpdateKeyProgress with error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + 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.checkUpdateKeyProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('deleteKey', () => { + it('invokes deleteKey without error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.DeleteKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.DeleteKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.deleteKey = stubLongRunningCall(expectedResponse); + const [operation] = await client.deleteKey(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteKey with LRO error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.DeleteKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.DeleteKeyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteKey = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.deleteKey(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.deleteKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteKey without error using callback', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.DeleteKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.DeleteKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.deleteKey = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteKey( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkDeleteKeyProgress without error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - 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.checkDeleteKeyProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes deleteKey with call error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.DeleteKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.DeleteKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteKey = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.deleteKey(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkDeleteKeyProgress with error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - 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.checkDeleteKeyProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes deleteKey with LRO error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.DeleteKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.DeleteKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteKey = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.deleteKey(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('undeleteKey', () => { - it('invokes undeleteKey without error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.UndeleteKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.UndeleteKeyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.undeleteKey = stubLongRunningCall(expectedResponse); - const [operation] = await client.undeleteKey(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.undeleteKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.undeleteKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkDeleteKeyProgress without error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + 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.checkDeleteKeyProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes undeleteKey without error using callback', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.UndeleteKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.UndeleteKeyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.undeleteKey = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.undeleteKey( - 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.undeleteKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.undeleteKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkDeleteKeyProgress with error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + 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.checkDeleteKeyProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('undeleteKey', () => { + it('invokes undeleteKey without error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.UndeleteKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.UndeleteKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.undeleteKey = stubLongRunningCall(expectedResponse); + const [operation] = await client.undeleteKey(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.undeleteKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.undeleteKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes undeleteKey with call error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.UndeleteKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.UndeleteKeyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.undeleteKey = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.undeleteKey(request), expectedError); - const actualRequest = (client.innerApiCalls.undeleteKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.undeleteKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes undeleteKey without error using callback', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.UndeleteKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.UndeleteKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation(), + ); + client.innerApiCalls.undeleteKey = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.undeleteKey( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + > | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const operation = (await promise) as LROperation< + protos.google.api.apikeys.v2.IKey, + protos.google.protobuf.IEmpty + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.undeleteKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.undeleteKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes undeleteKey with LRO error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.UndeleteKeyRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.UndeleteKeyRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.undeleteKey = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.undeleteKey(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.undeleteKey as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.undeleteKey as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes undeleteKey with call error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.UndeleteKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.UndeleteKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.undeleteKey = stubLongRunningCall( + undefined, + expectedError, + ); + await assert.rejects(client.undeleteKey(request), expectedError); + const actualRequest = ( + client.innerApiCalls.undeleteKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.undeleteKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkUndeleteKeyProgress without error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - 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.checkUndeleteKeyProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes undeleteKey with LRO error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.UndeleteKeyRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.UndeleteKeyRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.undeleteKey = stubLongRunningCall( + undefined, + undefined, + expectedError, + ); + const [operation] = await client.undeleteKey(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.undeleteKey as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.undeleteKey as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkUndeleteKeyProgress with error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - 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.checkUndeleteKeyProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes checkUndeleteKeyProgress without error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + 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.checkUndeleteKeyProgress( + expectedResponse.name, + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); }); - describe('listKeys', () => { - it('invokes listKeys without error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.ListKeysRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.ListKeysRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.api.apikeys.v2.Key()), - generateSampleMessage(new protos.google.api.apikeys.v2.Key()), - generateSampleMessage(new protos.google.api.apikeys.v2.Key()), - ]; - client.innerApiCalls.listKeys = stubSimpleCall(expectedResponse); - const [response] = await client.listKeys(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listKeys as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listKeys as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkUndeleteKeyProgress with error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + 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.checkUndeleteKeyProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('listKeys', () => { + it('invokes listKeys without error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.ListKeysRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.ListKeysRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.apikeys.v2.Key()), + generateSampleMessage(new protos.google.api.apikeys.v2.Key()), + generateSampleMessage(new protos.google.api.apikeys.v2.Key()), + ]; + client.innerApiCalls.listKeys = stubSimpleCall(expectedResponse); + const [response] = await client.listKeys(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listKeys as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listKeys as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listKeys without error using callback', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.ListKeysRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.ListKeysRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.api.apikeys.v2.Key()), - generateSampleMessage(new protos.google.api.apikeys.v2.Key()), - generateSampleMessage(new protos.google.api.apikeys.v2.Key()), - ]; - client.innerApiCalls.listKeys = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listKeys( - request, - (err?: Error|null, result?: protos.google.api.apikeys.v2.IKey[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listKeys as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listKeys as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listKeys without error using callback', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.ListKeysRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.ListKeysRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.apikeys.v2.Key()), + generateSampleMessage(new protos.google.api.apikeys.v2.Key()), + generateSampleMessage(new protos.google.api.apikeys.v2.Key()), + ]; + client.innerApiCalls.listKeys = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listKeys( + request, + ( + err?: Error | null, + result?: protos.google.api.apikeys.v2.IKey[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listKeys as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listKeys as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listKeys with error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.ListKeysRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.ListKeysRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listKeys = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listKeys(request), expectedError); - const actualRequest = (client.innerApiCalls.listKeys as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listKeys as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listKeys with error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.ListKeysRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.ListKeysRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listKeys = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listKeys(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listKeys as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listKeys as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listKeysStream without error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.ListKeysRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.ListKeysRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.api.apikeys.v2.Key()), - generateSampleMessage(new protos.google.api.apikeys.v2.Key()), - generateSampleMessage(new protos.google.api.apikeys.v2.Key()), - ]; - client.descriptors.page.listKeys.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listKeysStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.apikeys.v2.Key[] = []; - stream.on('data', (response: protos.google.api.apikeys.v2.Key) => { - 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.listKeys.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listKeys, request)); - assert( - (client.descriptors.page.listKeys.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listKeysStream without error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.ListKeysRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.ListKeysRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.apikeys.v2.Key()), + generateSampleMessage(new protos.google.api.apikeys.v2.Key()), + generateSampleMessage(new protos.google.api.apikeys.v2.Key()), + ]; + client.descriptors.page.listKeys.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listKeysStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.apikeys.v2.Key[] = []; + stream.on('data', (response: protos.google.api.apikeys.v2.Key) => { + 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.listKeys.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listKeys, request), + ); + assert( + (client.descriptors.page.listKeys.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listKeysStream with error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.ListKeysRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.ListKeysRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listKeys.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listKeysStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.apikeys.v2.Key[] = []; - stream.on('data', (response: protos.google.api.apikeys.v2.Key) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listKeys.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listKeys, request)); - assert( - (client.descriptors.page.listKeys.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listKeysStream with error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.ListKeysRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.ListKeysRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listKeys.createStream = stubPageStreamingCall( + undefined, + expectedError, + ); + const stream = client.listKeysStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.apikeys.v2.Key[] = []; + stream.on('data', (response: protos.google.api.apikeys.v2.Key) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listKeys.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listKeys, request), + ); + assert( + (client.descriptors.page.listKeys.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listKeys without error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.ListKeysRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.ListKeysRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.api.apikeys.v2.Key()), - generateSampleMessage(new protos.google.api.apikeys.v2.Key()), - generateSampleMessage(new protos.google.api.apikeys.v2.Key()), - ]; - client.descriptors.page.listKeys.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.api.apikeys.v2.IKey[] = []; - const iterable = client.listKeysAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listKeys.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listKeys.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listKeys without error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.ListKeysRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.ListKeysRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.apikeys.v2.Key()), + generateSampleMessage(new protos.google.api.apikeys.v2.Key()), + generateSampleMessage(new protos.google.api.apikeys.v2.Key()), + ]; + client.descriptors.page.listKeys.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.api.apikeys.v2.IKey[] = []; + const iterable = client.listKeysAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listKeys.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listKeys.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listKeys with error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.apikeys.v2.ListKeysRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.apikeys.v2.ListKeysRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listKeys.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listKeysAsync(request); - await assert.rejects(async () => { - const responses: protos.google.api.apikeys.v2.IKey[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listKeys.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listKeys.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listKeys with error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.apikeys.v2.ListKeysRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.apikeys.v2.ListKeysRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listKeys.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError, + ); + const iterable = client.listKeysAsync(request); + await assert.rejects(async () => { + const responses: protos.google.api.apikeys.v2.IKey[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listKeys.asyncIterate as SinonStub).getCall(0) + .args[1], + request, + ); + assert( + (client.descriptors.page.listKeys.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 apikeysModule.v2.ApiKeysClient({ - 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 apikeysModule.v2.ApiKeysClient({ - 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 apikeysModule.v2.ApiKeysClient({ - 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('getOperation', () => { + it('invokes getOperation without error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + 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('cancelOperation', () => { - it('invokes cancelOperation without error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - 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 apikeysModule.v2.ApiKeysClient({ - 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 apikeysModule.v2.ApiKeysClient({ - 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)); - }); + it('invokes getOperation without error using callback', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + 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)); }); - describe('deleteOperation', () => { - it('invokes deleteOperation without error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - 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 apikeysModule.v2.ApiKeysClient({ - 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 apikeysModule.v2.ApiKeysClient({ - 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 getOperation with error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + 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('listOperationsAsync', () => { - it('uses async iteration with listOperations without error', async () => { - const client = new apikeysModule.v2.ApiKeysClient({ - 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 apikeysModule.v2.ApiKeysClient({ - 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('cancelOperation', () => { + it('invokes cancelOperation without error', async () => { + const client = new apikeysModule.v2.ApiKeysClient({ + 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 apikeysModule.v2.ApiKeysClient({ + 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 apikeysModule.v2.ApiKeysClient({ + 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 apikeysModule.v2.ApiKeysClient({ + 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 apikeysModule.v2.ApiKeysClient({ + 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 apikeysModule.v2.ApiKeysClient({ + 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 apikeysModule.v2.ApiKeysClient({ + 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 apikeysModule.v2.ApiKeysClient({ + 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('key', async () => { + const fakePath = '/rendered/path/key'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + key: 'keyValue', + }; + const client = new apikeysModule.v2.ApiKeysClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.keyPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.keyPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('keyPath', () => { + const result = client.keyPath( + 'projectValue', + 'locationValue', + 'keyValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.keyPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromKeyName', () => { + const result = client.matchProjectFromKeyName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.keyPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromKeyName', () => { + const result = client.matchLocationFromKeyName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.keyPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchKeyFromKeyName', () => { + const result = client.matchKeyFromKeyName(fakePath); + assert.strictEqual(result, 'keyValue'); + assert( + (client.pathTemplates.keyPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); - describe('Path templates', () => { - - describe('key', async () => { - const fakePath = "/rendered/path/key"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - key: "keyValue", - }; - const client = new apikeysModule.v2.ApiKeysClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.keyPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.keyPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('keyPath', () => { - const result = client.keyPath("projectValue", "locationValue", "keyValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.keyPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromKeyName', () => { - const result = client.matchProjectFromKeyName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.keyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromKeyName', () => { - const result = client.matchLocationFromKeyName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.keyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchKeyFromKeyName', () => { - const result = client.matchKeyFromKeyName(fakePath); - assert.strictEqual(result, "keyValue"); - assert((client.pathTemplates.keyPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('location', async () => { - const fakePath = "/rendered/path/location"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - }; - const client = new apikeysModule.v2.ApiKeysClient({ - 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 apikeysModule.v2.ApiKeysClient({ + 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 apikeysModule.v2.ApiKeysClient({ - 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 apikeysModule.v2.ApiKeysClient({ + 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), + ); + }); }); + }); }); diff --git a/packages/google-api-apikeys/webpack.config.js b/packages/google-api-apikeys/webpack.config.js index 9dd3aa311442..59f92899befb 100644 --- a/packages/google-api-apikeys/webpack.config.js +++ b/packages/google-api-apikeys/webpack.config.js @@ -1,4 +1,4 @@ -// Copyright 2026 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/packages/google-api-cloudquotas/.eslintignore b/packages/google-api-cloudquotas/.eslintignore new file mode 100644 index 000000000000..cfc348ec4d11 --- /dev/null +++ b/packages/google-api-cloudquotas/.eslintignore @@ -0,0 +1,7 @@ +**/node_modules +**/.coverage +build/ +docs/ +protos/ +system-test/ +samples/generated/ diff --git a/packages/google-api-cloudquotas/.eslintrc.json b/packages/google-api-cloudquotas/.eslintrc.json new file mode 100644 index 000000000000..3e8d97ccb390 --- /dev/null +++ b/packages/google-api-cloudquotas/.eslintrc.json @@ -0,0 +1,4 @@ +{ + "extends": "./node_modules/gts", + "root": true +} diff --git a/packages/google-api-cloudquotas/README.md b/packages/google-api-cloudquotas/README.md index 536dbb6bbcb1..32b8b3e98c37 100644 --- a/packages/google-api-cloudquotas/README.md +++ b/packages/google-api-cloudquotas/README.md @@ -107,7 +107,7 @@ More Information: [Google Cloud Platform Launch Stages][launch_stages] ## Contributing -Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-api-cloudquotas/CONTRIBUTING.md). +Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/google-cloud-node/blob/main/CONTRIBUTING.md). Please note that this `README.md` and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`) @@ -117,7 +117,7 @@ are generated from a central template. Apache Version 2.0 -See [LICENSE](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-api-cloudquotas/LICENSE) +See [LICENSE](https://github.com/googleapis/google-cloud-node/blob/main/LICENSE) [shell_img]: https://gstatic.com/cloudssh/images/open-btn.png [projects]: https://console.cloud.google.com/project diff --git a/packages/google-api-cloudquotas/protos/protos.d.ts b/packages/google-api-cloudquotas/protos/protos.d.ts index c6f9c691b54f..2303c4318fc4 100644 --- a/packages/google-api-cloudquotas/protos/protos.d.ts +++ b/packages/google-api-cloudquotas/protos/protos.d.ts @@ -4699,6 +4699,9 @@ export namespace google { /** CommonLanguageSettings destinations */ destinations?: (google.api.ClientLibraryDestination[]|null); + + /** CommonLanguageSettings selectiveGapicGeneration */ + selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); } /** Represents a CommonLanguageSettings. */ @@ -4716,6 +4719,9 @@ export namespace google { /** CommonLanguageSettings destinations. */ public destinations: google.api.ClientLibraryDestination[]; + /** CommonLanguageSettings selectiveGapicGeneration. */ + public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + /** * Creates a new CommonLanguageSettings instance using the specified properties. * @param [properties] Properties to set @@ -5416,6 +5422,9 @@ export namespace google { /** PythonSettings common */ common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures */ + experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); } /** Represents a PythonSettings. */ @@ -5430,6 +5439,9 @@ export namespace google { /** PythonSettings common. */ public common?: (google.api.ICommonLanguageSettings|null); + /** PythonSettings experimentalFeatures. */ + public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + /** * Creates a new PythonSettings instance using the specified properties. * @param [properties] Properties to set @@ -5508,6 +5520,118 @@ 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); + + /** ExperimentalFeatures unversionedPackageDisabled */ + unversionedPackageDisabled?: (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; + + /** ExperimentalFeatures unversionedPackageDisabled. */ + public unversionedPackageDisabled: boolean; + + /** + * Creates a new ExperimentalFeatures instance using the specified properties. + * @param [properties] Properties to set + * @returns ExperimentalFeatures instance + */ + public static create(properties?: google.api.PythonSettings.IExperimentalFeatures): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Encodes the specified ExperimentalFeatures message. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @param message ExperimentalFeatures message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.PythonSettings.IExperimentalFeatures, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExperimentalFeatures message, length delimited. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @param message ExperimentalFeatures message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.PythonSettings.IExperimentalFeatures, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Verifies an ExperimentalFeatures message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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 { @@ -5834,6 +5958,9 @@ export namespace google { /** GoSettings common */ common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); } /** Represents a GoSettings. */ @@ -5848,6 +5975,9 @@ export namespace google { /** GoSettings common. */ public common?: (google.api.ICommonLanguageSettings|null); + /** GoSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + /** * Creates a new GoSettings instance using the specified properties. * @param [properties] Properties to set @@ -6172,6 +6302,109 @@ export namespace google { PACKAGE_MANAGER = 20 } + /** 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 new SelectiveGapicGeneration instance using the specified properties. + * @param [properties] Properties to set + * @returns SelectiveGapicGeneration instance + */ + public static create(properties?: google.api.ISelectiveGapicGeneration): google.api.SelectiveGapicGeneration; + + /** + * Encodes the specified SelectiveGapicGeneration message. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @param message SelectiveGapicGeneration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.ISelectiveGapicGeneration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SelectiveGapicGeneration message, length delimited. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @param message SelectiveGapicGeneration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.ISelectiveGapicGeneration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.SelectiveGapicGeneration; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.SelectiveGapicGeneration; + + /** + * Verifies a SelectiveGapicGeneration message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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. */ enum LaunchStage { LAUNCH_STAGE_UNSPECIFIED = 0, @@ -6553,6 +6786,7 @@ export namespace google { /** Edition enum. */ enum Edition { EDITION_UNKNOWN = 0, + EDITION_LEGACY = 900, EDITION_PROTO2 = 998, EDITION_PROTO3 = 999, EDITION_2023 = 1000, @@ -6583,6 +6817,9 @@ export namespace google { /** FileDescriptorProto weakDependency */ weakDependency?: (number[]|null); + /** FileDescriptorProto optionDependency */ + optionDependency?: (string[]|null); + /** FileDescriptorProto messageType */ messageType?: (google.protobuf.IDescriptorProto[]|null); @@ -6632,6 +6869,9 @@ export namespace google { /** FileDescriptorProto weakDependency. */ public weakDependency: number[]; + /** FileDescriptorProto optionDependency. */ + public optionDependency: string[]; + /** FileDescriptorProto messageType. */ public messageType: google.protobuf.IDescriptorProto[]; @@ -6766,6 +7006,9 @@ export namespace google { /** DescriptorProto reservedName */ reservedName?: (string[]|null); + + /** DescriptorProto visibility */ + visibility?: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility|null); } /** Represents a DescriptorProto. */ @@ -6807,6 +7050,9 @@ export namespace google { /** DescriptorProto reservedName. */ public reservedName: string[]; + /** DescriptorProto visibility. */ + public visibility: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility); + /** * Creates a new DescriptorProto instance using the specified properties. * @param [properties] Properties to set @@ -7654,6 +7900,9 @@ export namespace google { /** EnumDescriptorProto reservedName */ reservedName?: (string[]|null); + + /** EnumDescriptorProto visibility */ + visibility?: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility|null); } /** Represents an EnumDescriptorProto. */ @@ -7680,6 +7929,9 @@ export namespace google { /** EnumDescriptorProto reservedName. */ public reservedName: string[]; + /** EnumDescriptorProto visibility. */ + public visibility: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility); + /** * Creates a new EnumDescriptorProto instance using the specified properties. * @param [properties] Properties to set @@ -8614,6 +8866,9 @@ 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); @@ -8669,6 +8924,9 @@ 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[]; @@ -8889,6 +9147,121 @@ export namespace google { */ public static getTypeUrl(typeUrlPrefix?: string): string; } + + /** Properties of a FeatureSupport. */ + interface IFeatureSupport { + + /** FeatureSupport editionIntroduced */ + editionIntroduced?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + + /** FeatureSupport editionDeprecated */ + editionDeprecated?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + + /** FeatureSupport deprecationWarning */ + deprecationWarning?: (string|null); + + /** FeatureSupport editionRemoved */ + editionRemoved?: (google.protobuf.Edition|keyof typeof 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|keyof typeof google.protobuf.Edition); + + /** FeatureSupport editionDeprecated. */ + public editionDeprecated: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** FeatureSupport deprecationWarning. */ + public deprecationWarning: string; + + /** FeatureSupport editionRemoved. */ + public editionRemoved: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** + * Creates a new FeatureSupport instance using the specified properties. + * @param [properties] Properties to set + * @returns FeatureSupport instance + */ + public static create(properties?: google.protobuf.FieldOptions.IFeatureSupport): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Encodes the specified FeatureSupport message. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @param message FeatureSupport message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.FieldOptions.IFeatureSupport, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FeatureSupport message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @param message FeatureSupport message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.FieldOptions.IFeatureSupport, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Verifies a FeatureSupport message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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. */ @@ -9127,6 +9500,9 @@ export namespace google { /** EnumValueOptions debugRedact */ debugRedact?: (boolean|null); + /** EnumValueOptions featureSupport */ + featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); + /** EnumValueOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } @@ -9149,6 +9525,9 @@ export namespace google { /** EnumValueOptions debugRedact. */ public debugRedact: boolean; + /** EnumValueOptions featureSupport. */ + public featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); + /** EnumValueOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -9738,6 +10117,12 @@ export namespace google { /** FeatureSet jsonFormat */ jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|keyof typeof google.protobuf.FeatureSet.JsonFormat|null); + + /** FeatureSet enforceNamingStyle */ + enforceNamingStyle?: (google.protobuf.FeatureSet.EnforceNamingStyle|keyof typeof google.protobuf.FeatureSet.EnforceNamingStyle|null); + + /** FeatureSet defaultSymbolVisibility */ + defaultSymbolVisibility?: (google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|keyof typeof google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|null); } /** Represents a FeatureSet. */ @@ -9767,6 +10152,12 @@ export namespace google { /** FeatureSet jsonFormat. */ public jsonFormat: (google.protobuf.FeatureSet.JsonFormat|keyof typeof google.protobuf.FeatureSet.JsonFormat); + /** FeatureSet enforceNamingStyle. */ + public enforceNamingStyle: (google.protobuf.FeatureSet.EnforceNamingStyle|keyof typeof google.protobuf.FeatureSet.EnforceNamingStyle); + + /** FeatureSet defaultSymbolVisibility. */ + public defaultSymbolVisibility: (google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|keyof typeof google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility); + /** * Creates a new FeatureSet instance using the specified properties. * @param [properties] Properties to set @@ -9889,6 +10280,116 @@ export namespace google { ALLOW = 1, LEGACY_BEST_EFFORT = 2 } + + /** EnforceNamingStyle enum. */ + enum EnforceNamingStyle { + ENFORCE_NAMING_STYLE_UNKNOWN = 0, + STYLE2024 = 1, + STYLE_LEGACY = 2 + } + + /** Properties of a VisibilityFeature. */ + interface IVisibilityFeature { + } + + /** Represents a VisibilityFeature. */ + class VisibilityFeature implements IVisibilityFeature { + + /** + * Constructs a new VisibilityFeature. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FeatureSet.IVisibilityFeature); + + /** + * Creates a new VisibilityFeature instance using the specified properties. + * @param [properties] Properties to set + * @returns VisibilityFeature instance + */ + public static create(properties?: google.protobuf.FeatureSet.IVisibilityFeature): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Encodes the specified VisibilityFeature message. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @param message VisibilityFeature message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.FeatureSet.IVisibilityFeature, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified VisibilityFeature message, length delimited. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @param message VisibilityFeature message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.FeatureSet.IVisibilityFeature, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Verifies a VisibilityFeature message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a VisibilityFeature message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns VisibilityFeature + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Creates a plain object from a VisibilityFeature message. Also converts values to other types if specified. + * @param message VisibilityFeature + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet.VisibilityFeature, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this VisibilityFeature to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for VisibilityFeature + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace VisibilityFeature { + + /** DefaultSymbolVisibility enum. */ + enum DefaultSymbolVisibility { + DEFAULT_SYMBOL_VISIBILITY_UNKNOWN = 0, + EXPORT_ALL = 1, + EXPORT_TOP_LEVEL = 2, + LOCAL_ALL = 3, + STRICT = 4 + } + } } /** Properties of a FeatureSetDefaults. */ @@ -10008,8 +10509,11 @@ export namespace google { /** FeatureSetEditionDefault edition */ edition?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); - /** FeatureSetEditionDefault features */ - features?: (google.protobuf.IFeatureSet|null); + /** FeatureSetEditionDefault overridableFeatures */ + overridableFeatures?: (google.protobuf.IFeatureSet|null); + + /** FeatureSetEditionDefault fixedFeatures */ + fixedFeatures?: (google.protobuf.IFeatureSet|null); } /** Represents a FeatureSetEditionDefault. */ @@ -10024,8 +10528,11 @@ export namespace google { /** FeatureSetEditionDefault edition. */ public edition: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); - /** FeatureSetEditionDefault features. */ - public features?: (google.protobuf.IFeatureSet|null); + /** FeatureSetEditionDefault overridableFeatures. */ + public overridableFeatures?: (google.protobuf.IFeatureSet|null); + + /** FeatureSetEditionDefault fixedFeatures. */ + public fixedFeatures?: (google.protobuf.IFeatureSet|null); /** * Creates a new FeatureSetEditionDefault instance using the specified properties. @@ -10558,6 +11065,13 @@ export namespace google { } } + /** SymbolVisibility enum. */ + enum SymbolVisibility { + VISIBILITY_UNSET = 0, + VISIBILITY_LOCAL = 1, + VISIBILITY_EXPORT = 2 + } + /** Properties of a Duration. */ interface IDuration { diff --git a/packages/google-api-cloudquotas/protos/protos.js b/packages/google-api-cloudquotas/protos/protos.js index 5ecd68dcd06d..335b86c83c9d 100644 --- a/packages/google-api-cloudquotas/protos/protos.js +++ b/packages/google-api-cloudquotas/protos/protos.js @@ -12045,6 +12045,7 @@ * @interface ICommonLanguageSettings * @property {string|null} [referenceDocsUri] CommonLanguageSettings referenceDocsUri * @property {Array.|null} [destinations] CommonLanguageSettings destinations + * @property {google.api.ISelectiveGapicGeneration|null} [selectiveGapicGeneration] CommonLanguageSettings selectiveGapicGeneration */ /** @@ -12079,6 +12080,14 @@ */ 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 new CommonLanguageSettings instance using the specified properties. * @function create @@ -12111,6 +12120,8 @@ writer.int32(message.destinations[i]); writer.ldelim(); } + if (message.selectiveGapicGeneration != null && Object.hasOwnProperty.call(message, "selectiveGapicGeneration")) + $root.google.api.SelectiveGapicGeneration.encode(message.selectiveGapicGeneration, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); return writer; }; @@ -12162,6 +12173,10 @@ message.destinations.push(reader.int32()); break; } + case 3: { + message.selectiveGapicGeneration = $root.google.api.SelectiveGapicGeneration.decode(reader, reader.uint32()); + break; + } default: reader.skipType(tag & 7); break; @@ -12213,6 +12228,11 @@ break; } } + if (message.selectiveGapicGeneration != null && message.hasOwnProperty("selectiveGapicGeneration")) { + var error = $root.google.api.SelectiveGapicGeneration.verify(message.selectiveGapicGeneration); + if (error) + return "selectiveGapicGeneration." + error; + } return null; }; @@ -12255,6 +12275,11 @@ 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; }; @@ -12273,8 +12298,10 @@ 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) { @@ -12282,6 +12309,8 @@ 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; }; @@ -14104,6 +14133,7 @@ * @memberof google.api * @interface IPythonSettings * @property {google.api.ICommonLanguageSettings|null} [common] PythonSettings common + * @property {google.api.PythonSettings.IExperimentalFeatures|null} [experimentalFeatures] PythonSettings experimentalFeatures */ /** @@ -14129,6 +14159,14 @@ */ 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 new PythonSettings instance using the specified properties. * @function create @@ -14155,6 +14193,8 @@ writer = $Writer.create(); if (message.common != null && Object.hasOwnProperty.call(message, "common")) $root.google.api.CommonLanguageSettings.encode(message.common, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.experimentalFeatures != null && Object.hasOwnProperty.call(message, "experimentalFeatures")) + $root.google.api.PythonSettings.ExperimentalFeatures.encode(message.experimentalFeatures, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); return writer; }; @@ -14195,6 +14235,10 @@ message.common = $root.google.api.CommonLanguageSettings.decode(reader, reader.uint32()); break; } + case 2: { + message.experimentalFeatures = $root.google.api.PythonSettings.ExperimentalFeatures.decode(reader, reader.uint32()); + break; + } default: reader.skipType(tag & 7); break; @@ -14235,6 +14279,11 @@ if (error) return "common." + error; } + if (message.experimentalFeatures != null && message.hasOwnProperty("experimentalFeatures")) { + var error = $root.google.api.PythonSettings.ExperimentalFeatures.verify(message.experimentalFeatures); + if (error) + return "experimentalFeatures." + error; + } return null; }; @@ -14255,6 +14304,11 @@ 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; }; @@ -14271,10 +14325,14 @@ 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; }; @@ -14304,6 +14362,258 @@ 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 + * @property {boolean|null} [unversionedPackageDisabled] ExperimentalFeatures unversionedPackageDisabled + */ + + /** + * 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; + + /** + * ExperimentalFeatures unversionedPackageDisabled. + * @member {boolean} unversionedPackageDisabled + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @instance + */ + ExperimentalFeatures.prototype.unversionedPackageDisabled = false; + + /** + * Creates a new ExperimentalFeatures instance using the specified properties. + * @function create + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures=} [properties] Properties to set + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures instance + */ + ExperimentalFeatures.create = function create(properties) { + return new ExperimentalFeatures(properties); + }; + + /** + * Encodes the specified ExperimentalFeatures message. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @function encode + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures} message ExperimentalFeatures message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExperimentalFeatures.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.restAsyncIoEnabled != null && Object.hasOwnProperty.call(message, "restAsyncIoEnabled")) + writer.uint32(/* id 1, wireType 0 =*/8).bool(message.restAsyncIoEnabled); + if (message.protobufPythonicTypesEnabled != null && Object.hasOwnProperty.call(message, "protobufPythonicTypesEnabled")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.protobufPythonicTypesEnabled); + if (message.unversionedPackageDisabled != null && Object.hasOwnProperty.call(message, "unversionedPackageDisabled")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.unversionedPackageDisabled); + return writer; + }; + + /** + * Encodes the specified ExperimentalFeatures message, length delimited. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures} message ExperimentalFeatures message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExperimentalFeatures.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer. + * @function decode + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExperimentalFeatures.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.PythonSettings.ExperimentalFeatures(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.restAsyncIoEnabled = reader.bool(); + break; + } + case 2: { + message.protobufPythonicTypesEnabled = reader.bool(); + break; + } + case 3: { + message.unversionedPackageDisabled = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExperimentalFeatures.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ExperimentalFeatures message. + * @function verify + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExperimentalFeatures.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.restAsyncIoEnabled != null && message.hasOwnProperty("restAsyncIoEnabled")) + if (typeof message.restAsyncIoEnabled !== "boolean") + return "restAsyncIoEnabled: boolean expected"; + if (message.protobufPythonicTypesEnabled != null && message.hasOwnProperty("protobufPythonicTypesEnabled")) + if (typeof message.protobufPythonicTypesEnabled !== "boolean") + return "protobufPythonicTypesEnabled: boolean expected"; + if (message.unversionedPackageDisabled != null && message.hasOwnProperty("unversionedPackageDisabled")) + if (typeof message.unversionedPackageDisabled !== "boolean") + return "unversionedPackageDisabled: boolean expected"; + return null; + }; + + /** + * 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); + if (object.unversionedPackageDisabled != null) + message.unversionedPackageDisabled = Boolean(object.unversionedPackageDisabled); + 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; + object.unversionedPackageDisabled = false; + } + if (message.restAsyncIoEnabled != null && message.hasOwnProperty("restAsyncIoEnabled")) + object.restAsyncIoEnabled = message.restAsyncIoEnabled; + if (message.protobufPythonicTypesEnabled != null && message.hasOwnProperty("protobufPythonicTypesEnabled")) + object.protobufPythonicTypesEnabled = message.protobufPythonicTypesEnabled; + if (message.unversionedPackageDisabled != null && message.hasOwnProperty("unversionedPackageDisabled")) + object.unversionedPackageDisabled = message.unversionedPackageDisabled; + 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; })(); @@ -15180,6 +15490,7 @@ * @memberof google.api * @interface IGoSettings * @property {google.api.ICommonLanguageSettings|null} [common] GoSettings common + * @property {Object.|null} [renamedServices] GoSettings renamedServices */ /** @@ -15191,6 +15502,7 @@ * @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) @@ -15205,6 +15517,14 @@ */ GoSettings.prototype.common = null; + /** + * GoSettings renamedServices. + * @member {Object.} renamedServices + * @memberof google.api.GoSettings + * @instance + */ + GoSettings.prototype.renamedServices = $util.emptyObject; + /** * Creates a new GoSettings instance using the specified properties. * @function create @@ -15231,6 +15551,9 @@ writer = $Writer.create(); if (message.common != null && Object.hasOwnProperty.call(message, "common")) $root.google.api.CommonLanguageSettings.encode(message.common, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.renamedServices != null && Object.hasOwnProperty.call(message, "renamedServices")) + for (var keys = Object.keys(message.renamedServices), i = 0; i < keys.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.renamedServices[keys[i]]).ldelim(); return writer; }; @@ -15261,7 +15584,7 @@ GoSettings.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.GoSettings(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.GoSettings(), key, value; while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -15271,6 +15594,29 @@ message.common = $root.google.api.CommonLanguageSettings.decode(reader, reader.uint32()); break; } + case 2: { + if (message.renamedServices === $util.emptyObject) + message.renamedServices = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.renamedServices[key] = value; + break; + } default: reader.skipType(tag & 7); break; @@ -15311,6 +15657,14 @@ if (error) return "common." + error; } + if (message.renamedServices != null && message.hasOwnProperty("renamedServices")) { + if (!$util.isObject(message.renamedServices)) + return "renamedServices: object expected"; + var key = Object.keys(message.renamedServices); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.renamedServices[key[i]])) + return "renamedServices: string{k:string} expected"; + } return null; }; @@ -15331,6 +15685,13 @@ 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; }; @@ -15347,10 +15708,18 @@ 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; }; @@ -15989,30 +16358,275 @@ return values; })(); - /** - * LaunchStage enum. - * @name google.api.LaunchStage - * @enum {number} - * @property {number} LAUNCH_STAGE_UNSPECIFIED=0 LAUNCH_STAGE_UNSPECIFIED value - * @property {number} UNIMPLEMENTED=6 UNIMPLEMENTED value - * @property {number} PRELAUNCH=7 PRELAUNCH value - * @property {number} EARLY_ACCESS=1 EARLY_ACCESS value - * @property {number} ALPHA=2 ALPHA value - * @property {number} BETA=3 BETA value - * @property {number} GA=4 GA value - * @property {number} DEPRECATED=5 DEPRECATED value - */ - api.LaunchStage = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "LAUNCH_STAGE_UNSPECIFIED"] = 0; - values[valuesById[6] = "UNIMPLEMENTED"] = 6; - values[valuesById[7] = "PRELAUNCH"] = 7; - values[valuesById[1] = "EARLY_ACCESS"] = 1; - values[valuesById[2] = "ALPHA"] = 2; - values[valuesById[3] = "BETA"] = 3; - values[valuesById[4] = "GA"] = 4; - values[valuesById[5] = "DEPRECATED"] = 5; - 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 new SelectiveGapicGeneration instance using the specified properties. + * @function create + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration=} [properties] Properties to set + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration instance + */ + SelectiveGapicGeneration.create = function create(properties) { + return new SelectiveGapicGeneration(properties); + }; + + /** + * Encodes the specified SelectiveGapicGeneration message. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @function encode + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration} message SelectiveGapicGeneration message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SelectiveGapicGeneration.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.methods != null && message.methods.length) + for (var i = 0; i < message.methods.length; ++i) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.methods[i]); + if (message.generateOmittedAsInternal != null && Object.hasOwnProperty.call(message, "generateOmittedAsInternal")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.generateOmittedAsInternal); + return writer; + }; + + /** + * Encodes the specified SelectiveGapicGeneration message, length delimited. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration} message SelectiveGapicGeneration message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SelectiveGapicGeneration.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer. + * @function decode + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SelectiveGapicGeneration.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.SelectiveGapicGeneration(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.methods && message.methods.length)) + message.methods = []; + message.methods.push(reader.string()); + break; + } + case 2: { + message.generateOmittedAsInternal = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SelectiveGapicGeneration.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SelectiveGapicGeneration message. + * @function verify + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SelectiveGapicGeneration.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.methods != null && message.hasOwnProperty("methods")) { + if (!Array.isArray(message.methods)) + return "methods: array expected"; + for (var i = 0; i < message.methods.length; ++i) + if (!$util.isString(message.methods[i])) + return "methods: string[] expected"; + } + if (message.generateOmittedAsInternal != null && message.hasOwnProperty("generateOmittedAsInternal")) + if (typeof message.generateOmittedAsInternal !== "boolean") + return "generateOmittedAsInternal: boolean expected"; + return null; + }; + + /** + * 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 + * @enum {number} + * @property {number} LAUNCH_STAGE_UNSPECIFIED=0 LAUNCH_STAGE_UNSPECIFIED value + * @property {number} UNIMPLEMENTED=6 UNIMPLEMENTED value + * @property {number} PRELAUNCH=7 PRELAUNCH value + * @property {number} EARLY_ACCESS=1 EARLY_ACCESS value + * @property {number} ALPHA=2 ALPHA value + * @property {number} BETA=3 BETA value + * @property {number} GA=4 GA value + * @property {number} DEPRECATED=5 DEPRECATED value + */ + api.LaunchStage = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "LAUNCH_STAGE_UNSPECIFIED"] = 0; + values[valuesById[6] = "UNIMPLEMENTED"] = 6; + values[valuesById[7] = "PRELAUNCH"] = 7; + values[valuesById[1] = "EARLY_ACCESS"] = 1; + values[valuesById[2] = "ALPHA"] = 2; + values[valuesById[3] = "BETA"] = 3; + values[valuesById[4] = "GA"] = 4; + values[valuesById[5] = "DEPRECATED"] = 5; + return values; })(); /** @@ -16974,6 +17588,7 @@ * @name google.protobuf.Edition * @enum {number} * @property {number} EDITION_UNKNOWN=0 EDITION_UNKNOWN value + * @property {number} EDITION_LEGACY=900 EDITION_LEGACY value * @property {number} EDITION_PROTO2=998 EDITION_PROTO2 value * @property {number} EDITION_PROTO3=999 EDITION_PROTO3 value * @property {number} EDITION_2023=1000 EDITION_2023 value @@ -16988,6 +17603,7 @@ protobuf.Edition = (function() { var valuesById = {}, values = Object.create(valuesById); values[valuesById[0] = "EDITION_UNKNOWN"] = 0; + values[valuesById[900] = "EDITION_LEGACY"] = 900; values[valuesById[998] = "EDITION_PROTO2"] = 998; values[valuesById[999] = "EDITION_PROTO3"] = 999; values[valuesById[1000] = "EDITION_2023"] = 1000; @@ -17012,6 +17628,7 @@ * @property {Array.|null} [dependency] FileDescriptorProto dependency * @property {Array.|null} [publicDependency] FileDescriptorProto publicDependency * @property {Array.|null} [weakDependency] FileDescriptorProto weakDependency + * @property {Array.|null} [optionDependency] FileDescriptorProto optionDependency * @property {Array.|null} [messageType] FileDescriptorProto messageType * @property {Array.|null} [enumType] FileDescriptorProto enumType * @property {Array.|null} [service] FileDescriptorProto service @@ -17034,6 +17651,7 @@ this.dependency = []; this.publicDependency = []; this.weakDependency = []; + this.optionDependency = []; this.messageType = []; this.enumType = []; this.service = []; @@ -17084,6 +17702,14 @@ */ FileDescriptorProto.prototype.weakDependency = $util.emptyArray; + /** + * FileDescriptorProto optionDependency. + * @member {Array.} optionDependency + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.optionDependency = $util.emptyArray; + /** * FileDescriptorProto messageType. * @member {Array.} messageType @@ -17205,6 +17831,9 @@ writer.uint32(/* id 12, wireType 2 =*/98).string(message.syntax); if (message.edition != null && Object.hasOwnProperty.call(message, "edition")) writer.uint32(/* id 14, wireType 0 =*/112).int32(message.edition); + if (message.optionDependency != null && message.optionDependency.length) + for (var i = 0; i < message.optionDependency.length; ++i) + writer.uint32(/* id 15, wireType 2 =*/122).string(message.optionDependency[i]); return writer; }; @@ -17277,6 +17906,12 @@ message.weakDependency.push(reader.int32()); break; } + case 15: { + if (!(message.optionDependency && message.optionDependency.length)) + message.optionDependency = []; + message.optionDependency.push(reader.string()); + break; + } case 4: { if (!(message.messageType && message.messageType.length)) message.messageType = []; @@ -17379,6 +18014,13 @@ if (!$util.isInteger(message.weakDependency[i])) return "weakDependency: integer[] expected"; } + if (message.optionDependency != null && message.hasOwnProperty("optionDependency")) { + if (!Array.isArray(message.optionDependency)) + return "optionDependency: array expected"; + for (var i = 0; i < message.optionDependency.length; ++i) + if (!$util.isString(message.optionDependency[i])) + return "optionDependency: string[] expected"; + } if (message.messageType != null && message.hasOwnProperty("messageType")) { if (!Array.isArray(message.messageType)) return "messageType: array expected"; @@ -17433,6 +18075,7 @@ default: return "edition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -17485,6 +18128,13 @@ for (var i = 0; i < object.weakDependency.length; ++i) message.weakDependency[i] = object.weakDependency[i] | 0; } + if (object.optionDependency) { + if (!Array.isArray(object.optionDependency)) + throw TypeError(".google.protobuf.FileDescriptorProto.optionDependency: array expected"); + message.optionDependency = []; + for (var i = 0; i < object.optionDependency.length; ++i) + message.optionDependency[i] = String(object.optionDependency[i]); + } if (object.messageType) { if (!Array.isArray(object.messageType)) throw TypeError(".google.protobuf.FileDescriptorProto.messageType: array expected"); @@ -17548,6 +18198,10 @@ case 0: message.edition = 0; break; + case "EDITION_LEGACY": + case 900: + message.edition = 900; + break; case "EDITION_PROTO2": case 998: message.edition = 998; @@ -17613,6 +18267,7 @@ object.extension = []; object.publicDependency = []; object.weakDependency = []; + object.optionDependency = []; } if (options.defaults) { object.name = ""; @@ -17669,6 +18324,11 @@ 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; + if (message.optionDependency && message.optionDependency.length) { + object.optionDependency = []; + for (var j = 0; j < message.optionDependency.length; ++j) + object.optionDependency[j] = message.optionDependency[j]; + } return object; }; @@ -17717,6 +18377,7 @@ * @property {google.protobuf.IMessageOptions|null} [options] DescriptorProto options * @property {Array.|null} [reservedRange] DescriptorProto reservedRange * @property {Array.|null} [reservedName] DescriptorProto reservedName + * @property {google.protobuf.SymbolVisibility|null} [visibility] DescriptorProto visibility */ /** @@ -17822,6 +18483,14 @@ */ DescriptorProto.prototype.reservedName = $util.emptyArray; + /** + * DescriptorProto visibility. + * @member {google.protobuf.SymbolVisibility} visibility + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.visibility = 0; + /** * Creates a new DescriptorProto instance using the specified properties. * @function create @@ -17874,6 +18543,8 @@ if (message.reservedName != null && message.reservedName.length) for (var i = 0; i < message.reservedName.length; ++i) writer.uint32(/* id 10, wireType 2 =*/82).string(message.reservedName[i]); + if (message.visibility != null && Object.hasOwnProperty.call(message, "visibility")) + writer.uint32(/* id 11, wireType 0 =*/88).int32(message.visibility); return writer; }; @@ -17966,6 +18637,10 @@ message.reservedName.push(reader.string()); break; } + case 11: { + message.visibility = reader.int32(); + break; + } default: reader.skipType(tag & 7); break; @@ -18079,6 +18754,15 @@ if (!$util.isString(message.reservedName[i])) return "reservedName: string[] expected"; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + switch (message.visibility) { + default: + return "visibility: enum value expected"; + case 0: + case 1: + case 2: + break; + } return null; }; @@ -18178,6 +18862,26 @@ for (var i = 0; i < object.reservedName.length; ++i) message.reservedName[i] = String(object.reservedName[i]); } + switch (object.visibility) { + default: + if (typeof object.visibility === "number") { + message.visibility = object.visibility; + break; + } + break; + case "VISIBILITY_UNSET": + case 0: + message.visibility = 0; + break; + case "VISIBILITY_LOCAL": + case 1: + message.visibility = 1; + break; + case "VISIBILITY_EXPORT": + case 2: + message.visibility = 2; + break; + } return message; }; @@ -18207,6 +18911,7 @@ if (options.defaults) { object.name = ""; object.options = null; + object.visibility = options.enums === String ? "VISIBILITY_UNSET" : 0; } if (message.name != null && message.hasOwnProperty("name")) object.name = message.name; @@ -18252,6 +18957,8 @@ for (var j = 0; j < message.reservedName.length; ++j) object.reservedName[j] = message.reservedName[j]; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + object.visibility = options.enums === String ? $root.google.protobuf.SymbolVisibility[message.visibility] === undefined ? message.visibility : $root.google.protobuf.SymbolVisibility[message.visibility] : message.visibility; return object; }; @@ -20296,6 +21003,7 @@ * @property {google.protobuf.IEnumOptions|null} [options] EnumDescriptorProto options * @property {Array.|null} [reservedRange] EnumDescriptorProto reservedRange * @property {Array.|null} [reservedName] EnumDescriptorProto reservedName + * @property {google.protobuf.SymbolVisibility|null} [visibility] EnumDescriptorProto visibility */ /** @@ -20356,6 +21064,14 @@ */ EnumDescriptorProto.prototype.reservedName = $util.emptyArray; + /** + * EnumDescriptorProto visibility. + * @member {google.protobuf.SymbolVisibility} visibility + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.visibility = 0; + /** * Creates a new EnumDescriptorProto instance using the specified properties. * @function create @@ -20393,6 +21109,8 @@ if (message.reservedName != null && message.reservedName.length) for (var i = 0; i < message.reservedName.length; ++i) writer.uint32(/* id 5, wireType 2 =*/42).string(message.reservedName[i]); + if (message.visibility != null && Object.hasOwnProperty.call(message, "visibility")) + writer.uint32(/* id 6, wireType 0 =*/48).int32(message.visibility); return writer; }; @@ -20455,6 +21173,10 @@ message.reservedName.push(reader.string()); break; } + case 6: { + message.visibility = reader.int32(); + break; + } default: reader.skipType(tag & 7); break; @@ -20523,6 +21245,15 @@ if (!$util.isString(message.reservedName[i])) return "reservedName: string[] expected"; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + switch (message.visibility) { + default: + return "visibility: enum value expected"; + case 0: + case 1: + case 2: + break; + } return null; }; @@ -20572,6 +21303,26 @@ for (var i = 0; i < object.reservedName.length; ++i) message.reservedName[i] = String(object.reservedName[i]); } + switch (object.visibility) { + default: + if (typeof object.visibility === "number") { + message.visibility = object.visibility; + break; + } + break; + case "VISIBILITY_UNSET": + case 0: + message.visibility = 0; + break; + case "VISIBILITY_LOCAL": + case 1: + message.visibility = 1; + break; + case "VISIBILITY_EXPORT": + case 2: + message.visibility = 2; + break; + } return message; }; @@ -20596,6 +21347,7 @@ if (options.defaults) { object.name = ""; object.options = null; + object.visibility = options.enums === String ? "VISIBILITY_UNSET" : 0; } if (message.name != null && message.hasOwnProperty("name")) object.name = message.name; @@ -20616,6 +21368,8 @@ for (var j = 0; j < message.reservedName.length; ++j) object.reservedName[j] = message.reservedName[j]; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + object.visibility = options.enums === String ? $root.google.protobuf.SymbolVisibility[message.visibility] === undefined ? message.visibility : $root.google.protobuf.SymbolVisibility[message.visibility] : message.visibility; return object; }; @@ -22934,6 +23688,7 @@ * @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 @@ -23054,6 +23809,14 @@ */ 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 @@ -23128,6 +23891,8 @@ $root.google.protobuf.FieldOptions.EditionDefault.encode(message.editionDefaults[i], writer.uint32(/* id 20, wireType 2 =*/162).fork()).ldelim(); if (message.features != null && Object.hasOwnProperty.call(message, "features")) $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 21, wireType 2 =*/170).fork()).ldelim(); + if (message.featureSupport != null && Object.hasOwnProperty.call(message, "featureSupport")) + $root.google.protobuf.FieldOptions.FeatureSupport.encode(message.featureSupport, writer.uint32(/* id 22, wireType 2 =*/178).fork()).ldelim(); if (message.uninterpretedOption != null && message.uninterpretedOption.length) for (var i = 0; i < message.uninterpretedOption.length; ++i) $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); @@ -23229,6 +23994,10 @@ message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); break; } + case 22: { + message.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.decode(reader, reader.uint32()); + break; + } case 999: { if (!(message.uninterpretedOption && message.uninterpretedOption.length)) message.uninterpretedOption = []; @@ -23364,6 +24133,11 @@ if (error) return "features." + error; } + if (message.featureSupport != null && message.hasOwnProperty("featureSupport")) { + var error = $root.google.protobuf.FieldOptions.FeatureSupport.verify(message.featureSupport); + if (error) + return "featureSupport." + error; + } if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { if (!Array.isArray(message.uninterpretedOption)) return "uninterpretedOption: array expected"; @@ -23552,6 +24326,11 @@ 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"); @@ -23649,6 +24428,7 @@ 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")) @@ -23681,6 +24461,8 @@ } 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) @@ -23953,6 +24735,7 @@ default: return "edition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -23994,103 +24777,589 @@ 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; + 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 EditionDefault message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {google.protobuf.FieldOptions.EditionDefault} message EditionDefault + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EditionDefault.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.value = ""; + object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; + } + 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 EditionDefault to JSON. + * @function toJSON + * @memberof google.protobuf.FieldOptions.EditionDefault + * @instance + * @returns {Object.} JSON object + */ + EditionDefault.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * 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; + })(); + + 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 new FeatureSupport instance using the specified properties. + * @function create + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport=} [properties] Properties to set + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport instance + */ + FeatureSupport.create = function create(properties) { + return new FeatureSupport(properties); + }; + + /** + * Encodes the specified FeatureSupport message. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport} message FeatureSupport message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FeatureSupport.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.editionIntroduced != null && Object.hasOwnProperty.call(message, "editionIntroduced")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.editionIntroduced); + if (message.editionDeprecated != null && Object.hasOwnProperty.call(message, "editionDeprecated")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.editionDeprecated); + if (message.deprecationWarning != null && Object.hasOwnProperty.call(message, "deprecationWarning")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.deprecationWarning); + if (message.editionRemoved != null && Object.hasOwnProperty.call(message, "editionRemoved")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.editionRemoved); + return writer; + }; + + /** + * Encodes the specified FeatureSupport message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport} message FeatureSupport message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FeatureSupport.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FeatureSupport.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FieldOptions.FeatureSupport(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.editionIntroduced = reader.int32(); + break; + } + case 2: { + message.editionDeprecated = reader.int32(); + break; + } + case 3: { + message.deprecationWarning = reader.string(); + break; + } + case 4: { + message.editionRemoved = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FeatureSupport.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FeatureSupport message. + * @function verify + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FeatureSupport.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.editionIntroduced != null && message.hasOwnProperty("editionIntroduced")) + switch (message.editionIntroduced) { + default: + return "editionIntroduced: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + if (message.editionDeprecated != null && message.hasOwnProperty("editionDeprecated")) + switch (message.editionDeprecated) { + default: + return "editionDeprecated: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + if (message.deprecationWarning != null && message.hasOwnProperty("deprecationWarning")) + if (!$util.isString(message.deprecationWarning)) + return "deprecationWarning: string expected"; + if (message.editionRemoved != null && message.hasOwnProperty("editionRemoved")) + switch (message.editionRemoved) { + default: + return "editionRemoved: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + return null; + }; + + /** + * 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.edition = 1000; + message.editionRemoved = 1000; break; case "EDITION_2024": case 1001: - message.edition = 1001; + message.editionRemoved = 1001; break; case "EDITION_1_TEST_ONLY": case 1: - message.edition = 1; + message.editionRemoved = 1; break; case "EDITION_2_TEST_ONLY": case 2: - message.edition = 2; + message.editionRemoved = 2; break; case "EDITION_99997_TEST_ONLY": case 99997: - message.edition = 99997; + message.editionRemoved = 99997; break; case "EDITION_99998_TEST_ONLY": case 99998: - message.edition = 99998; + message.editionRemoved = 99998; break; case "EDITION_99999_TEST_ONLY": case 99999: - message.edition = 99999; + message.editionRemoved = 99999; break; case "EDITION_MAX": case 2147483647: - message.edition = 2147483647; + message.editionRemoved = 2147483647; break; } - 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 FeatureSupport message. Also converts values to other types if specified. * @function toObject - * @memberof google.protobuf.FieldOptions.EditionDefault + * @memberof google.protobuf.FieldOptions.FeatureSupport * @static - * @param {google.protobuf.FieldOptions.EditionDefault} message EditionDefault + * @param {google.protobuf.FieldOptions.FeatureSupport} message FeatureSupport * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - EditionDefault.toObject = function toObject(message, options) { + FeatureSupport.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { - object.value = ""; - object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; - } - 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; + 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 EditionDefault to JSON. + * Converts this FeatureSupport to JSON. * @function toJSON - * @memberof google.protobuf.FieldOptions.EditionDefault + * @memberof google.protobuf.FieldOptions.FeatureSupport * @instance * @returns {Object.} JSON object */ - EditionDefault.prototype.toJSON = function toJSON() { + FeatureSupport.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 FeatureSupport * @function getTypeUrl - * @memberof google.protobuf.FieldOptions.EditionDefault + * @memberof google.protobuf.FieldOptions.FeatureSupport * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - EditionDefault.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + FeatureSupport.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.protobuf.FieldOptions.EditionDefault"; + return typeUrlPrefix + "/google.protobuf.FieldOptions.FeatureSupport"; }; - return EditionDefault; + return FeatureSupport; })(); return FieldOptions; @@ -24685,6 +25954,7 @@ * @property {boolean|null} [deprecated] EnumValueOptions deprecated * @property {google.protobuf.IFeatureSet|null} [features] EnumValueOptions features * @property {boolean|null} [debugRedact] EnumValueOptions debugRedact + * @property {google.protobuf.FieldOptions.IFeatureSupport|null} [featureSupport] EnumValueOptions featureSupport * @property {Array.|null} [uninterpretedOption] EnumValueOptions uninterpretedOption */ @@ -24728,6 +25998,14 @@ */ EnumValueOptions.prototype.debugRedact = false; + /** + * EnumValueOptions featureSupport. + * @member {google.protobuf.FieldOptions.IFeatureSupport|null|undefined} featureSupport + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.featureSupport = null; + /** * EnumValueOptions uninterpretedOption. * @member {Array.} uninterpretedOption @@ -24766,6 +26044,8 @@ $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); if (message.debugRedact != null && Object.hasOwnProperty.call(message, "debugRedact")) writer.uint32(/* id 3, wireType 0 =*/24).bool(message.debugRedact); + if (message.featureSupport != null && Object.hasOwnProperty.call(message, "featureSupport")) + $root.google.protobuf.FieldOptions.FeatureSupport.encode(message.featureSupport, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); if (message.uninterpretedOption != null && message.uninterpretedOption.length) for (var i = 0; i < message.uninterpretedOption.length; ++i) $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); @@ -24817,6 +26097,10 @@ message.debugRedact = reader.bool(); break; } + case 4: { + message.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.decode(reader, reader.uint32()); + break; + } case 999: { if (!(message.uninterpretedOption && message.uninterpretedOption.length)) message.uninterpretedOption = []; @@ -24869,6 +26153,11 @@ if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) if (typeof message.debugRedact !== "boolean") return "debugRedact: boolean expected"; + if (message.featureSupport != null && message.hasOwnProperty("featureSupport")) { + var error = $root.google.protobuf.FieldOptions.FeatureSupport.verify(message.featureSupport); + if (error) + return "featureSupport." + error; + } if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { if (!Array.isArray(message.uninterpretedOption)) return "uninterpretedOption: array expected"; @@ -24902,6 +26191,11 @@ } if (object.debugRedact != null) message.debugRedact = Boolean(object.debugRedact); + if (object.featureSupport != null) { + if (typeof object.featureSupport !== "object") + throw TypeError(".google.protobuf.EnumValueOptions.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.EnumValueOptions.uninterpretedOption: array expected"); @@ -24934,6 +26228,7 @@ object.deprecated = false; object.features = null; object.debugRedact = false; + object.featureSupport = null; } if (message.deprecated != null && message.hasOwnProperty("deprecated")) object.deprecated = message.deprecated; @@ -24941,6 +26236,8 @@ object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) object.debugRedact = message.debugRedact; + 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) @@ -26380,6 +27677,8 @@ * @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 + * @property {google.protobuf.FeatureSet.EnforceNamingStyle|null} [enforceNamingStyle] FeatureSet enforceNamingStyle + * @property {google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|null} [defaultSymbolVisibility] FeatureSet defaultSymbolVisibility */ /** @@ -26445,6 +27744,22 @@ */ FeatureSet.prototype.jsonFormat = 0; + /** + * FeatureSet enforceNamingStyle. + * @member {google.protobuf.FeatureSet.EnforceNamingStyle} enforceNamingStyle + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.enforceNamingStyle = 0; + + /** + * FeatureSet defaultSymbolVisibility. + * @member {google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility} defaultSymbolVisibility + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.defaultSymbolVisibility = 0; + /** * Creates a new FeatureSet instance using the specified properties. * @function create @@ -26481,6 +27796,10 @@ writer.uint32(/* id 5, wireType 0 =*/40).int32(message.messageEncoding); if (message.jsonFormat != null && Object.hasOwnProperty.call(message, "jsonFormat")) writer.uint32(/* id 6, wireType 0 =*/48).int32(message.jsonFormat); + if (message.enforceNamingStyle != null && Object.hasOwnProperty.call(message, "enforceNamingStyle")) + writer.uint32(/* id 7, wireType 0 =*/56).int32(message.enforceNamingStyle); + if (message.defaultSymbolVisibility != null && Object.hasOwnProperty.call(message, "defaultSymbolVisibility")) + writer.uint32(/* id 8, wireType 0 =*/64).int32(message.defaultSymbolVisibility); return writer; }; @@ -26541,6 +27860,14 @@ message.jsonFormat = reader.int32(); break; } + case 7: { + message.enforceNamingStyle = reader.int32(); + break; + } + case 8: { + message.defaultSymbolVisibility = reader.int32(); + break; + } default: reader.skipType(tag & 7); break; @@ -26631,6 +27958,26 @@ case 2: break; } + if (message.enforceNamingStyle != null && message.hasOwnProperty("enforceNamingStyle")) + switch (message.enforceNamingStyle) { + default: + return "enforceNamingStyle: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.defaultSymbolVisibility != null && message.hasOwnProperty("defaultSymbolVisibility")) + switch (message.defaultSymbolVisibility) { + default: + return "defaultSymbolVisibility: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + break; + } return null; }; @@ -26770,6 +28117,54 @@ message.jsonFormat = 2; break; } + switch (object.enforceNamingStyle) { + default: + if (typeof object.enforceNamingStyle === "number") { + message.enforceNamingStyle = object.enforceNamingStyle; + break; + } + break; + case "ENFORCE_NAMING_STYLE_UNKNOWN": + case 0: + message.enforceNamingStyle = 0; + break; + case "STYLE2024": + case 1: + message.enforceNamingStyle = 1; + break; + case "STYLE_LEGACY": + case 2: + message.enforceNamingStyle = 2; + break; + } + switch (object.defaultSymbolVisibility) { + default: + if (typeof object.defaultSymbolVisibility === "number") { + message.defaultSymbolVisibility = object.defaultSymbolVisibility; + break; + } + break; + case "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN": + case 0: + message.defaultSymbolVisibility = 0; + break; + case "EXPORT_ALL": + case 1: + message.defaultSymbolVisibility = 1; + break; + case "EXPORT_TOP_LEVEL": + case 2: + message.defaultSymbolVisibility = 2; + break; + case "LOCAL_ALL": + case 3: + message.defaultSymbolVisibility = 3; + break; + case "STRICT": + case 4: + message.defaultSymbolVisibility = 4; + break; + } return message; }; @@ -26793,6 +28188,8 @@ 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; + object.enforceNamingStyle = options.enums === String ? "ENFORCE_NAMING_STYLE_UNKNOWN" : 0; + object.defaultSymbolVisibility = options.enums === String ? "DEFAULT_SYMBOL_VISIBILITY_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; @@ -26806,6 +28203,10 @@ 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; + if (message.enforceNamingStyle != null && message.hasOwnProperty("enforceNamingStyle")) + object.enforceNamingStyle = options.enums === String ? $root.google.protobuf.FeatureSet.EnforceNamingStyle[message.enforceNamingStyle] === undefined ? message.enforceNamingStyle : $root.google.protobuf.FeatureSet.EnforceNamingStyle[message.enforceNamingStyle] : message.enforceNamingStyle; + if (message.defaultSymbolVisibility != null && message.hasOwnProperty("defaultSymbolVisibility")) + object.defaultSymbolVisibility = options.enums === String ? $root.google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility[message.defaultSymbolVisibility] === undefined ? message.defaultSymbolVisibility : $root.google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility[message.defaultSymbolVisibility] : message.defaultSymbolVisibility; return object; }; @@ -26933,6 +28334,219 @@ return values; })(); + /** + * EnforceNamingStyle enum. + * @name google.protobuf.FeatureSet.EnforceNamingStyle + * @enum {number} + * @property {number} ENFORCE_NAMING_STYLE_UNKNOWN=0 ENFORCE_NAMING_STYLE_UNKNOWN value + * @property {number} STYLE2024=1 STYLE2024 value + * @property {number} STYLE_LEGACY=2 STYLE_LEGACY value + */ + FeatureSet.EnforceNamingStyle = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ENFORCE_NAMING_STYLE_UNKNOWN"] = 0; + values[valuesById[1] = "STYLE2024"] = 1; + values[valuesById[2] = "STYLE_LEGACY"] = 2; + return values; + })(); + + FeatureSet.VisibilityFeature = (function() { + + /** + * Properties of a VisibilityFeature. + * @memberof google.protobuf.FeatureSet + * @interface IVisibilityFeature + */ + + /** + * Constructs a new VisibilityFeature. + * @memberof google.protobuf.FeatureSet + * @classdesc Represents a VisibilityFeature. + * @implements IVisibilityFeature + * @constructor + * @param {google.protobuf.FeatureSet.IVisibilityFeature=} [properties] Properties to set + */ + function VisibilityFeature(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 new VisibilityFeature instance using the specified properties. + * @function create + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature=} [properties] Properties to set + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature instance + */ + VisibilityFeature.create = function create(properties) { + return new VisibilityFeature(properties); + }; + + /** + * Encodes the specified VisibilityFeature message. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature} message VisibilityFeature message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + VisibilityFeature.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + return writer; + }; + + /** + * Encodes the specified VisibilityFeature message, length delimited. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature} message VisibilityFeature message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + VisibilityFeature.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + VisibilityFeature.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FeatureSet.VisibilityFeature(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + VisibilityFeature.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a VisibilityFeature message. + * @function verify + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + VisibilityFeature.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + return null; + }; + + /** + * Creates a VisibilityFeature message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + */ + VisibilityFeature.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FeatureSet.VisibilityFeature) + return object; + return new $root.google.protobuf.FeatureSet.VisibilityFeature(); + }; + + /** + * Creates a plain object from a VisibilityFeature message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.VisibilityFeature} message VisibilityFeature + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + VisibilityFeature.toObject = function toObject() { + return {}; + }; + + /** + * Converts this VisibilityFeature to JSON. + * @function toJSON + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @instance + * @returns {Object.} JSON object + */ + VisibilityFeature.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for VisibilityFeature + * @function getTypeUrl + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + VisibilityFeature.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FeatureSet.VisibilityFeature"; + }; + + /** + * DefaultSymbolVisibility enum. + * @name google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility + * @enum {number} + * @property {number} DEFAULT_SYMBOL_VISIBILITY_UNKNOWN=0 DEFAULT_SYMBOL_VISIBILITY_UNKNOWN value + * @property {number} EXPORT_ALL=1 EXPORT_ALL value + * @property {number} EXPORT_TOP_LEVEL=2 EXPORT_TOP_LEVEL value + * @property {number} LOCAL_ALL=3 LOCAL_ALL value + * @property {number} STRICT=4 STRICT value + */ + VisibilityFeature.DefaultSymbolVisibility = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN"] = 0; + values[valuesById[1] = "EXPORT_ALL"] = 1; + values[valuesById[2] = "EXPORT_TOP_LEVEL"] = 2; + values[valuesById[3] = "LOCAL_ALL"] = 3; + values[valuesById[4] = "STRICT"] = 4; + return values; + })(); + + return VisibilityFeature; + })(); + return FeatureSet; })(); @@ -27117,6 +28731,7 @@ default: return "minimumEdition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -27134,6 +28749,7 @@ default: return "maximumEdition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -27182,6 +28798,10 @@ case 0: message.minimumEdition = 0; break; + case "EDITION_LEGACY": + case 900: + message.minimumEdition = 900; + break; case "EDITION_PROTO2": case 998: message.minimumEdition = 998; @@ -27234,6 +28854,10 @@ case 0: message.maximumEdition = 0; break; + case "EDITION_LEGACY": + case 900: + message.maximumEdition = 900; + break; case "EDITION_PROTO2": case 998: message.maximumEdition = 998; @@ -27342,7 +28966,8 @@ * @memberof google.protobuf.FeatureSetDefaults * @interface IFeatureSetEditionDefault * @property {google.protobuf.Edition|null} [edition] FeatureSetEditionDefault edition - * @property {google.protobuf.IFeatureSet|null} [features] FeatureSetEditionDefault features + * @property {google.protobuf.IFeatureSet|null} [overridableFeatures] FeatureSetEditionDefault overridableFeatures + * @property {google.protobuf.IFeatureSet|null} [fixedFeatures] FeatureSetEditionDefault fixedFeatures */ /** @@ -27369,12 +28994,20 @@ FeatureSetEditionDefault.prototype.edition = 0; /** - * FeatureSetEditionDefault features. - * @member {google.protobuf.IFeatureSet|null|undefined} features + * 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 * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault * @instance */ - FeatureSetEditionDefault.prototype.features = null; + FeatureSetEditionDefault.prototype.fixedFeatures = null; /** * Creates a new FeatureSetEditionDefault instance using the specified properties. @@ -27400,10 +29033,12 @@ FeatureSetEditionDefault.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); - if (message.features != null && Object.hasOwnProperty.call(message, "features")) - $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); if (message.edition != null && Object.hasOwnProperty.call(message, "edition")) writer.uint32(/* id 3, wireType 0 =*/24).int32(message.edition); + if (message.overridableFeatures != null && Object.hasOwnProperty.call(message, "overridableFeatures")) + $root.google.protobuf.FeatureSet.encode(message.overridableFeatures, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.fixedFeatures != null && Object.hasOwnProperty.call(message, "fixedFeatures")) + $root.google.protobuf.FeatureSet.encode(message.fixedFeatures, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); return writer; }; @@ -27444,8 +29079,12 @@ message.edition = reader.int32(); break; } - case 2: { - message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + case 4: { + message.overridableFeatures = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + break; + } + case 5: { + message.fixedFeatures = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); break; } default: @@ -27488,6 +29127,7 @@ default: return "edition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -27500,10 +29140,15 @@ case 2147483647: break; } - if (message.features != null && message.hasOwnProperty("features")) { - var error = $root.google.protobuf.FeatureSet.verify(message.features); + if (message.overridableFeatures != null && message.hasOwnProperty("overridableFeatures")) { + var error = $root.google.protobuf.FeatureSet.verify(message.overridableFeatures); + if (error) + return "overridableFeatures." + error; + } + if (message.fixedFeatures != null && message.hasOwnProperty("fixedFeatures")) { + var error = $root.google.protobuf.FeatureSet.verify(message.fixedFeatures); if (error) - return "features." + error; + return "fixedFeatures." + error; } return null; }; @@ -27531,6 +29176,10 @@ case 0: message.edition = 0; break; + case "EDITION_LEGACY": + case 900: + message.edition = 900; + break; case "EDITION_PROTO2": case 998: message.edition = 998; @@ -27572,10 +29221,15 @@ message.edition = 2147483647; break; } - 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); + 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); } return message; }; @@ -27594,13 +29248,16 @@ 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; }; @@ -28815,6 +30472,22 @@ return GeneratedCodeInfo; })(); + /** + * SymbolVisibility enum. + * @name google.protobuf.SymbolVisibility + * @enum {number} + * @property {number} VISIBILITY_UNSET=0 VISIBILITY_UNSET value + * @property {number} VISIBILITY_LOCAL=1 VISIBILITY_LOCAL value + * @property {number} VISIBILITY_EXPORT=2 VISIBILITY_EXPORT value + */ + protobuf.SymbolVisibility = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "VISIBILITY_UNSET"] = 0; + values[valuesById[1] = "VISIBILITY_LOCAL"] = 1; + values[valuesById[2] = "VISIBILITY_EXPORT"] = 2; + return values; + })(); + protobuf.Duration = (function() { /** diff --git a/packages/google-api-cloudquotas/protos/protos.json b/packages/google-api-cloudquotas/protos/protos.json index 9dd841a8fb30..cc8d0aafaa6d 100644 --- a/packages/google-api-cloudquotas/protos/protos.json +++ b/packages/google-api-cloudquotas/protos/protos.json @@ -8,8 +8,7 @@ "java_multiple_files": true, "java_outer_classname": "ResourceProto", "java_package": "com.google.api", - "objc_class_prefix": "GAPI", - "cc_enable_arenas": true + "objc_class_prefix": "GAPI" }, "nested": { "cloudquotas": { @@ -1653,6 +1652,10 @@ "rule": "repeated", "type": "ClientLibraryDestination", "id": 2 + }, + "selectiveGapicGeneration": { + "type": "SelectiveGapicGeneration", + "id": 3 } } }, @@ -1793,6 +1796,28 @@ "common": { "type": "CommonLanguageSettings", "id": 1 + }, + "experimentalFeatures": { + "type": "ExperimentalFeatures", + "id": 2 + } + }, + "nested": { + "ExperimentalFeatures": { + "fields": { + "restAsyncIoEnabled": { + "type": "bool", + "id": 1 + }, + "protobufPythonicTypesEnabled": { + "type": "bool", + "id": 2 + }, + "unversionedPackageDisabled": { + "type": "bool", + "id": 3 + } + } } } }, @@ -1850,6 +1875,11 @@ "common": { "type": "CommonLanguageSettings", "id": 1 + }, + "renamedServices": { + "keyType": "string", + "type": "string", + "id": 2 } } }, @@ -1911,6 +1941,19 @@ "PACKAGE_MANAGER": 20 } }, + "SelectiveGapicGeneration": { + "fields": { + "methods": { + "rule": "repeated", + "type": "string", + "id": 1 + }, + "generateOmittedAsInternal": { + "type": "bool", + "id": 2 + } + } + }, "LaunchStage": { "values": { "LAUNCH_STAGE_UNSPECIFIED": 0, @@ -2043,12 +2086,19 @@ "type": "FileDescriptorProto", "id": 1 } - } + }, + "extensions": [ + [ + 536000000, + 536000000 + ] + ] }, "Edition": { "edition": "proto2", "values": { "EDITION_UNKNOWN": 0, + "EDITION_LEGACY": 900, "EDITION_PROTO2": 998, "EDITION_PROTO3": 999, "EDITION_2023": 1000, @@ -2087,6 +2137,11 @@ "type": "int32", "id": 11 }, + "optionDependency": { + "rule": "repeated", + "type": "string", + "id": 15 + }, "messageType": { "rule": "repeated", "type": "DescriptorProto", @@ -2175,6 +2230,10 @@ "rule": "repeated", "type": "string", "id": 10 + }, + "visibility": { + "type": "SymbolVisibility", + "id": 11 } }, "nested": { @@ -2400,6 +2459,10 @@ "rule": "repeated", "type": "string", "id": 5 + }, + "visibility": { + "type": "SymbolVisibility", + "id": 6 } }, "nested": { @@ -2450,7 +2513,14 @@ "type": "ServiceOptions", "id": 3 } - } + }, + "reserved": [ + [ + 4, + 4 + ], + "stream" + ] }, "MethodDescriptorProto": { "edition": "proto2", @@ -2614,6 +2684,7 @@ 42, 42 ], + "php_generic_services", [ 38, 38 @@ -2749,7 +2820,8 @@ "type": "bool", "id": 10, "options": { - "default": false + "default": false, + "deprecated": true } }, "debugRedact": { @@ -2777,6 +2849,10 @@ "type": "FeatureSet", "id": 21 }, + "featureSupport": { + "type": "FeatureSupport", + "id": 22 + }, "uninterpretedOption": { "rule": "repeated", "type": "UninterpretedOption", @@ -2846,6 +2922,26 @@ "id": 2 } } + }, + "FeatureSupport": { + "fields": { + "editionIntroduced": { + "type": "Edition", + "id": 1 + }, + "editionDeprecated": { + "type": "Edition", + "id": 2 + }, + "deprecationWarning": { + "type": "string", + "id": 3 + }, + "editionRemoved": { + "type": "Edition", + "id": 4 + } + } } } }, @@ -2934,6 +3030,10 @@ "default": false } }, + "featureSupport": { + "type": "FieldOptions.FeatureSupport", + "id": 4 + }, "uninterpretedOption": { "rule": "repeated", "type": "UninterpretedOption", @@ -3076,6 +3176,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_2023", "edition_defaults.value": "EXPLICIT" } @@ -3086,6 +3187,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "OPEN" } @@ -3096,6 +3198,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "PACKED" } @@ -3106,6 +3209,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "VERIFY" } @@ -3116,7 +3220,8 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", - "edition_defaults.edition": "EDITION_PROTO2", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_LEGACY", "edition_defaults.value": "LENGTH_PREFIXED" } }, @@ -3126,27 +3231,38 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "ALLOW" } + }, + "enforceNamingStyle": { + "type": "EnforceNamingStyle", + "id": 7, + "options": { + "retention": "RETENTION_SOURCE", + "targets": "TARGET_TYPE_METHOD", + "feature_support.edition_introduced": "EDITION_2024", + "edition_defaults.edition": "EDITION_2024", + "edition_defaults.value": "STYLE2024" + } + }, + "defaultSymbolVisibility": { + "type": "VisibilityFeature.DefaultSymbolVisibility", + "id": 8, + "options": { + "retention": "RETENTION_SOURCE", + "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2024", + "edition_defaults.edition": "EDITION_2024", + "edition_defaults.value": "EXPORT_TOP_LEVEL" + } } }, "extensions": [ [ 1000, - 1000 - ], - [ - 1001, - 1001 - ], - [ - 1002, - 1002 - ], - [ - 9990, - 9990 + 9994 ], [ 9995, @@ -3191,7 +3307,13 @@ "UTF8_VALIDATION_UNKNOWN": 0, "VERIFY": 2, "NONE": 3 - } + }, + "reserved": [ + [ + 1, + 1 + ] + ] }, "MessageEncoding": { "values": { @@ -3206,6 +3328,33 @@ "ALLOW": 1, "LEGACY_BEST_EFFORT": 2 } + }, + "EnforceNamingStyle": { + "values": { + "ENFORCE_NAMING_STYLE_UNKNOWN": 0, + "STYLE2024": 1, + "STYLE_LEGACY": 2 + } + }, + "VisibilityFeature": { + "fields": {}, + "reserved": [ + [ + 1, + 536870911 + ] + ], + "nested": { + "DefaultSymbolVisibility": { + "values": { + "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN": 0, + "EXPORT_ALL": 1, + "EXPORT_TOP_LEVEL": 2, + "LOCAL_ALL": 3, + "STRICT": 4 + } + } + } } } }, @@ -3233,11 +3382,26 @@ "type": "Edition", "id": 3 }, - "features": { + "overridableFeatures": { "type": "FeatureSet", - "id": 2 + "id": 4 + }, + "fixedFeatures": { + "type": "FeatureSet", + "id": 5 } - } + }, + "reserved": [ + [ + 1, + 1 + ], + [ + 2, + 2 + ], + "features" + ] } } }, @@ -3250,6 +3414,12 @@ "id": 1 } }, + "extensions": [ + [ + 536000000, + 536000000 + ] + ], "nested": { "Location": { "fields": { @@ -3335,6 +3505,14 @@ } } }, + "SymbolVisibility": { + "edition": "proto2", + "values": { + "VISIBILITY_UNSET": 0, + "VISIBILITY_LOCAL": 1, + "VISIBILITY_EXPORT": 2 + } + }, "Duration": { "fields": { "seconds": { diff --git a/packages/google-api-cloudquotas/samples/generated/v1/snippet_metadata_google.api.cloudquotas.v1.json b/packages/google-api-cloudquotas/samples/generated/v1/snippet_metadata_google.api.cloudquotas.v1.json index 86379c255264..6eeb5a35aa3b 100644 --- a/packages/google-api-cloudquotas/samples/generated/v1/snippet_metadata_google.api.cloudquotas.v1.json +++ b/packages/google-api-cloudquotas/samples/generated/v1/snippet_metadata_google.api.cloudquotas.v1.json @@ -1,7 +1,7 @@ { "clientLibrary": { "name": "nodejs-cloudquotas", - "version": "2.3.0", + "version": "0.1.0", "language": "TYPESCRIPT", "apis": [ { diff --git a/packages/google-api-cloudquotas/samples/generated/v1beta/snippet_metadata_google.api.cloudquotas.v1beta.json b/packages/google-api-cloudquotas/samples/generated/v1beta/snippet_metadata_google.api.cloudquotas.v1beta.json index 422129620c13..b7a3216bcfaa 100644 --- a/packages/google-api-cloudquotas/samples/generated/v1beta/snippet_metadata_google.api.cloudquotas.v1beta.json +++ b/packages/google-api-cloudquotas/samples/generated/v1beta/snippet_metadata_google.api.cloudquotas.v1beta.json @@ -1,7 +1,7 @@ { "clientLibrary": { "name": "nodejs-cloudquotas", - "version": "2.3.0", + "version": "0.1.0", "language": "TYPESCRIPT", "apis": [ { diff --git a/packages/google-api-cloudquotas/src/v1/cloud_quotas_client.ts b/packages/google-api-cloudquotas/src/v1/cloud_quotas_client.ts index b39ba27ae82c..00b0187c3894 100644 --- a/packages/google-api-cloudquotas/src/v1/cloud_quotas_client.ts +++ b/packages/google-api-cloudquotas/src/v1/cloud_quotas_client.ts @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -50,7 +57,7 @@ export class CloudQuotasClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('cloudquotas'); @@ -63,9 +70,9 @@ export class CloudQuotasClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - cloudQuotasStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + cloudQuotasStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of CloudQuotasClient. @@ -106,21 +113,42 @@ export class CloudQuotasClient { * const client = new CloudQuotasClient({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 CloudQuotasClient; - 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 = 'cloudquotas.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -145,7 +173,7 @@ export class CloudQuotasClient { 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,10 +187,7 @@ export class CloudQuotasClient { } // 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 { @@ -183,46 +208,61 @@ export class CloudQuotasClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { - folderLocationQuotaPreferencePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/locations/{location}/quotaPreferences/{quota_preference}' - ), - folderLocationServiceQuotaInfoPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/locations/{location}/services/{service}/quotaInfos/{quota_info}' - ), - organizationLocationQuotaPreferencePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/locations/{location}/quotaPreferences/{quota_preference}' - ), - organizationLocationServiceQuotaInfoPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/locations/{location}/services/{service}/quotaInfos/{quota_info}' - ), + folderLocationQuotaPreferencePathTemplate: + new this._gaxModule.PathTemplate( + 'folders/{folder}/locations/{location}/quotaPreferences/{quota_preference}', + ), + folderLocationServiceQuotaInfoPathTemplate: + new this._gaxModule.PathTemplate( + 'folders/{folder}/locations/{location}/services/{service}/quotaInfos/{quota_info}', + ), + organizationLocationQuotaPreferencePathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/locations/{location}/quotaPreferences/{quota_preference}', + ), + organizationLocationServiceQuotaInfoPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/locations/{location}/services/{service}/quotaInfos/{quota_info}', + ), projectLocationPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}' - ), - projectLocationQuotaPreferencePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/quotaPreferences/{quota_preference}' + 'projects/{project}/locations/{location}', ), + projectLocationQuotaPreferencePathTemplate: + new this._gaxModule.PathTemplate( + 'projects/{project}/locations/{location}/quotaPreferences/{quota_preference}', + ), projectLocationServicePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/services/{service}' - ), - projectLocationServiceQuotaInfoPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/services/{service}/quotaInfos/{quota_info}' + 'projects/{project}/locations/{location}/services/{service}', ), + projectLocationServiceQuotaInfoPathTemplate: + new this._gaxModule.PathTemplate( + 'projects/{project}/locations/{location}/services/{service}/quotaInfos/{quota_info}', + ), }; // 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 = { - listQuotaInfos: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'quotaInfos'), - listQuotaPreferences: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'quotaPreferences') + listQuotaInfos: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'quotaInfos', + ), + listQuotaPreferences: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'quotaPreferences', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.api.cloudquotas.v1.CloudQuotas', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.api.cloudquotas.v1.CloudQuotas', + 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 @@ -253,37 +293,47 @@ export class CloudQuotasClient { // Put together the "service stub" for // google.api.cloudquotas.v1.CloudQuotas. this.cloudQuotasStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.api.cloudquotas.v1.CloudQuotas') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.api.cloudquotas.v1.CloudQuotas', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.api.cloudquotas.v1.CloudQuotas, - 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 cloudQuotasStubMethods = - ['listQuotaInfos', 'getQuotaInfo', 'listQuotaPreferences', 'getQuotaPreference', 'createQuotaPreference', 'updateQuotaPreference']; + const cloudQuotasStubMethods = [ + 'listQuotaInfos', + 'getQuotaInfo', + 'listQuotaPreferences', + 'getQuotaPreference', + 'createQuotaPreference', + 'updateQuotaPreference', + ]; for (const methodName of cloudQuotasStubMethods) { const callPromise = this.cloudQuotasStub.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] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -298,8 +348,14 @@ export class CloudQuotasClient { * @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 'cloudquotas.googleapis.com'; } @@ -310,8 +366,14 @@ export class CloudQuotasClient { * @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 'cloudquotas.googleapis.com'; } @@ -342,9 +404,7 @@ export class CloudQuotasClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -353,8 +413,9 @@ export class CloudQuotasClient { * 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; @@ -365,504 +426,704 @@ export class CloudQuotasClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Retrieve the QuotaInfo of a quota for a project, folder or organization. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the quota info. - * - * An example name: - * `projects/123/locations/global/services/compute.googleapis.com/quotaInfos/CpusPerProjectPerRegion` - * @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.api.cloudquotas.v1.QuotaInfo|QuotaInfo}. - * 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/cloud_quotas.get_quota_info.js - * region_tag:cloudquotas_v1_generated_CloudQuotas_GetQuotaInfo_async - */ + /** + * Retrieve the QuotaInfo of a quota for a project, folder or organization. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the quota info. + * + * An example name: + * `projects/123/locations/global/services/compute.googleapis.com/quotaInfos/CpusPerProjectPerRegion` + * @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.api.cloudquotas.v1.QuotaInfo|QuotaInfo}. + * 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/cloud_quotas.get_quota_info.js + * region_tag:cloudquotas_v1_generated_CloudQuotas_GetQuotaInfo_async + */ getQuotaInfo( - request?: protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest, - options?: CallOptions): - Promise<[ - protos.google.api.cloudquotas.v1.IQuotaInfo, - protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest|undefined, {}|undefined - ]>; + request?: protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.cloudquotas.v1.IQuotaInfo, + protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest | undefined, + {} | undefined, + ] + >; getQuotaInfo( - request: protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest, - options: CallOptions, - callback: Callback< - protos.google.api.cloudquotas.v1.IQuotaInfo, - protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest, + options: CallOptions, + callback: Callback< + protos.google.api.cloudquotas.v1.IQuotaInfo, + protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest | null | undefined, + {} | null | undefined + >, + ): void; getQuotaInfo( - request: protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest, - callback: Callback< - protos.google.api.cloudquotas.v1.IQuotaInfo, - protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest, + callback: Callback< + protos.google.api.cloudquotas.v1.IQuotaInfo, + protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest | null | undefined, + {} | null | undefined + >, + ): void; getQuotaInfo( - request?: protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.api.cloudquotas.v1.IQuotaInfo, - protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.cloudquotas.v1.IQuotaInfo, - protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.cloudquotas.v1.IQuotaInfo, - protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest|undefined, {}|undefined - ]>|void { + | protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.cloudquotas.v1.IQuotaInfo, + protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.cloudquotas.v1.IQuotaInfo, + protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest | 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('getQuotaInfo request %j', request); - const wrappedCallback: Callback< - protos.google.api.cloudquotas.v1.IQuotaInfo, - protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.cloudquotas.v1.IQuotaInfo, + | protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getQuotaInfo response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getQuotaInfo(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.cloudquotas.v1.IQuotaInfo, - protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest|undefined, - {}|undefined - ]) => { - this._log.info('getQuotaInfo response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getQuotaInfo(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.cloudquotas.v1.IQuotaInfo, + protos.google.api.cloudquotas.v1.IGetQuotaInfoRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getQuotaInfo response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets details of a single QuotaPreference. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Name of the resource - * - * Example name: - * `projects/123/locations/global/quota_preferences/my-config-for-us-east1` - * @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.api.cloudquotas.v1.QuotaPreference|QuotaPreference}. - * 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/cloud_quotas.get_quota_preference.js - * region_tag:cloudquotas_v1_generated_CloudQuotas_GetQuotaPreference_async - */ + /** + * Gets details of a single QuotaPreference. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Name of the resource + * + * Example name: + * `projects/123/locations/global/quota_preferences/my-config-for-us-east1` + * @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.api.cloudquotas.v1.QuotaPreference|QuotaPreference}. + * 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/cloud_quotas.get_quota_preference.js + * region_tag:cloudquotas_v1_generated_CloudQuotas_GetQuotaPreference_async + */ getQuotaPreference( - request?: protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest, - options?: CallOptions): - Promise<[ - protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest|undefined, {}|undefined - ]>; + request?: protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.cloudquotas.v1.IQuotaPreference, + protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest | undefined, + {} | undefined, + ] + >; getQuotaPreference( - request: protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest, - options: CallOptions, - callback: Callback< - protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest, + options: CallOptions, + callback: Callback< + protos.google.api.cloudquotas.v1.IQuotaPreference, + | protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getQuotaPreference( - request: protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest, - callback: Callback< - protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest, + callback: Callback< + protos.google.api.cloudquotas.v1.IQuotaPreference, + | protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getQuotaPreference( - request?: protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest|undefined, {}|undefined - ]>|void { + | protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.cloudquotas.v1.IQuotaPreference, + | protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.cloudquotas.v1.IQuotaPreference, + protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest | 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('getQuotaPreference request %j', request); - const wrappedCallback: Callback< - protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.cloudquotas.v1.IQuotaPreference, + | protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getQuotaPreference response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getQuotaPreference(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest|undefined, - {}|undefined - ]) => { - this._log.info('getQuotaPreference response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getQuotaPreference(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.cloudquotas.v1.IQuotaPreference, + ( + | protos.google.api.cloudquotas.v1.IGetQuotaPreferenceRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getQuotaPreference response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new QuotaPreference that declares the desired value for a quota. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Value for parent. - * - * Example: - * `projects/123/locations/global` - * @param {string} [request.quotaPreferenceId] - * Optional. Id of the requesting object, must be unique under its parent. - * If client does not set this field, the service will generate one. - * @param {google.api.cloudquotas.v1.QuotaPreference} request.quotaPreference - * Required. The resource being created - * @param {number[]} request.ignoreSafetyChecks - * The list of quota safety checks to be ignored. - * @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.api.cloudquotas.v1.QuotaPreference|QuotaPreference}. - * 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/cloud_quotas.create_quota_preference.js - * region_tag:cloudquotas_v1_generated_CloudQuotas_CreateQuotaPreference_async - */ + /** + * Creates a new QuotaPreference that declares the desired value for a quota. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Value for parent. + * + * Example: + * `projects/123/locations/global` + * @param {string} [request.quotaPreferenceId] + * Optional. Id of the requesting object, must be unique under its parent. + * If client does not set this field, the service will generate one. + * @param {google.api.cloudquotas.v1.QuotaPreference} request.quotaPreference + * Required. The resource being created + * @param {number[]} request.ignoreSafetyChecks + * The list of quota safety checks to be ignored. + * @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.api.cloudquotas.v1.QuotaPreference|QuotaPreference}. + * 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/cloud_quotas.create_quota_preference.js + * region_tag:cloudquotas_v1_generated_CloudQuotas_CreateQuotaPreference_async + */ createQuotaPreference( - request?: protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest, - options?: CallOptions): - Promise<[ - protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest|undefined, {}|undefined - ]>; + request?: protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.cloudquotas.v1.IQuotaPreference, + ( + | protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest + | undefined + ), + {} | undefined, + ] + >; createQuotaPreference( - request: protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest, - options: CallOptions, - callback: Callback< - protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest, + options: CallOptions, + callback: Callback< + protos.google.api.cloudquotas.v1.IQuotaPreference, + | protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createQuotaPreference( - request: protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest, - callback: Callback< - protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest, + callback: Callback< + protos.google.api.cloudquotas.v1.IQuotaPreference, + | protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createQuotaPreference( - request?: protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest|undefined, {}|undefined - ]>|void { + | protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.cloudquotas.v1.IQuotaPreference, + | protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.cloudquotas.v1.IQuotaPreference, + ( + | protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest + | 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('createQuotaPreference request %j', request); - const wrappedCallback: Callback< - protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.cloudquotas.v1.IQuotaPreference, + | protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createQuotaPreference response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createQuotaPreference(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest|undefined, - {}|undefined - ]) => { - this._log.info('createQuotaPreference response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createQuotaPreference(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.cloudquotas.v1.IQuotaPreference, + ( + | protos.google.api.cloudquotas.v1.ICreateQuotaPreferenceRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createQuotaPreference response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the parameters of a single QuotaPreference. It can updates the - * config in any states, not just the ones pending approval. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. Field mask is used to specify the fields to be overwritten in the - * QuotaPreference resource by the update. - * The fields specified in the update_mask are relative to the resource, not - * the full request. A field will be overwritten if it is in the mask. If the - * user does not provide a mask then all fields will be overwritten. - * @param {google.api.cloudquotas.v1.QuotaPreference} request.quotaPreference - * Required. The resource being updated - * @param {boolean} [request.allowMissing] - * Optional. If set to true, and the quota preference is not found, a new one - * will be created. In this situation, `update_mask` is ignored. - * @param {boolean} [request.validateOnly] - * Optional. If set to true, validate the request, but do not actually update. - * Note that a request being valid does not mean that the request is - * guaranteed to be fulfilled. - * @param {number[]} request.ignoreSafetyChecks - * The list of quota safety checks to be ignored. - * @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.api.cloudquotas.v1.QuotaPreference|QuotaPreference}. - * 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/cloud_quotas.update_quota_preference.js - * region_tag:cloudquotas_v1_generated_CloudQuotas_UpdateQuotaPreference_async - */ + /** + * Updates the parameters of a single QuotaPreference. It can updates the + * config in any states, not just the ones pending approval. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. Field mask is used to specify the fields to be overwritten in the + * QuotaPreference resource by the update. + * The fields specified in the update_mask are relative to the resource, not + * the full request. A field will be overwritten if it is in the mask. If the + * user does not provide a mask then all fields will be overwritten. + * @param {google.api.cloudquotas.v1.QuotaPreference} request.quotaPreference + * Required. The resource being updated + * @param {boolean} [request.allowMissing] + * Optional. If set to true, and the quota preference is not found, a new one + * will be created. In this situation, `update_mask` is ignored. + * @param {boolean} [request.validateOnly] + * Optional. If set to true, validate the request, but do not actually update. + * Note that a request being valid does not mean that the request is + * guaranteed to be fulfilled. + * @param {number[]} request.ignoreSafetyChecks + * The list of quota safety checks to be ignored. + * @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.api.cloudquotas.v1.QuotaPreference|QuotaPreference}. + * 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/cloud_quotas.update_quota_preference.js + * region_tag:cloudquotas_v1_generated_CloudQuotas_UpdateQuotaPreference_async + */ updateQuotaPreference( - request?: protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest, - options?: CallOptions): - Promise<[ - protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest|undefined, {}|undefined - ]>; + request?: protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.cloudquotas.v1.IQuotaPreference, + ( + | protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest + | undefined + ), + {} | undefined, + ] + >; updateQuotaPreference( - request: protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest, - options: CallOptions, - callback: Callback< - protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest, + options: CallOptions, + callback: Callback< + protos.google.api.cloudquotas.v1.IQuotaPreference, + | protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateQuotaPreference( - request: protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest, - callback: Callback< - protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest, + callback: Callback< + protos.google.api.cloudquotas.v1.IQuotaPreference, + | protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateQuotaPreference( - request?: protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest|undefined, {}|undefined - ]>|void { + | protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.cloudquotas.v1.IQuotaPreference, + | protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.cloudquotas.v1.IQuotaPreference, + ( + | protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest + | 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({ - 'quota_preference.name': request.quotaPreference!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'quota_preference.name': request.quotaPreference!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateQuotaPreference request %j', request); - const wrappedCallback: Callback< - protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.cloudquotas.v1.IQuotaPreference, + | protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateQuotaPreference response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateQuotaPreference(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.cloudquotas.v1.IQuotaPreference, - protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateQuotaPreference response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateQuotaPreference(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.cloudquotas.v1.IQuotaPreference, + ( + | protos.google.api.cloudquotas.v1.IUpdateQuotaPreferenceRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateQuotaPreference response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists QuotaInfos of all quotas for a given project, folder or organization. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Parent value of QuotaInfo resources. - * Listing across different resource containers (such as 'projects/-') is not - * allowed. - * - * Example names: - * `projects/123/locations/global/services/compute.googleapis.com` - * `folders/234/locations/global/services/compute.googleapis.com` - * `organizations/345/locations/global/services/compute.googleapis.com` - * @param {number} [request.pageSize] - * Optional. Requested page size. Server may return fewer items than - * requested. If unspecified, server will pick an appropriate default. - * @param {string} [request.pageToken] - * Optional. A token identifying a page of results the server should return. - * @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.api.cloudquotas.v1.QuotaInfo|QuotaInfo}. - * 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 `listQuotaInfosAsync()` - * 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 QuotaInfos of all quotas for a given project, folder or organization. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Parent value of QuotaInfo resources. + * Listing across different resource containers (such as 'projects/-') is not + * allowed. + * + * Example names: + * `projects/123/locations/global/services/compute.googleapis.com` + * `folders/234/locations/global/services/compute.googleapis.com` + * `organizations/345/locations/global/services/compute.googleapis.com` + * @param {number} [request.pageSize] + * Optional. Requested page size. Server may return fewer items than + * requested. If unspecified, server will pick an appropriate default. + * @param {string} [request.pageToken] + * Optional. A token identifying a page of results the server should return. + * @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.api.cloudquotas.v1.QuotaInfo|QuotaInfo}. + * 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 `listQuotaInfosAsync()` + * 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. + */ listQuotaInfos( - request?: protos.google.api.cloudquotas.v1.IListQuotaInfosRequest, - options?: CallOptions): - Promise<[ - protos.google.api.cloudquotas.v1.IQuotaInfo[], - protos.google.api.cloudquotas.v1.IListQuotaInfosRequest|null, - protos.google.api.cloudquotas.v1.IListQuotaInfosResponse - ]>; + request?: protos.google.api.cloudquotas.v1.IListQuotaInfosRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.cloudquotas.v1.IQuotaInfo[], + protos.google.api.cloudquotas.v1.IListQuotaInfosRequest | null, + protos.google.api.cloudquotas.v1.IListQuotaInfosResponse, + ] + >; listQuotaInfos( - request: protos.google.api.cloudquotas.v1.IListQuotaInfosRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.api.cloudquotas.v1.IListQuotaInfosRequest, - protos.google.api.cloudquotas.v1.IListQuotaInfosResponse|null|undefined, - protos.google.api.cloudquotas.v1.IQuotaInfo>): void; + request: protos.google.api.cloudquotas.v1.IListQuotaInfosRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.api.cloudquotas.v1.IListQuotaInfosRequest, + | protos.google.api.cloudquotas.v1.IListQuotaInfosResponse + | null + | undefined, + protos.google.api.cloudquotas.v1.IQuotaInfo + >, + ): void; listQuotaInfos( - request: protos.google.api.cloudquotas.v1.IListQuotaInfosRequest, - callback: PaginationCallback< - protos.google.api.cloudquotas.v1.IListQuotaInfosRequest, - protos.google.api.cloudquotas.v1.IListQuotaInfosResponse|null|undefined, - protos.google.api.cloudquotas.v1.IQuotaInfo>): void; + request: protos.google.api.cloudquotas.v1.IListQuotaInfosRequest, + callback: PaginationCallback< + protos.google.api.cloudquotas.v1.IListQuotaInfosRequest, + | protos.google.api.cloudquotas.v1.IListQuotaInfosResponse + | null + | undefined, + protos.google.api.cloudquotas.v1.IQuotaInfo + >, + ): void; listQuotaInfos( - request?: protos.google.api.cloudquotas.v1.IListQuotaInfosRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.api.cloudquotas.v1.IListQuotaInfosRequest, - protos.google.api.cloudquotas.v1.IListQuotaInfosResponse|null|undefined, - protos.google.api.cloudquotas.v1.IQuotaInfo>, - callback?: PaginationCallback< + request?: protos.google.api.cloudquotas.v1.IListQuotaInfosRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.api.cloudquotas.v1.IListQuotaInfosRequest, - protos.google.api.cloudquotas.v1.IListQuotaInfosResponse|null|undefined, - protos.google.api.cloudquotas.v1.IQuotaInfo>): - Promise<[ - protos.google.api.cloudquotas.v1.IQuotaInfo[], - protos.google.api.cloudquotas.v1.IListQuotaInfosRequest|null, - protos.google.api.cloudquotas.v1.IListQuotaInfosResponse - ]>|void { + | protos.google.api.cloudquotas.v1.IListQuotaInfosResponse + | null + | undefined, + protos.google.api.cloudquotas.v1.IQuotaInfo + >, + callback?: PaginationCallback< + protos.google.api.cloudquotas.v1.IListQuotaInfosRequest, + | protos.google.api.cloudquotas.v1.IListQuotaInfosResponse + | null + | undefined, + protos.google.api.cloudquotas.v1.IQuotaInfo + >, + ): Promise< + [ + protos.google.api.cloudquotas.v1.IQuotaInfo[], + protos.google.api.cloudquotas.v1.IListQuotaInfosRequest | null, + protos.google.api.cloudquotas.v1.IListQuotaInfosResponse, + ] + > | 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.api.cloudquotas.v1.IListQuotaInfosRequest, - protos.google.api.cloudquotas.v1.IListQuotaInfosResponse|null|undefined, - protos.google.api.cloudquotas.v1.IQuotaInfo>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.api.cloudquotas.v1.IListQuotaInfosRequest, + | protos.google.api.cloudquotas.v1.IListQuotaInfosResponse + | null + | undefined, + protos.google.api.cloudquotas.v1.IQuotaInfo + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listQuotaInfos values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -871,229 +1132,258 @@ export class CloudQuotasClient { this._log.info('listQuotaInfos request %j', request); return this.innerApiCalls .listQuotaInfos(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.api.cloudquotas.v1.IQuotaInfo[], - protos.google.api.cloudquotas.v1.IListQuotaInfosRequest|null, - protos.google.api.cloudquotas.v1.IListQuotaInfosResponse - ]) => { - this._log.info('listQuotaInfos values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.api.cloudquotas.v1.IQuotaInfo[], + protos.google.api.cloudquotas.v1.IListQuotaInfosRequest | null, + protos.google.api.cloudquotas.v1.IListQuotaInfosResponse, + ]) => { + this._log.info('listQuotaInfos values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listQuotaInfos`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Parent value of QuotaInfo resources. - * Listing across different resource containers (such as 'projects/-') is not - * allowed. - * - * Example names: - * `projects/123/locations/global/services/compute.googleapis.com` - * `folders/234/locations/global/services/compute.googleapis.com` - * `organizations/345/locations/global/services/compute.googleapis.com` - * @param {number} [request.pageSize] - * Optional. Requested page size. Server may return fewer items than - * requested. If unspecified, server will pick an appropriate default. - * @param {string} [request.pageToken] - * Optional. A token identifying a page of results the server should return. - * @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.api.cloudquotas.v1.QuotaInfo|QuotaInfo} 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 `listQuotaInfosAsync()` - * 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 `listQuotaInfos`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Parent value of QuotaInfo resources. + * Listing across different resource containers (such as 'projects/-') is not + * allowed. + * + * Example names: + * `projects/123/locations/global/services/compute.googleapis.com` + * `folders/234/locations/global/services/compute.googleapis.com` + * `organizations/345/locations/global/services/compute.googleapis.com` + * @param {number} [request.pageSize] + * Optional. Requested page size. Server may return fewer items than + * requested. If unspecified, server will pick an appropriate default. + * @param {string} [request.pageToken] + * Optional. A token identifying a page of results the server should return. + * @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.api.cloudquotas.v1.QuotaInfo|QuotaInfo} 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 `listQuotaInfosAsync()` + * 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. + */ listQuotaInfosStream( - request?: protos.google.api.cloudquotas.v1.IListQuotaInfosRequest, - options?: CallOptions): - Transform{ + request?: protos.google.api.cloudquotas.v1.IListQuotaInfosRequest, + 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['listQuotaInfos']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listQuotaInfos stream %j', request); return this.descriptors.page.listQuotaInfos.createStream( this.innerApiCalls.listQuotaInfos as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listQuotaInfos`, 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. Parent value of QuotaInfo resources. - * Listing across different resource containers (such as 'projects/-') is not - * allowed. - * - * Example names: - * `projects/123/locations/global/services/compute.googleapis.com` - * `folders/234/locations/global/services/compute.googleapis.com` - * `organizations/345/locations/global/services/compute.googleapis.com` - * @param {number} [request.pageSize] - * Optional. Requested page size. Server may return fewer items than - * requested. If unspecified, server will pick an appropriate default. - * @param {string} [request.pageToken] - * Optional. A token identifying a page of results the server should return. - * @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.api.cloudquotas.v1.QuotaInfo|QuotaInfo}. 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 include:samples/generated/v1/cloud_quotas.list_quota_infos.js - * region_tag:cloudquotas_v1_generated_CloudQuotas_ListQuotaInfos_async - */ + /** + * Equivalent to `listQuotaInfos`, 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. Parent value of QuotaInfo resources. + * Listing across different resource containers (such as 'projects/-') is not + * allowed. + * + * Example names: + * `projects/123/locations/global/services/compute.googleapis.com` + * `folders/234/locations/global/services/compute.googleapis.com` + * `organizations/345/locations/global/services/compute.googleapis.com` + * @param {number} [request.pageSize] + * Optional. Requested page size. Server may return fewer items than + * requested. If unspecified, server will pick an appropriate default. + * @param {string} [request.pageToken] + * Optional. A token identifying a page of results the server should return. + * @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.api.cloudquotas.v1.QuotaInfo|QuotaInfo}. 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 include:samples/generated/v1/cloud_quotas.list_quota_infos.js + * region_tag:cloudquotas_v1_generated_CloudQuotas_ListQuotaInfos_async + */ listQuotaInfosAsync( - request?: protos.google.api.cloudquotas.v1.IListQuotaInfosRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.api.cloudquotas.v1.IListQuotaInfosRequest, + 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['listQuotaInfos']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listQuotaInfos iterate %j', request); return this.descriptors.page.listQuotaInfos.asyncIterate( this.innerApiCalls['listQuotaInfos'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists QuotaPreferences in a given project, folder or organization. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Parent value of QuotaPreference resources. - * Listing across different resource containers (such as 'projects/-') is not - * allowed. - * - * When the value starts with 'folders' or 'organizations', it lists the - * QuotaPreferences for org quotas in the container. It does not list the - * QuotaPreferences in the descendant projects of the container. - * - * Example parents: - * `projects/123/locations/global` - * @param {number} [request.pageSize] - * Optional. Requested page size. Server may return fewer items than - * requested. If unspecified, server will pick an appropriate default. - * @param {string} [request.pageToken] - * Optional. A token identifying a page of results the server should return. - * @param {string} [request.filter] - * Optional. Filter result QuotaPreferences by their state, type, - * create/update time range. - * - * Example filters: - * `reconciling=true AND request_type=CLOUD_CONSOLE`, - * `reconciling=true OR creation_time>2022-12-03T10:30:00` - * @param {string} [request.orderBy] - * Optional. How to order of the results. By default, the results are ordered - * by create time. - * - * Example orders: - * `quota_id`, - * `service, create_time` - * @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.api.cloudquotas.v1.QuotaPreference|QuotaPreference}. - * 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 `listQuotaPreferencesAsync()` - * 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 QuotaPreferences in a given project, folder or organization. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Parent value of QuotaPreference resources. + * Listing across different resource containers (such as 'projects/-') is not + * allowed. + * + * When the value starts with 'folders' or 'organizations', it lists the + * QuotaPreferences for org quotas in the container. It does not list the + * QuotaPreferences in the descendant projects of the container. + * + * Example parents: + * `projects/123/locations/global` + * @param {number} [request.pageSize] + * Optional. Requested page size. Server may return fewer items than + * requested. If unspecified, server will pick an appropriate default. + * @param {string} [request.pageToken] + * Optional. A token identifying a page of results the server should return. + * @param {string} [request.filter] + * Optional. Filter result QuotaPreferences by their state, type, + * create/update time range. + * + * Example filters: + * `reconciling=true AND request_type=CLOUD_CONSOLE`, + * `reconciling=true OR creation_time>2022-12-03T10:30:00` + * @param {string} [request.orderBy] + * Optional. How to order of the results. By default, the results are ordered + * by create time. + * + * Example orders: + * `quota_id`, + * `service, create_time` + * @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.api.cloudquotas.v1.QuotaPreference|QuotaPreference}. + * 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 `listQuotaPreferencesAsync()` + * 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. + */ listQuotaPreferences( - request?: protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest, - options?: CallOptions): - Promise<[ - protos.google.api.cloudquotas.v1.IQuotaPreference[], - protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest|null, - protos.google.api.cloudquotas.v1.IListQuotaPreferencesResponse - ]>; + request?: protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.cloudquotas.v1.IQuotaPreference[], + protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest | null, + protos.google.api.cloudquotas.v1.IListQuotaPreferencesResponse, + ] + >; listQuotaPreferences( - request: protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest, - protos.google.api.cloudquotas.v1.IListQuotaPreferencesResponse|null|undefined, - protos.google.api.cloudquotas.v1.IQuotaPreference>): void; + request: protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest, + | protos.google.api.cloudquotas.v1.IListQuotaPreferencesResponse + | null + | undefined, + protos.google.api.cloudquotas.v1.IQuotaPreference + >, + ): void; listQuotaPreferences( - request: protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest, - callback: PaginationCallback< - protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest, - protos.google.api.cloudquotas.v1.IListQuotaPreferencesResponse|null|undefined, - protos.google.api.cloudquotas.v1.IQuotaPreference>): void; + request: protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest, + callback: PaginationCallback< + protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest, + | protos.google.api.cloudquotas.v1.IListQuotaPreferencesResponse + | null + | undefined, + protos.google.api.cloudquotas.v1.IQuotaPreference + >, + ): void; listQuotaPreferences( - request?: protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest, - protos.google.api.cloudquotas.v1.IListQuotaPreferencesResponse|null|undefined, - protos.google.api.cloudquotas.v1.IQuotaPreference>, - callback?: PaginationCallback< + request?: protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest, - protos.google.api.cloudquotas.v1.IListQuotaPreferencesResponse|null|undefined, - protos.google.api.cloudquotas.v1.IQuotaPreference>): - Promise<[ - protos.google.api.cloudquotas.v1.IQuotaPreference[], - protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest|null, - protos.google.api.cloudquotas.v1.IListQuotaPreferencesResponse - ]>|void { + | protos.google.api.cloudquotas.v1.IListQuotaPreferencesResponse + | null + | undefined, + protos.google.api.cloudquotas.v1.IQuotaPreference + >, + callback?: PaginationCallback< + protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest, + | protos.google.api.cloudquotas.v1.IListQuotaPreferencesResponse + | null + | undefined, + protos.google.api.cloudquotas.v1.IQuotaPreference + >, + ): Promise< + [ + protos.google.api.cloudquotas.v1.IQuotaPreference[], + protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest | null, + protos.google.api.cloudquotas.v1.IListQuotaPreferencesResponse, + ] + > | 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.api.cloudquotas.v1.IListQuotaPreferencesRequest, - protos.google.api.cloudquotas.v1.IListQuotaPreferencesResponse|null|undefined, - protos.google.api.cloudquotas.v1.IQuotaPreference>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest, + | protos.google.api.cloudquotas.v1.IListQuotaPreferencesResponse + | null + | undefined, + protos.google.api.cloudquotas.v1.IQuotaPreference + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listQuotaPreferences values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1102,154 +1392,158 @@ export class CloudQuotasClient { this._log.info('listQuotaPreferences request %j', request); return this.innerApiCalls .listQuotaPreferences(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.api.cloudquotas.v1.IQuotaPreference[], - protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest|null, - protos.google.api.cloudquotas.v1.IListQuotaPreferencesResponse - ]) => { - this._log.info('listQuotaPreferences values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.api.cloudquotas.v1.IQuotaPreference[], + protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest | null, + protos.google.api.cloudquotas.v1.IListQuotaPreferencesResponse, + ]) => { + this._log.info('listQuotaPreferences values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listQuotaPreferences`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Parent value of QuotaPreference resources. - * Listing across different resource containers (such as 'projects/-') is not - * allowed. - * - * When the value starts with 'folders' or 'organizations', it lists the - * QuotaPreferences for org quotas in the container. It does not list the - * QuotaPreferences in the descendant projects of the container. - * - * Example parents: - * `projects/123/locations/global` - * @param {number} [request.pageSize] - * Optional. Requested page size. Server may return fewer items than - * requested. If unspecified, server will pick an appropriate default. - * @param {string} [request.pageToken] - * Optional. A token identifying a page of results the server should return. - * @param {string} [request.filter] - * Optional. Filter result QuotaPreferences by their state, type, - * create/update time range. - * - * Example filters: - * `reconciling=true AND request_type=CLOUD_CONSOLE`, - * `reconciling=true OR creation_time>2022-12-03T10:30:00` - * @param {string} [request.orderBy] - * Optional. How to order of the results. By default, the results are ordered - * by create time. - * - * Example orders: - * `quota_id`, - * `service, create_time` - * @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.api.cloudquotas.v1.QuotaPreference|QuotaPreference} 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 `listQuotaPreferencesAsync()` - * 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 `listQuotaPreferences`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Parent value of QuotaPreference resources. + * Listing across different resource containers (such as 'projects/-') is not + * allowed. + * + * When the value starts with 'folders' or 'organizations', it lists the + * QuotaPreferences for org quotas in the container. It does not list the + * QuotaPreferences in the descendant projects of the container. + * + * Example parents: + * `projects/123/locations/global` + * @param {number} [request.pageSize] + * Optional. Requested page size. Server may return fewer items than + * requested. If unspecified, server will pick an appropriate default. + * @param {string} [request.pageToken] + * Optional. A token identifying a page of results the server should return. + * @param {string} [request.filter] + * Optional. Filter result QuotaPreferences by their state, type, + * create/update time range. + * + * Example filters: + * `reconciling=true AND request_type=CLOUD_CONSOLE`, + * `reconciling=true OR creation_time>2022-12-03T10:30:00` + * @param {string} [request.orderBy] + * Optional. How to order of the results. By default, the results are ordered + * by create time. + * + * Example orders: + * `quota_id`, + * `service, create_time` + * @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.api.cloudquotas.v1.QuotaPreference|QuotaPreference} 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 `listQuotaPreferencesAsync()` + * 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. + */ listQuotaPreferencesStream( - request?: protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest, + 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['listQuotaPreferences']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listQuotaPreferences stream %j', request); return this.descriptors.page.listQuotaPreferences.createStream( this.innerApiCalls.listQuotaPreferences as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listQuotaPreferences`, 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. Parent value of QuotaPreference resources. - * Listing across different resource containers (such as 'projects/-') is not - * allowed. - * - * When the value starts with 'folders' or 'organizations', it lists the - * QuotaPreferences for org quotas in the container. It does not list the - * QuotaPreferences in the descendant projects of the container. - * - * Example parents: - * `projects/123/locations/global` - * @param {number} [request.pageSize] - * Optional. Requested page size. Server may return fewer items than - * requested. If unspecified, server will pick an appropriate default. - * @param {string} [request.pageToken] - * Optional. A token identifying a page of results the server should return. - * @param {string} [request.filter] - * Optional. Filter result QuotaPreferences by their state, type, - * create/update time range. - * - * Example filters: - * `reconciling=true AND request_type=CLOUD_CONSOLE`, - * `reconciling=true OR creation_time>2022-12-03T10:30:00` - * @param {string} [request.orderBy] - * Optional. How to order of the results. By default, the results are ordered - * by create time. - * - * Example orders: - * `quota_id`, - * `service, create_time` - * @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.api.cloudquotas.v1.QuotaPreference|QuotaPreference}. 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 include:samples/generated/v1/cloud_quotas.list_quota_preferences.js - * region_tag:cloudquotas_v1_generated_CloudQuotas_ListQuotaPreferences_async - */ + /** + * Equivalent to `listQuotaPreferences`, 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. Parent value of QuotaPreference resources. + * Listing across different resource containers (such as 'projects/-') is not + * allowed. + * + * When the value starts with 'folders' or 'organizations', it lists the + * QuotaPreferences for org quotas in the container. It does not list the + * QuotaPreferences in the descendant projects of the container. + * + * Example parents: + * `projects/123/locations/global` + * @param {number} [request.pageSize] + * Optional. Requested page size. Server may return fewer items than + * requested. If unspecified, server will pick an appropriate default. + * @param {string} [request.pageToken] + * Optional. A token identifying a page of results the server should return. + * @param {string} [request.filter] + * Optional. Filter result QuotaPreferences by their state, type, + * create/update time range. + * + * Example filters: + * `reconciling=true AND request_type=CLOUD_CONSOLE`, + * `reconciling=true OR creation_time>2022-12-03T10:30:00` + * @param {string} [request.orderBy] + * Optional. How to order of the results. By default, the results are ordered + * by create time. + * + * Example orders: + * `quota_id`, + * `service, create_time` + * @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.api.cloudquotas.v1.QuotaPreference|QuotaPreference}. 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 include:samples/generated/v1/cloud_quotas.list_quota_preferences.js + * region_tag:cloudquotas_v1_generated_CloudQuotas_ListQuotaPreferences_async + */ listQuotaPreferencesAsync( - request?: protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.api.cloudquotas.v1.IListQuotaPreferencesRequest, + 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['listQuotaPreferences']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listQuotaPreferences iterate %j', request); return this.descriptors.page.listQuotaPreferences.asyncIterate( this.innerApiCalls['listQuotaPreferences'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1264,7 +1558,11 @@ export class CloudQuotasClient { * @param {string} quota_preference * @returns {string} Resource name string. */ - folderLocationQuotaPreferencePath(folder:string,location:string,quotaPreference:string) { + folderLocationQuotaPreferencePath( + folder: string, + location: string, + quotaPreference: string, + ) { return this.pathTemplates.folderLocationQuotaPreferencePathTemplate.render({ folder: folder, location: location, @@ -1279,8 +1577,12 @@ export class CloudQuotasClient { * A fully-qualified path representing folder_location_quota_preference resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderLocationQuotaPreferenceName(folderLocationQuotaPreferenceName: string) { - return this.pathTemplates.folderLocationQuotaPreferencePathTemplate.match(folderLocationQuotaPreferenceName).folder; + matchFolderFromFolderLocationQuotaPreferenceName( + folderLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.folderLocationQuotaPreferencePathTemplate.match( + folderLocationQuotaPreferenceName, + ).folder; } /** @@ -1290,8 +1592,12 @@ export class CloudQuotasClient { * A fully-qualified path representing folder_location_quota_preference resource. * @returns {string} A string representing the location. */ - matchLocationFromFolderLocationQuotaPreferenceName(folderLocationQuotaPreferenceName: string) { - return this.pathTemplates.folderLocationQuotaPreferencePathTemplate.match(folderLocationQuotaPreferenceName).location; + matchLocationFromFolderLocationQuotaPreferenceName( + folderLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.folderLocationQuotaPreferencePathTemplate.match( + folderLocationQuotaPreferenceName, + ).location; } /** @@ -1301,8 +1607,12 @@ export class CloudQuotasClient { * A fully-qualified path representing folder_location_quota_preference resource. * @returns {string} A string representing the quota_preference. */ - matchQuotaPreferenceFromFolderLocationQuotaPreferenceName(folderLocationQuotaPreferenceName: string) { - return this.pathTemplates.folderLocationQuotaPreferencePathTemplate.match(folderLocationQuotaPreferenceName).quota_preference; + matchQuotaPreferenceFromFolderLocationQuotaPreferenceName( + folderLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.folderLocationQuotaPreferencePathTemplate.match( + folderLocationQuotaPreferenceName, + ).quota_preference; } /** @@ -1314,13 +1624,20 @@ export class CloudQuotasClient { * @param {string} quota_info * @returns {string} Resource name string. */ - folderLocationServiceQuotaInfoPath(folder:string,location:string,service:string,quotaInfo:string) { - return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.render({ - folder: folder, - location: location, - service: service, - quota_info: quotaInfo, - }); + folderLocationServiceQuotaInfoPath( + folder: string, + location: string, + service: string, + quotaInfo: string, + ) { + return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.render( + { + folder: folder, + location: location, + service: service, + quota_info: quotaInfo, + }, + ); } /** @@ -1330,8 +1647,12 @@ export class CloudQuotasClient { * A fully-qualified path representing folder_location_service_quota_info resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderLocationServiceQuotaInfoName(folderLocationServiceQuotaInfoName: string) { - return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match(folderLocationServiceQuotaInfoName).folder; + matchFolderFromFolderLocationServiceQuotaInfoName( + folderLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match( + folderLocationServiceQuotaInfoName, + ).folder; } /** @@ -1341,8 +1662,12 @@ export class CloudQuotasClient { * A fully-qualified path representing folder_location_service_quota_info resource. * @returns {string} A string representing the location. */ - matchLocationFromFolderLocationServiceQuotaInfoName(folderLocationServiceQuotaInfoName: string) { - return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match(folderLocationServiceQuotaInfoName).location; + matchLocationFromFolderLocationServiceQuotaInfoName( + folderLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match( + folderLocationServiceQuotaInfoName, + ).location; } /** @@ -1352,8 +1677,12 @@ export class CloudQuotasClient { * A fully-qualified path representing folder_location_service_quota_info resource. * @returns {string} A string representing the service. */ - matchServiceFromFolderLocationServiceQuotaInfoName(folderLocationServiceQuotaInfoName: string) { - return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match(folderLocationServiceQuotaInfoName).service; + matchServiceFromFolderLocationServiceQuotaInfoName( + folderLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match( + folderLocationServiceQuotaInfoName, + ).service; } /** @@ -1363,8 +1692,12 @@ export class CloudQuotasClient { * A fully-qualified path representing folder_location_service_quota_info resource. * @returns {string} A string representing the quota_info. */ - matchQuotaInfoFromFolderLocationServiceQuotaInfoName(folderLocationServiceQuotaInfoName: string) { - return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match(folderLocationServiceQuotaInfoName).quota_info; + matchQuotaInfoFromFolderLocationServiceQuotaInfoName( + folderLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match( + folderLocationServiceQuotaInfoName, + ).quota_info; } /** @@ -1375,12 +1708,18 @@ export class CloudQuotasClient { * @param {string} quota_preference * @returns {string} Resource name string. */ - organizationLocationQuotaPreferencePath(organization:string,location:string,quotaPreference:string) { - return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.render({ - organization: organization, - location: location, - quota_preference: quotaPreference, - }); + organizationLocationQuotaPreferencePath( + organization: string, + location: string, + quotaPreference: string, + ) { + return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.render( + { + organization: organization, + location: location, + quota_preference: quotaPreference, + }, + ); } /** @@ -1390,8 +1729,12 @@ export class CloudQuotasClient { * A fully-qualified path representing organization_location_quota_preference resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationLocationQuotaPreferenceName(organizationLocationQuotaPreferenceName: string) { - return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match(organizationLocationQuotaPreferenceName).organization; + matchOrganizationFromOrganizationLocationQuotaPreferenceName( + organizationLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match( + organizationLocationQuotaPreferenceName, + ).organization; } /** @@ -1401,8 +1744,12 @@ export class CloudQuotasClient { * A fully-qualified path representing organization_location_quota_preference resource. * @returns {string} A string representing the location. */ - matchLocationFromOrganizationLocationQuotaPreferenceName(organizationLocationQuotaPreferenceName: string) { - return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match(organizationLocationQuotaPreferenceName).location; + matchLocationFromOrganizationLocationQuotaPreferenceName( + organizationLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match( + organizationLocationQuotaPreferenceName, + ).location; } /** @@ -1412,8 +1759,12 @@ export class CloudQuotasClient { * A fully-qualified path representing organization_location_quota_preference resource. * @returns {string} A string representing the quota_preference. */ - matchQuotaPreferenceFromOrganizationLocationQuotaPreferenceName(organizationLocationQuotaPreferenceName: string) { - return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match(organizationLocationQuotaPreferenceName).quota_preference; + matchQuotaPreferenceFromOrganizationLocationQuotaPreferenceName( + organizationLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match( + organizationLocationQuotaPreferenceName, + ).quota_preference; } /** @@ -1425,13 +1776,20 @@ export class CloudQuotasClient { * @param {string} quota_info * @returns {string} Resource name string. */ - organizationLocationServiceQuotaInfoPath(organization:string,location:string,service:string,quotaInfo:string) { - return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.render({ - organization: organization, - location: location, - service: service, - quota_info: quotaInfo, - }); + organizationLocationServiceQuotaInfoPath( + organization: string, + location: string, + service: string, + quotaInfo: string, + ) { + return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.render( + { + organization: organization, + location: location, + service: service, + quota_info: quotaInfo, + }, + ); } /** @@ -1441,8 +1799,12 @@ export class CloudQuotasClient { * A fully-qualified path representing organization_location_service_quota_info resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationLocationServiceQuotaInfoName(organizationLocationServiceQuotaInfoName: string) { - return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match(organizationLocationServiceQuotaInfoName).organization; + matchOrganizationFromOrganizationLocationServiceQuotaInfoName( + organizationLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match( + organizationLocationServiceQuotaInfoName, + ).organization; } /** @@ -1452,8 +1814,12 @@ export class CloudQuotasClient { * A fully-qualified path representing organization_location_service_quota_info resource. * @returns {string} A string representing the location. */ - matchLocationFromOrganizationLocationServiceQuotaInfoName(organizationLocationServiceQuotaInfoName: string) { - return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match(organizationLocationServiceQuotaInfoName).location; + matchLocationFromOrganizationLocationServiceQuotaInfoName( + organizationLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match( + organizationLocationServiceQuotaInfoName, + ).location; } /** @@ -1463,8 +1829,12 @@ export class CloudQuotasClient { * A fully-qualified path representing organization_location_service_quota_info resource. * @returns {string} A string representing the service. */ - matchServiceFromOrganizationLocationServiceQuotaInfoName(organizationLocationServiceQuotaInfoName: string) { - return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match(organizationLocationServiceQuotaInfoName).service; + matchServiceFromOrganizationLocationServiceQuotaInfoName( + organizationLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match( + organizationLocationServiceQuotaInfoName, + ).service; } /** @@ -1474,8 +1844,12 @@ export class CloudQuotasClient { * A fully-qualified path representing organization_location_service_quota_info resource. * @returns {string} A string representing the quota_info. */ - matchQuotaInfoFromOrganizationLocationServiceQuotaInfoName(organizationLocationServiceQuotaInfoName: string) { - return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match(organizationLocationServiceQuotaInfoName).quota_info; + matchQuotaInfoFromOrganizationLocationServiceQuotaInfoName( + organizationLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match( + organizationLocationServiceQuotaInfoName, + ).quota_info; } /** @@ -1485,7 +1859,7 @@ export class CloudQuotasClient { * @param {string} location * @returns {string} Resource name string. */ - projectLocationPath(project:string,location:string) { + projectLocationPath(project: string, location: string) { return this.pathTemplates.projectLocationPathTemplate.render({ project: project, location: location, @@ -1500,7 +1874,9 @@ export class CloudQuotasClient { * @returns {string} A string representing the project. */ matchProjectFromProjectLocationName(projectLocationName: string) { - return this.pathTemplates.projectLocationPathTemplate.match(projectLocationName).project; + return this.pathTemplates.projectLocationPathTemplate.match( + projectLocationName, + ).project; } /** @@ -1511,7 +1887,9 @@ export class CloudQuotasClient { * @returns {string} A string representing the location. */ matchLocationFromProjectLocationName(projectLocationName: string) { - return this.pathTemplates.projectLocationPathTemplate.match(projectLocationName).location; + return this.pathTemplates.projectLocationPathTemplate.match( + projectLocationName, + ).location; } /** @@ -1522,12 +1900,18 @@ export class CloudQuotasClient { * @param {string} quota_preference * @returns {string} Resource name string. */ - projectLocationQuotaPreferencePath(project:string,location:string,quotaPreference:string) { - return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.render({ - project: project, - location: location, - quota_preference: quotaPreference, - }); + projectLocationQuotaPreferencePath( + project: string, + location: string, + quotaPreference: string, + ) { + return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.render( + { + project: project, + location: location, + quota_preference: quotaPreference, + }, + ); } /** @@ -1537,8 +1921,12 @@ export class CloudQuotasClient { * A fully-qualified path representing project_location_quota_preference resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectLocationQuotaPreferenceName(projectLocationQuotaPreferenceName: string) { - return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.match(projectLocationQuotaPreferenceName).project; + matchProjectFromProjectLocationQuotaPreferenceName( + projectLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.match( + projectLocationQuotaPreferenceName, + ).project; } /** @@ -1548,8 +1936,12 @@ export class CloudQuotasClient { * A fully-qualified path representing project_location_quota_preference resource. * @returns {string} A string representing the location. */ - matchLocationFromProjectLocationQuotaPreferenceName(projectLocationQuotaPreferenceName: string) { - return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.match(projectLocationQuotaPreferenceName).location; + matchLocationFromProjectLocationQuotaPreferenceName( + projectLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.match( + projectLocationQuotaPreferenceName, + ).location; } /** @@ -1559,8 +1951,12 @@ export class CloudQuotasClient { * A fully-qualified path representing project_location_quota_preference resource. * @returns {string} A string representing the quota_preference. */ - matchQuotaPreferenceFromProjectLocationQuotaPreferenceName(projectLocationQuotaPreferenceName: string) { - return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.match(projectLocationQuotaPreferenceName).quota_preference; + matchQuotaPreferenceFromProjectLocationQuotaPreferenceName( + projectLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.match( + projectLocationQuotaPreferenceName, + ).quota_preference; } /** @@ -1571,7 +1967,11 @@ export class CloudQuotasClient { * @param {string} service * @returns {string} Resource name string. */ - projectLocationServicePath(project:string,location:string,service:string) { + projectLocationServicePath( + project: string, + location: string, + service: string, + ) { return this.pathTemplates.projectLocationServicePathTemplate.render({ project: project, location: location, @@ -1586,8 +1986,12 @@ export class CloudQuotasClient { * A fully-qualified path representing project_location_service resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectLocationServiceName(projectLocationServiceName: string) { - return this.pathTemplates.projectLocationServicePathTemplate.match(projectLocationServiceName).project; + matchProjectFromProjectLocationServiceName( + projectLocationServiceName: string, + ) { + return this.pathTemplates.projectLocationServicePathTemplate.match( + projectLocationServiceName, + ).project; } /** @@ -1597,8 +2001,12 @@ export class CloudQuotasClient { * A fully-qualified path representing project_location_service resource. * @returns {string} A string representing the location. */ - matchLocationFromProjectLocationServiceName(projectLocationServiceName: string) { - return this.pathTemplates.projectLocationServicePathTemplate.match(projectLocationServiceName).location; + matchLocationFromProjectLocationServiceName( + projectLocationServiceName: string, + ) { + return this.pathTemplates.projectLocationServicePathTemplate.match( + projectLocationServiceName, + ).location; } /** @@ -1608,8 +2016,12 @@ export class CloudQuotasClient { * A fully-qualified path representing project_location_service resource. * @returns {string} A string representing the service. */ - matchServiceFromProjectLocationServiceName(projectLocationServiceName: string) { - return this.pathTemplates.projectLocationServicePathTemplate.match(projectLocationServiceName).service; + matchServiceFromProjectLocationServiceName( + projectLocationServiceName: string, + ) { + return this.pathTemplates.projectLocationServicePathTemplate.match( + projectLocationServiceName, + ).service; } /** @@ -1621,13 +2033,20 @@ export class CloudQuotasClient { * @param {string} quota_info * @returns {string} Resource name string. */ - projectLocationServiceQuotaInfoPath(project:string,location:string,service:string,quotaInfo:string) { - return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.render({ - project: project, - location: location, - service: service, - quota_info: quotaInfo, - }); + projectLocationServiceQuotaInfoPath( + project: string, + location: string, + service: string, + quotaInfo: string, + ) { + return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.render( + { + project: project, + location: location, + service: service, + quota_info: quotaInfo, + }, + ); } /** @@ -1637,8 +2056,12 @@ export class CloudQuotasClient { * A fully-qualified path representing project_location_service_quota_info resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectLocationServiceQuotaInfoName(projectLocationServiceQuotaInfoName: string) { - return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match(projectLocationServiceQuotaInfoName).project; + matchProjectFromProjectLocationServiceQuotaInfoName( + projectLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match( + projectLocationServiceQuotaInfoName, + ).project; } /** @@ -1648,8 +2071,12 @@ export class CloudQuotasClient { * A fully-qualified path representing project_location_service_quota_info resource. * @returns {string} A string representing the location. */ - matchLocationFromProjectLocationServiceQuotaInfoName(projectLocationServiceQuotaInfoName: string) { - return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match(projectLocationServiceQuotaInfoName).location; + matchLocationFromProjectLocationServiceQuotaInfoName( + projectLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match( + projectLocationServiceQuotaInfoName, + ).location; } /** @@ -1659,8 +2086,12 @@ export class CloudQuotasClient { * A fully-qualified path representing project_location_service_quota_info resource. * @returns {string} A string representing the service. */ - matchServiceFromProjectLocationServiceQuotaInfoName(projectLocationServiceQuotaInfoName: string) { - return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match(projectLocationServiceQuotaInfoName).service; + matchServiceFromProjectLocationServiceQuotaInfoName( + projectLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match( + projectLocationServiceQuotaInfoName, + ).service; } /** @@ -1670,8 +2101,12 @@ export class CloudQuotasClient { * A fully-qualified path representing project_location_service_quota_info resource. * @returns {string} A string representing the quota_info. */ - matchQuotaInfoFromProjectLocationServiceQuotaInfoName(projectLocationServiceQuotaInfoName: string) { - return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match(projectLocationServiceQuotaInfoName).quota_info; + matchQuotaInfoFromProjectLocationServiceQuotaInfoName( + projectLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match( + projectLocationServiceQuotaInfoName, + ).quota_info; } /** @@ -1682,7 +2117,7 @@ export class CloudQuotasClient { */ close(): Promise { if (this.cloudQuotasStub && !this._terminated) { - return this.cloudQuotasStub.then(stub => { + return this.cloudQuotasStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1690,4 +2125,4 @@ export class CloudQuotasClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-api-cloudquotas/src/v1/index.ts b/packages/google-api-cloudquotas/src/v1/index.ts index 773df238f3ff..904aef65add9 100644 --- a/packages/google-api-cloudquotas/src/v1/index.ts +++ b/packages/google-api-cloudquotas/src/v1/index.ts @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {CloudQuotasClient} from './cloud_quotas_client'; +export { CloudQuotasClient } from './cloud_quotas_client'; diff --git a/packages/google-api-cloudquotas/src/v1beta/cloud_quotas_client.ts b/packages/google-api-cloudquotas/src/v1beta/cloud_quotas_client.ts index 4883c5e8e09b..09e90082624c 100644 --- a/packages/google-api-cloudquotas/src/v1beta/cloud_quotas_client.ts +++ b/packages/google-api-cloudquotas/src/v1beta/cloud_quotas_client.ts @@ -18,11 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall} from 'google-gax'; -import {Transform} from 'stream'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, +} from 'google-gax'; +import { Transform } from 'stream'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -50,7 +57,7 @@ export class CloudQuotasClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('cloudquotas'); @@ -63,9 +70,9 @@ export class CloudQuotasClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - cloudQuotasStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + cloudQuotasStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of CloudQuotasClient. @@ -106,21 +113,42 @@ export class CloudQuotasClient { * const client = new CloudQuotasClient({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 CloudQuotasClient; - 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 = 'cloudquotas.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -145,7 +173,7 @@ export class CloudQuotasClient { 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,10 +187,7 @@ export class CloudQuotasClient { } // 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 { @@ -183,55 +208,73 @@ export class CloudQuotasClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { - folderLocationQuotaAdjusterSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/locations/{location}/quotaAdjusterSettings' - ), - folderLocationQuotaPreferencePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/locations/{location}/quotaPreferences/{quota_preference}' - ), - folderLocationServiceQuotaInfoPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/locations/{location}/services/{service}/quotaInfos/{quota_info}' - ), - organizationLocationQuotaAdjusterSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/locations/{location}/quotaAdjusterSettings' - ), - organizationLocationQuotaPreferencePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/locations/{location}/quotaPreferences/{quota_preference}' - ), - organizationLocationServiceQuotaInfoPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/locations/{location}/services/{service}/quotaInfos/{quota_info}' - ), + folderLocationQuotaAdjusterSettingsPathTemplate: + new this._gaxModule.PathTemplate( + 'folders/{folder}/locations/{location}/quotaAdjusterSettings', + ), + folderLocationQuotaPreferencePathTemplate: + new this._gaxModule.PathTemplate( + 'folders/{folder}/locations/{location}/quotaPreferences/{quota_preference}', + ), + folderLocationServiceQuotaInfoPathTemplate: + new this._gaxModule.PathTemplate( + 'folders/{folder}/locations/{location}/services/{service}/quotaInfos/{quota_info}', + ), + organizationLocationQuotaAdjusterSettingsPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/locations/{location}/quotaAdjusterSettings', + ), + organizationLocationQuotaPreferencePathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/locations/{location}/quotaPreferences/{quota_preference}', + ), + organizationLocationServiceQuotaInfoPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/locations/{location}/services/{service}/quotaInfos/{quota_info}', + ), projectLocationPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}' - ), - projectLocationQuotaAdjusterSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/quotaAdjusterSettings' - ), - projectLocationQuotaPreferencePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/quotaPreferences/{quota_preference}' + 'projects/{project}/locations/{location}', ), + projectLocationQuotaAdjusterSettingsPathTemplate: + new this._gaxModule.PathTemplate( + 'projects/{project}/locations/{location}/quotaAdjusterSettings', + ), + projectLocationQuotaPreferencePathTemplate: + new this._gaxModule.PathTemplate( + 'projects/{project}/locations/{location}/quotaPreferences/{quota_preference}', + ), projectLocationServicePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/services/{service}' - ), - projectLocationServiceQuotaInfoPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/services/{service}/quotaInfos/{quota_info}' + 'projects/{project}/locations/{location}/services/{service}', ), + projectLocationServiceQuotaInfoPathTemplate: + new this._gaxModule.PathTemplate( + 'projects/{project}/locations/{location}/services/{service}/quotaInfos/{quota_info}', + ), }; // 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 = { - listQuotaInfos: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'quotaInfos'), - listQuotaPreferences: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'quotaPreferences') + listQuotaInfos: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'quotaInfos', + ), + listQuotaPreferences: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'quotaPreferences', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.api.cloudquotas.v1beta.CloudQuotas', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.api.cloudquotas.v1beta.CloudQuotas', + 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 @@ -262,37 +305,47 @@ export class CloudQuotasClient { // Put together the "service stub" for // google.api.cloudquotas.v1beta.CloudQuotas. this.cloudQuotasStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.api.cloudquotas.v1beta.CloudQuotas') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.api.cloudquotas.v1beta.CloudQuotas', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.api.cloudquotas.v1beta.CloudQuotas, - 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 cloudQuotasStubMethods = - ['listQuotaInfos', 'getQuotaInfo', 'listQuotaPreferences', 'getQuotaPreference', 'createQuotaPreference', 'updateQuotaPreference']; + const cloudQuotasStubMethods = [ + 'listQuotaInfos', + 'getQuotaInfo', + 'listQuotaPreferences', + 'getQuotaPreference', + 'createQuotaPreference', + 'updateQuotaPreference', + ]; for (const methodName of cloudQuotasStubMethods) { const callPromise = this.cloudQuotasStub.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] || - undefined; + const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -307,8 +360,14 @@ export class CloudQuotasClient { * @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 'cloudquotas.googleapis.com'; } @@ -319,8 +378,14 @@ export class CloudQuotasClient { * @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 'cloudquotas.googleapis.com'; } @@ -351,9 +416,7 @@ export class CloudQuotasClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -362,8 +425,9 @@ export class CloudQuotasClient { * 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; @@ -374,504 +438,716 @@ export class CloudQuotasClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Retrieve the QuotaInfo of a quota for a project, folder or organization. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the quota info. - * - * An example name: - * `projects/123/locations/global/services/compute.googleapis.com/quotaInfos/CpusPerProjectPerRegion` - * @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.api.cloudquotas.v1beta.QuotaInfo|QuotaInfo}. - * 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/v1beta/cloud_quotas.get_quota_info.js - * region_tag:cloudquotas_v1beta_generated_CloudQuotas_GetQuotaInfo_async - */ + /** + * Retrieve the QuotaInfo of a quota for a project, folder or organization. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the quota info. + * + * An example name: + * `projects/123/locations/global/services/compute.googleapis.com/quotaInfos/CpusPerProjectPerRegion` + * @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.api.cloudquotas.v1beta.QuotaInfo|QuotaInfo}. + * 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/v1beta/cloud_quotas.get_quota_info.js + * region_tag:cloudquotas_v1beta_generated_CloudQuotas_GetQuotaInfo_async + */ getQuotaInfo( - request?: protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest, - options?: CallOptions): - Promise<[ - protos.google.api.cloudquotas.v1beta.IQuotaInfo, - protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest|undefined, {}|undefined - ]>; + request?: protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.cloudquotas.v1beta.IQuotaInfo, + protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest | undefined, + {} | undefined, + ] + >; getQuotaInfo( - request: protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest, - options: CallOptions, - callback: Callback< - protos.google.api.cloudquotas.v1beta.IQuotaInfo, - protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest, + options: CallOptions, + callback: Callback< + protos.google.api.cloudquotas.v1beta.IQuotaInfo, + | protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getQuotaInfo( - request: protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest, - callback: Callback< - protos.google.api.cloudquotas.v1beta.IQuotaInfo, - protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest, + callback: Callback< + protos.google.api.cloudquotas.v1beta.IQuotaInfo, + | protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getQuotaInfo( - request?: protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.cloudquotas.v1beta.IQuotaInfo, - protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.api.cloudquotas.v1beta.IQuotaInfo, - protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.cloudquotas.v1beta.IQuotaInfo, - protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest|undefined, {}|undefined - ]>|void { + | protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.cloudquotas.v1beta.IQuotaInfo, + | protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.cloudquotas.v1beta.IQuotaInfo, + protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest | 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('getQuotaInfo request %j', request); - const wrappedCallback: Callback< - protos.google.api.cloudquotas.v1beta.IQuotaInfo, - protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.cloudquotas.v1beta.IQuotaInfo, + | protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getQuotaInfo response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getQuotaInfo(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.cloudquotas.v1beta.IQuotaInfo, - protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest|undefined, - {}|undefined - ]) => { - this._log.info('getQuotaInfo response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getQuotaInfo(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.cloudquotas.v1beta.IQuotaInfo, + protos.google.api.cloudquotas.v1beta.IGetQuotaInfoRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getQuotaInfo response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets details of a single QuotaPreference. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Name of the resource - * - * Example name: - * `projects/123/locations/global/quota_preferences/my-config-for-us-east1` - * @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.api.cloudquotas.v1beta.QuotaPreference|QuotaPreference}. - * 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/v1beta/cloud_quotas.get_quota_preference.js - * region_tag:cloudquotas_v1beta_generated_CloudQuotas_GetQuotaPreference_async - */ + /** + * Gets details of a single QuotaPreference. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Name of the resource + * + * Example name: + * `projects/123/locations/global/quota_preferences/my-config-for-us-east1` + * @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.api.cloudquotas.v1beta.QuotaPreference|QuotaPreference}. + * 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/v1beta/cloud_quotas.get_quota_preference.js + * region_tag:cloudquotas_v1beta_generated_CloudQuotas_GetQuotaPreference_async + */ getQuotaPreference( - request?: protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest, - options?: CallOptions): - Promise<[ - protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest|undefined, {}|undefined - ]>; + request?: protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.cloudquotas.v1beta.IQuotaPreference, + ( + | protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest + | undefined + ), + {} | undefined, + ] + >; getQuotaPreference( - request: protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest, - options: CallOptions, - callback: Callback< - protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest, + options: CallOptions, + callback: Callback< + protos.google.api.cloudquotas.v1beta.IQuotaPreference, + | protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getQuotaPreference( - request: protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest, - callback: Callback< - protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest, + callback: Callback< + protos.google.api.cloudquotas.v1beta.IQuotaPreference, + | protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getQuotaPreference( - request?: protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest|undefined, {}|undefined - ]>|void { + | protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.cloudquotas.v1beta.IQuotaPreference, + | protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.cloudquotas.v1beta.IQuotaPreference, + ( + | protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest + | 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('getQuotaPreference request %j', request); - const wrappedCallback: Callback< - protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.cloudquotas.v1beta.IQuotaPreference, + | protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getQuotaPreference response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getQuotaPreference(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest|undefined, - {}|undefined - ]) => { - this._log.info('getQuotaPreference response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getQuotaPreference(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.cloudquotas.v1beta.IQuotaPreference, + ( + | protos.google.api.cloudquotas.v1beta.IGetQuotaPreferenceRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getQuotaPreference response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Creates a new QuotaPreference that declares the desired value for a quota. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Value for parent. - * - * Example: - * `projects/123/locations/global` - * @param {string} [request.quotaPreferenceId] - * Optional. Id of the requesting object, must be unique under its parent. - * If client does not set this field, the service will generate one. - * @param {google.api.cloudquotas.v1beta.QuotaPreference} request.quotaPreference - * Required. The resource being created - * @param {number[]} request.ignoreSafetyChecks - * The list of quota safety checks to be ignored. - * @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.api.cloudquotas.v1beta.QuotaPreference|QuotaPreference}. - * 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/v1beta/cloud_quotas.create_quota_preference.js - * region_tag:cloudquotas_v1beta_generated_CloudQuotas_CreateQuotaPreference_async - */ + /** + * Creates a new QuotaPreference that declares the desired value for a quota. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Value for parent. + * + * Example: + * `projects/123/locations/global` + * @param {string} [request.quotaPreferenceId] + * Optional. Id of the requesting object, must be unique under its parent. + * If client does not set this field, the service will generate one. + * @param {google.api.cloudquotas.v1beta.QuotaPreference} request.quotaPreference + * Required. The resource being created + * @param {number[]} request.ignoreSafetyChecks + * The list of quota safety checks to be ignored. + * @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.api.cloudquotas.v1beta.QuotaPreference|QuotaPreference}. + * 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/v1beta/cloud_quotas.create_quota_preference.js + * region_tag:cloudquotas_v1beta_generated_CloudQuotas_CreateQuotaPreference_async + */ createQuotaPreference( - request?: protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest, - options?: CallOptions): - Promise<[ - protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest|undefined, {}|undefined - ]>; + request?: protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.cloudquotas.v1beta.IQuotaPreference, + ( + | protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest + | undefined + ), + {} | undefined, + ] + >; createQuotaPreference( - request: protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest, - options: CallOptions, - callback: Callback< - protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest, + options: CallOptions, + callback: Callback< + protos.google.api.cloudquotas.v1beta.IQuotaPreference, + | protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createQuotaPreference( - request: protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest, - callback: Callback< - protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest, + callback: Callback< + protos.google.api.cloudquotas.v1beta.IQuotaPreference, + | protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; createQuotaPreference( - request?: protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest|undefined, {}|undefined - ]>|void { + | protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.cloudquotas.v1beta.IQuotaPreference, + | protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.cloudquotas.v1beta.IQuotaPreference, + ( + | protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest + | 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('createQuotaPreference request %j', request); - const wrappedCallback: Callback< - protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.cloudquotas.v1beta.IQuotaPreference, + | protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createQuotaPreference response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createQuotaPreference(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest|undefined, - {}|undefined - ]) => { - this._log.info('createQuotaPreference response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .createQuotaPreference(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.cloudquotas.v1beta.IQuotaPreference, + ( + | protos.google.api.cloudquotas.v1beta.ICreateQuotaPreferenceRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createQuotaPreference response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Updates the parameters of a single QuotaPreference. It can updates the - * config in any states, not just the ones pending approval. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. Field mask is used to specify the fields to be overwritten in the - * QuotaPreference resource by the update. - * The fields specified in the update_mask are relative to the resource, not - * the full request. A field will be overwritten if it is in the mask. If the - * user does not provide a mask then all fields will be overwritten. - * @param {google.api.cloudquotas.v1beta.QuotaPreference} request.quotaPreference - * Required. The resource being updated - * @param {boolean} [request.allowMissing] - * Optional. If set to true, and the quota preference is not found, a new one - * will be created. In this situation, `update_mask` is ignored. - * @param {boolean} [request.validateOnly] - * Optional. If set to true, validate the request, but do not actually update. - * Note that a request being valid does not mean that the request is - * guaranteed to be fulfilled. - * @param {number[]} request.ignoreSafetyChecks - * The list of quota safety checks to be ignored. - * @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.api.cloudquotas.v1beta.QuotaPreference|QuotaPreference}. - * 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/v1beta/cloud_quotas.update_quota_preference.js - * region_tag:cloudquotas_v1beta_generated_CloudQuotas_UpdateQuotaPreference_async - */ + /** + * Updates the parameters of a single QuotaPreference. It can updates the + * config in any states, not just the ones pending approval. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. Field mask is used to specify the fields to be overwritten in the + * QuotaPreference resource by the update. + * The fields specified in the update_mask are relative to the resource, not + * the full request. A field will be overwritten if it is in the mask. If the + * user does not provide a mask then all fields will be overwritten. + * @param {google.api.cloudquotas.v1beta.QuotaPreference} request.quotaPreference + * Required. The resource being updated + * @param {boolean} [request.allowMissing] + * Optional. If set to true, and the quota preference is not found, a new one + * will be created. In this situation, `update_mask` is ignored. + * @param {boolean} [request.validateOnly] + * Optional. If set to true, validate the request, but do not actually update. + * Note that a request being valid does not mean that the request is + * guaranteed to be fulfilled. + * @param {number[]} request.ignoreSafetyChecks + * The list of quota safety checks to be ignored. + * @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.api.cloudquotas.v1beta.QuotaPreference|QuotaPreference}. + * 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/v1beta/cloud_quotas.update_quota_preference.js + * region_tag:cloudquotas_v1beta_generated_CloudQuotas_UpdateQuotaPreference_async + */ updateQuotaPreference( - request?: protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest, - options?: CallOptions): - Promise<[ - protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest|undefined, {}|undefined - ]>; + request?: protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.cloudquotas.v1beta.IQuotaPreference, + ( + | protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest + | undefined + ), + {} | undefined, + ] + >; updateQuotaPreference( - request: protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest, - options: CallOptions, - callback: Callback< - protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest, + options: CallOptions, + callback: Callback< + protos.google.api.cloudquotas.v1beta.IQuotaPreference, + | protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateQuotaPreference( - request: protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest, - callback: Callback< - protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest, + callback: Callback< + protos.google.api.cloudquotas.v1beta.IQuotaPreference, + | protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateQuotaPreference( - request?: protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest|undefined, {}|undefined - ]>|void { + | protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.cloudquotas.v1beta.IQuotaPreference, + | protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.cloudquotas.v1beta.IQuotaPreference, + ( + | protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest + | 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({ - 'quota_preference.name': request.quotaPreference!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'quota_preference.name': request.quotaPreference!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateQuotaPreference request %j', request); - const wrappedCallback: Callback< - protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.cloudquotas.v1beta.IQuotaPreference, + | protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateQuotaPreference response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateQuotaPreference(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.cloudquotas.v1beta.IQuotaPreference, - protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateQuotaPreference response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateQuotaPreference(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.cloudquotas.v1beta.IQuotaPreference, + ( + | protos.google.api.cloudquotas.v1beta.IUpdateQuotaPreferenceRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateQuotaPreference response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** - * Lists QuotaInfos of all quotas for a given project, folder or organization. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Parent value of QuotaInfo resources. - * Listing across different resource containers (such as 'projects/-') is not - * allowed. - * - * Example names: - * `projects/123/locations/global/services/compute.googleapis.com` - * `folders/234/locations/global/services/compute.googleapis.com` - * `organizations/345/locations/global/services/compute.googleapis.com` - * @param {number} [request.pageSize] - * Optional. Requested page size. Server may return fewer items than - * requested. If unspecified, server will pick an appropriate default. - * @param {string} [request.pageToken] - * Optional. A token identifying a page of results the server should return. - * @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.api.cloudquotas.v1beta.QuotaInfo|QuotaInfo}. - * 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 `listQuotaInfosAsync()` - * 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 QuotaInfos of all quotas for a given project, folder or organization. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Parent value of QuotaInfo resources. + * Listing across different resource containers (such as 'projects/-') is not + * allowed. + * + * Example names: + * `projects/123/locations/global/services/compute.googleapis.com` + * `folders/234/locations/global/services/compute.googleapis.com` + * `organizations/345/locations/global/services/compute.googleapis.com` + * @param {number} [request.pageSize] + * Optional. Requested page size. Server may return fewer items than + * requested. If unspecified, server will pick an appropriate default. + * @param {string} [request.pageToken] + * Optional. A token identifying a page of results the server should return. + * @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.api.cloudquotas.v1beta.QuotaInfo|QuotaInfo}. + * 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 `listQuotaInfosAsync()` + * 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. + */ listQuotaInfos( - request?: protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest, - options?: CallOptions): - Promise<[ - protos.google.api.cloudquotas.v1beta.IQuotaInfo[], - protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest|null, - protos.google.api.cloudquotas.v1beta.IListQuotaInfosResponse - ]>; + request?: protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.cloudquotas.v1beta.IQuotaInfo[], + protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest | null, + protos.google.api.cloudquotas.v1beta.IListQuotaInfosResponse, + ] + >; listQuotaInfos( - request: protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest, - protos.google.api.cloudquotas.v1beta.IListQuotaInfosResponse|null|undefined, - protos.google.api.cloudquotas.v1beta.IQuotaInfo>): void; + request: protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest, + | protos.google.api.cloudquotas.v1beta.IListQuotaInfosResponse + | null + | undefined, + protos.google.api.cloudquotas.v1beta.IQuotaInfo + >, + ): void; listQuotaInfos( - request: protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest, - callback: PaginationCallback< - protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest, - protos.google.api.cloudquotas.v1beta.IListQuotaInfosResponse|null|undefined, - protos.google.api.cloudquotas.v1beta.IQuotaInfo>): void; + request: protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest, + callback: PaginationCallback< + protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest, + | protos.google.api.cloudquotas.v1beta.IListQuotaInfosResponse + | null + | undefined, + protos.google.api.cloudquotas.v1beta.IQuotaInfo + >, + ): void; listQuotaInfos( - request?: protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest, - protos.google.api.cloudquotas.v1beta.IListQuotaInfosResponse|null|undefined, - protos.google.api.cloudquotas.v1beta.IQuotaInfo>, - callback?: PaginationCallback< - protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest, - protos.google.api.cloudquotas.v1beta.IListQuotaInfosResponse|null|undefined, - protos.google.api.cloudquotas.v1beta.IQuotaInfo>): - Promise<[ - protos.google.api.cloudquotas.v1beta.IQuotaInfo[], - protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest|null, - protos.google.api.cloudquotas.v1beta.IListQuotaInfosResponse - ]>|void { + | protos.google.api.cloudquotas.v1beta.IListQuotaInfosResponse + | null + | undefined, + protos.google.api.cloudquotas.v1beta.IQuotaInfo + >, + callback?: PaginationCallback< + protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest, + | protos.google.api.cloudquotas.v1beta.IListQuotaInfosResponse + | null + | undefined, + protos.google.api.cloudquotas.v1beta.IQuotaInfo + >, + ): Promise< + [ + protos.google.api.cloudquotas.v1beta.IQuotaInfo[], + protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest | null, + protos.google.api.cloudquotas.v1beta.IListQuotaInfosResponse, + ] + > | 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.api.cloudquotas.v1beta.IListQuotaInfosRequest, - protos.google.api.cloudquotas.v1beta.IListQuotaInfosResponse|null|undefined, - protos.google.api.cloudquotas.v1beta.IQuotaInfo>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest, + | protos.google.api.cloudquotas.v1beta.IListQuotaInfosResponse + | null + | undefined, + protos.google.api.cloudquotas.v1beta.IQuotaInfo + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listQuotaInfos values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -880,229 +1156,258 @@ export class CloudQuotasClient { this._log.info('listQuotaInfos request %j', request); return this.innerApiCalls .listQuotaInfos(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.api.cloudquotas.v1beta.IQuotaInfo[], - protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest|null, - protos.google.api.cloudquotas.v1beta.IListQuotaInfosResponse - ]) => { - this._log.info('listQuotaInfos values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.api.cloudquotas.v1beta.IQuotaInfo[], + protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest | null, + protos.google.api.cloudquotas.v1beta.IListQuotaInfosResponse, + ]) => { + this._log.info('listQuotaInfos values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listQuotaInfos`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Parent value of QuotaInfo resources. - * Listing across different resource containers (such as 'projects/-') is not - * allowed. - * - * Example names: - * `projects/123/locations/global/services/compute.googleapis.com` - * `folders/234/locations/global/services/compute.googleapis.com` - * `organizations/345/locations/global/services/compute.googleapis.com` - * @param {number} [request.pageSize] - * Optional. Requested page size. Server may return fewer items than - * requested. If unspecified, server will pick an appropriate default. - * @param {string} [request.pageToken] - * Optional. A token identifying a page of results the server should return. - * @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.api.cloudquotas.v1beta.QuotaInfo|QuotaInfo} 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 `listQuotaInfosAsync()` - * 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 `listQuotaInfos`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Parent value of QuotaInfo resources. + * Listing across different resource containers (such as 'projects/-') is not + * allowed. + * + * Example names: + * `projects/123/locations/global/services/compute.googleapis.com` + * `folders/234/locations/global/services/compute.googleapis.com` + * `organizations/345/locations/global/services/compute.googleapis.com` + * @param {number} [request.pageSize] + * Optional. Requested page size. Server may return fewer items than + * requested. If unspecified, server will pick an appropriate default. + * @param {string} [request.pageToken] + * Optional. A token identifying a page of results the server should return. + * @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.api.cloudquotas.v1beta.QuotaInfo|QuotaInfo} 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 `listQuotaInfosAsync()` + * 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. + */ listQuotaInfosStream( - request?: protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest, - options?: CallOptions): - Transform{ + request?: protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest, + 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['listQuotaInfos']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listQuotaInfos stream %j', request); return this.descriptors.page.listQuotaInfos.createStream( this.innerApiCalls.listQuotaInfos as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listQuotaInfos`, 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. Parent value of QuotaInfo resources. - * Listing across different resource containers (such as 'projects/-') is not - * allowed. - * - * Example names: - * `projects/123/locations/global/services/compute.googleapis.com` - * `folders/234/locations/global/services/compute.googleapis.com` - * `organizations/345/locations/global/services/compute.googleapis.com` - * @param {number} [request.pageSize] - * Optional. Requested page size. Server may return fewer items than - * requested. If unspecified, server will pick an appropriate default. - * @param {string} [request.pageToken] - * Optional. A token identifying a page of results the server should return. - * @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.api.cloudquotas.v1beta.QuotaInfo|QuotaInfo}. 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 include:samples/generated/v1beta/cloud_quotas.list_quota_infos.js - * region_tag:cloudquotas_v1beta_generated_CloudQuotas_ListQuotaInfos_async - */ + /** + * Equivalent to `listQuotaInfos`, 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. Parent value of QuotaInfo resources. + * Listing across different resource containers (such as 'projects/-') is not + * allowed. + * + * Example names: + * `projects/123/locations/global/services/compute.googleapis.com` + * `folders/234/locations/global/services/compute.googleapis.com` + * `organizations/345/locations/global/services/compute.googleapis.com` + * @param {number} [request.pageSize] + * Optional. Requested page size. Server may return fewer items than + * requested. If unspecified, server will pick an appropriate default. + * @param {string} [request.pageToken] + * Optional. A token identifying a page of results the server should return. + * @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.api.cloudquotas.v1beta.QuotaInfo|QuotaInfo}. 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 include:samples/generated/v1beta/cloud_quotas.list_quota_infos.js + * region_tag:cloudquotas_v1beta_generated_CloudQuotas_ListQuotaInfos_async + */ listQuotaInfosAsync( - request?: protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.api.cloudquotas.v1beta.IListQuotaInfosRequest, + 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['listQuotaInfos']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listQuotaInfos iterate %j', request); return this.descriptors.page.listQuotaInfos.asyncIterate( this.innerApiCalls['listQuotaInfos'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } - /** - * Lists QuotaPreferences in a given project, folder or organization. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Parent value of QuotaPreference resources. - * Listing across different resource containers (such as 'projects/-') is not - * allowed. - * - * When the value starts with 'folders' or 'organizations', it lists the - * QuotaPreferences for org quotas in the container. It does not list the - * QuotaPreferences in the descendant projects of the container. - * - * Example parents: - * `projects/123/locations/global` - * @param {number} [request.pageSize] - * Optional. Requested page size. Server may return fewer items than - * requested. If unspecified, server will pick an appropriate default. - * @param {string} [request.pageToken] - * Optional. A token identifying a page of results the server should return. - * @param {string} [request.filter] - * Optional. Filter result QuotaPreferences by their state, type, - * create/update time range. - * - * Example filters: - * `reconciling=true AND request_type=CLOUD_CONSOLE`, - * `reconciling=true OR creation_time>2022-12-03T10:30:00` - * @param {string} [request.orderBy] - * Optional. How to order of the results. By default, the results are ordered - * by create time. - * - * Example orders: - * `quota_id`, - * `service, create_time` - * @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.api.cloudquotas.v1beta.QuotaPreference|QuotaPreference}. - * 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 `listQuotaPreferencesAsync()` - * 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 QuotaPreferences in a given project, folder or organization. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Parent value of QuotaPreference resources. + * Listing across different resource containers (such as 'projects/-') is not + * allowed. + * + * When the value starts with 'folders' or 'organizations', it lists the + * QuotaPreferences for org quotas in the container. It does not list the + * QuotaPreferences in the descendant projects of the container. + * + * Example parents: + * `projects/123/locations/global` + * @param {number} [request.pageSize] + * Optional. Requested page size. Server may return fewer items than + * requested. If unspecified, server will pick an appropriate default. + * @param {string} [request.pageToken] + * Optional. A token identifying a page of results the server should return. + * @param {string} [request.filter] + * Optional. Filter result QuotaPreferences by their state, type, + * create/update time range. + * + * Example filters: + * `reconciling=true AND request_type=CLOUD_CONSOLE`, + * `reconciling=true OR creation_time>2022-12-03T10:30:00` + * @param {string} [request.orderBy] + * Optional. How to order of the results. By default, the results are ordered + * by create time. + * + * Example orders: + * `quota_id`, + * `service, create_time` + * @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.api.cloudquotas.v1beta.QuotaPreference|QuotaPreference}. + * 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 `listQuotaPreferencesAsync()` + * 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. + */ listQuotaPreferences( - request?: protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest, - options?: CallOptions): - Promise<[ - protos.google.api.cloudquotas.v1beta.IQuotaPreference[], - protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest|null, - protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesResponse - ]>; + request?: protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.cloudquotas.v1beta.IQuotaPreference[], + protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest | null, + protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesResponse, + ] + >; listQuotaPreferences( - request: protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest, - protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesResponse|null|undefined, - protos.google.api.cloudquotas.v1beta.IQuotaPreference>): void; + request: protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest, + | protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesResponse + | null + | undefined, + protos.google.api.cloudquotas.v1beta.IQuotaPreference + >, + ): void; listQuotaPreferences( - request: protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest, - callback: PaginationCallback< - protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest, - protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesResponse|null|undefined, - protos.google.api.cloudquotas.v1beta.IQuotaPreference>): void; + request: protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest, + callback: PaginationCallback< + protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest, + | protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesResponse + | null + | undefined, + protos.google.api.cloudquotas.v1beta.IQuotaPreference + >, + ): void; listQuotaPreferences( - request?: protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest, - protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesResponse|null|undefined, - protos.google.api.cloudquotas.v1beta.IQuotaPreference>, - callback?: PaginationCallback< - protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest, - protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesResponse|null|undefined, - protos.google.api.cloudquotas.v1beta.IQuotaPreference>): - Promise<[ - protos.google.api.cloudquotas.v1beta.IQuotaPreference[], - protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest|null, - protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesResponse - ]>|void { + | protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesResponse + | null + | undefined, + protos.google.api.cloudquotas.v1beta.IQuotaPreference + >, + callback?: PaginationCallback< + protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest, + | protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesResponse + | null + | undefined, + protos.google.api.cloudquotas.v1beta.IQuotaPreference + >, + ): Promise< + [ + protos.google.api.cloudquotas.v1beta.IQuotaPreference[], + protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest | null, + protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesResponse, + ] + > | 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.api.cloudquotas.v1beta.IListQuotaPreferencesRequest, - protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesResponse|null|undefined, - protos.google.api.cloudquotas.v1beta.IQuotaPreference>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest, + | protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesResponse + | null + | undefined, + protos.google.api.cloudquotas.v1beta.IQuotaPreference + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listQuotaPreferences values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1111,154 +1416,158 @@ export class CloudQuotasClient { this._log.info('listQuotaPreferences request %j', request); return this.innerApiCalls .listQuotaPreferences(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.api.cloudquotas.v1beta.IQuotaPreference[], - protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest|null, - protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesResponse - ]) => { - this._log.info('listQuotaPreferences values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.api.cloudquotas.v1beta.IQuotaPreference[], + protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest | null, + protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesResponse, + ]) => { + this._log.info('listQuotaPreferences values %j', response); + return [response, input, output]; + }, + ); } -/** - * Equivalent to `listQuotaPreferences`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. Parent value of QuotaPreference resources. - * Listing across different resource containers (such as 'projects/-') is not - * allowed. - * - * When the value starts with 'folders' or 'organizations', it lists the - * QuotaPreferences for org quotas in the container. It does not list the - * QuotaPreferences in the descendant projects of the container. - * - * Example parents: - * `projects/123/locations/global` - * @param {number} [request.pageSize] - * Optional. Requested page size. Server may return fewer items than - * requested. If unspecified, server will pick an appropriate default. - * @param {string} [request.pageToken] - * Optional. A token identifying a page of results the server should return. - * @param {string} [request.filter] - * Optional. Filter result QuotaPreferences by their state, type, - * create/update time range. - * - * Example filters: - * `reconciling=true AND request_type=CLOUD_CONSOLE`, - * `reconciling=true OR creation_time>2022-12-03T10:30:00` - * @param {string} [request.orderBy] - * Optional. How to order of the results. By default, the results are ordered - * by create time. - * - * Example orders: - * `quota_id`, - * `service, create_time` - * @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.api.cloudquotas.v1beta.QuotaPreference|QuotaPreference} 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 `listQuotaPreferencesAsync()` - * 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 `listQuotaPreferences`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. Parent value of QuotaPreference resources. + * Listing across different resource containers (such as 'projects/-') is not + * allowed. + * + * When the value starts with 'folders' or 'organizations', it lists the + * QuotaPreferences for org quotas in the container. It does not list the + * QuotaPreferences in the descendant projects of the container. + * + * Example parents: + * `projects/123/locations/global` + * @param {number} [request.pageSize] + * Optional. Requested page size. Server may return fewer items than + * requested. If unspecified, server will pick an appropriate default. + * @param {string} [request.pageToken] + * Optional. A token identifying a page of results the server should return. + * @param {string} [request.filter] + * Optional. Filter result QuotaPreferences by their state, type, + * create/update time range. + * + * Example filters: + * `reconciling=true AND request_type=CLOUD_CONSOLE`, + * `reconciling=true OR creation_time>2022-12-03T10:30:00` + * @param {string} [request.orderBy] + * Optional. How to order of the results. By default, the results are ordered + * by create time. + * + * Example orders: + * `quota_id`, + * `service, create_time` + * @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.api.cloudquotas.v1beta.QuotaPreference|QuotaPreference} 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 `listQuotaPreferencesAsync()` + * 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. + */ listQuotaPreferencesStream( - request?: protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest, + 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['listQuotaPreferences']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listQuotaPreferences stream %j', request); return this.descriptors.page.listQuotaPreferences.createStream( this.innerApiCalls.listQuotaPreferences as GaxCall, request, - callSettings + callSettings, ); } -/** - * Equivalent to `listQuotaPreferences`, 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. Parent value of QuotaPreference resources. - * Listing across different resource containers (such as 'projects/-') is not - * allowed. - * - * When the value starts with 'folders' or 'organizations', it lists the - * QuotaPreferences for org quotas in the container. It does not list the - * QuotaPreferences in the descendant projects of the container. - * - * Example parents: - * `projects/123/locations/global` - * @param {number} [request.pageSize] - * Optional. Requested page size. Server may return fewer items than - * requested. If unspecified, server will pick an appropriate default. - * @param {string} [request.pageToken] - * Optional. A token identifying a page of results the server should return. - * @param {string} [request.filter] - * Optional. Filter result QuotaPreferences by their state, type, - * create/update time range. - * - * Example filters: - * `reconciling=true AND request_type=CLOUD_CONSOLE`, - * `reconciling=true OR creation_time>2022-12-03T10:30:00` - * @param {string} [request.orderBy] - * Optional. How to order of the results. By default, the results are ordered - * by create time. - * - * Example orders: - * `quota_id`, - * `service, create_time` - * @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.api.cloudquotas.v1beta.QuotaPreference|QuotaPreference}. 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 include:samples/generated/v1beta/cloud_quotas.list_quota_preferences.js - * region_tag:cloudquotas_v1beta_generated_CloudQuotas_ListQuotaPreferences_async - */ + /** + * Equivalent to `listQuotaPreferences`, 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. Parent value of QuotaPreference resources. + * Listing across different resource containers (such as 'projects/-') is not + * allowed. + * + * When the value starts with 'folders' or 'organizations', it lists the + * QuotaPreferences for org quotas in the container. It does not list the + * QuotaPreferences in the descendant projects of the container. + * + * Example parents: + * `projects/123/locations/global` + * @param {number} [request.pageSize] + * Optional. Requested page size. Server may return fewer items than + * requested. If unspecified, server will pick an appropriate default. + * @param {string} [request.pageToken] + * Optional. A token identifying a page of results the server should return. + * @param {string} [request.filter] + * Optional. Filter result QuotaPreferences by their state, type, + * create/update time range. + * + * Example filters: + * `reconciling=true AND request_type=CLOUD_CONSOLE`, + * `reconciling=true OR creation_time>2022-12-03T10:30:00` + * @param {string} [request.orderBy] + * Optional. How to order of the results. By default, the results are ordered + * by create time. + * + * Example orders: + * `quota_id`, + * `service, create_time` + * @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.api.cloudquotas.v1beta.QuotaPreference|QuotaPreference}. 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 include:samples/generated/v1beta/cloud_quotas.list_quota_preferences.js + * region_tag:cloudquotas_v1beta_generated_CloudQuotas_ListQuotaPreferences_async + */ listQuotaPreferencesAsync( - request?: protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.api.cloudquotas.v1beta.IListQuotaPreferencesRequest, + 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['listQuotaPreferences']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch((err) => { + throw err; + }); this._log.info('listQuotaPreferences iterate %j', request); return this.descriptors.page.listQuotaPreferences.asyncIterate( this.innerApiCalls['listQuotaPreferences'] as GaxCall, request as {}, - callSettings + callSettings, ) as AsyncIterable; } // -------------------- @@ -1272,11 +1581,13 @@ export class CloudQuotasClient { * @param {string} location * @returns {string} Resource name string. */ - folderLocationQuotaAdjusterSettingsPath(folder:string,location:string) { - return this.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.render({ - folder: folder, - location: location, - }); + folderLocationQuotaAdjusterSettingsPath(folder: string, location: string) { + return this.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.render( + { + folder: folder, + location: location, + }, + ); } /** @@ -1286,8 +1597,12 @@ export class CloudQuotasClient { * A fully-qualified path representing folder_location_quotaAdjusterSettings resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderLocationQuotaAdjusterSettingsName(folderLocationQuotaAdjusterSettingsName: string) { - return this.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.match(folderLocationQuotaAdjusterSettingsName).folder; + matchFolderFromFolderLocationQuotaAdjusterSettingsName( + folderLocationQuotaAdjusterSettingsName: string, + ) { + return this.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.match( + folderLocationQuotaAdjusterSettingsName, + ).folder; } /** @@ -1297,8 +1612,12 @@ export class CloudQuotasClient { * A fully-qualified path representing folder_location_quotaAdjusterSettings resource. * @returns {string} A string representing the location. */ - matchLocationFromFolderLocationQuotaAdjusterSettingsName(folderLocationQuotaAdjusterSettingsName: string) { - return this.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.match(folderLocationQuotaAdjusterSettingsName).location; + matchLocationFromFolderLocationQuotaAdjusterSettingsName( + folderLocationQuotaAdjusterSettingsName: string, + ) { + return this.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.match( + folderLocationQuotaAdjusterSettingsName, + ).location; } /** @@ -1309,7 +1628,11 @@ export class CloudQuotasClient { * @param {string} quota_preference * @returns {string} Resource name string. */ - folderLocationQuotaPreferencePath(folder:string,location:string,quotaPreference:string) { + folderLocationQuotaPreferencePath( + folder: string, + location: string, + quotaPreference: string, + ) { return this.pathTemplates.folderLocationQuotaPreferencePathTemplate.render({ folder: folder, location: location, @@ -1324,8 +1647,12 @@ export class CloudQuotasClient { * A fully-qualified path representing folder_location_quota_preference resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderLocationQuotaPreferenceName(folderLocationQuotaPreferenceName: string) { - return this.pathTemplates.folderLocationQuotaPreferencePathTemplate.match(folderLocationQuotaPreferenceName).folder; + matchFolderFromFolderLocationQuotaPreferenceName( + folderLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.folderLocationQuotaPreferencePathTemplate.match( + folderLocationQuotaPreferenceName, + ).folder; } /** @@ -1335,8 +1662,12 @@ export class CloudQuotasClient { * A fully-qualified path representing folder_location_quota_preference resource. * @returns {string} A string representing the location. */ - matchLocationFromFolderLocationQuotaPreferenceName(folderLocationQuotaPreferenceName: string) { - return this.pathTemplates.folderLocationQuotaPreferencePathTemplate.match(folderLocationQuotaPreferenceName).location; + matchLocationFromFolderLocationQuotaPreferenceName( + folderLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.folderLocationQuotaPreferencePathTemplate.match( + folderLocationQuotaPreferenceName, + ).location; } /** @@ -1346,8 +1677,12 @@ export class CloudQuotasClient { * A fully-qualified path representing folder_location_quota_preference resource. * @returns {string} A string representing the quota_preference. */ - matchQuotaPreferenceFromFolderLocationQuotaPreferenceName(folderLocationQuotaPreferenceName: string) { - return this.pathTemplates.folderLocationQuotaPreferencePathTemplate.match(folderLocationQuotaPreferenceName).quota_preference; + matchQuotaPreferenceFromFolderLocationQuotaPreferenceName( + folderLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.folderLocationQuotaPreferencePathTemplate.match( + folderLocationQuotaPreferenceName, + ).quota_preference; } /** @@ -1359,13 +1694,20 @@ export class CloudQuotasClient { * @param {string} quota_info * @returns {string} Resource name string. */ - folderLocationServiceQuotaInfoPath(folder:string,location:string,service:string,quotaInfo:string) { - return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.render({ - folder: folder, - location: location, - service: service, - quota_info: quotaInfo, - }); + folderLocationServiceQuotaInfoPath( + folder: string, + location: string, + service: string, + quotaInfo: string, + ) { + return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.render( + { + folder: folder, + location: location, + service: service, + quota_info: quotaInfo, + }, + ); } /** @@ -1375,8 +1717,12 @@ export class CloudQuotasClient { * A fully-qualified path representing folder_location_service_quota_info resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderLocationServiceQuotaInfoName(folderLocationServiceQuotaInfoName: string) { - return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match(folderLocationServiceQuotaInfoName).folder; + matchFolderFromFolderLocationServiceQuotaInfoName( + folderLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match( + folderLocationServiceQuotaInfoName, + ).folder; } /** @@ -1386,8 +1732,12 @@ export class CloudQuotasClient { * A fully-qualified path representing folder_location_service_quota_info resource. * @returns {string} A string representing the location. */ - matchLocationFromFolderLocationServiceQuotaInfoName(folderLocationServiceQuotaInfoName: string) { - return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match(folderLocationServiceQuotaInfoName).location; + matchLocationFromFolderLocationServiceQuotaInfoName( + folderLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match( + folderLocationServiceQuotaInfoName, + ).location; } /** @@ -1397,8 +1747,12 @@ export class CloudQuotasClient { * A fully-qualified path representing folder_location_service_quota_info resource. * @returns {string} A string representing the service. */ - matchServiceFromFolderLocationServiceQuotaInfoName(folderLocationServiceQuotaInfoName: string) { - return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match(folderLocationServiceQuotaInfoName).service; + matchServiceFromFolderLocationServiceQuotaInfoName( + folderLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match( + folderLocationServiceQuotaInfoName, + ).service; } /** @@ -1408,8 +1762,12 @@ export class CloudQuotasClient { * A fully-qualified path representing folder_location_service_quota_info resource. * @returns {string} A string representing the quota_info. */ - matchQuotaInfoFromFolderLocationServiceQuotaInfoName(folderLocationServiceQuotaInfoName: string) { - return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match(folderLocationServiceQuotaInfoName).quota_info; + matchQuotaInfoFromFolderLocationServiceQuotaInfoName( + folderLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match( + folderLocationServiceQuotaInfoName, + ).quota_info; } /** @@ -1419,11 +1777,16 @@ export class CloudQuotasClient { * @param {string} location * @returns {string} Resource name string. */ - organizationLocationQuotaAdjusterSettingsPath(organization:string,location:string) { - return this.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.render({ - organization: organization, - location: location, - }); + organizationLocationQuotaAdjusterSettingsPath( + organization: string, + location: string, + ) { + return this.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.render( + { + organization: organization, + location: location, + }, + ); } /** @@ -1433,8 +1796,12 @@ export class CloudQuotasClient { * A fully-qualified path representing organization_location_quotaAdjusterSettings resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationLocationQuotaAdjusterSettingsName(organizationLocationQuotaAdjusterSettingsName: string) { - return this.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.match(organizationLocationQuotaAdjusterSettingsName).organization; + matchOrganizationFromOrganizationLocationQuotaAdjusterSettingsName( + organizationLocationQuotaAdjusterSettingsName: string, + ) { + return this.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.match( + organizationLocationQuotaAdjusterSettingsName, + ).organization; } /** @@ -1444,8 +1811,12 @@ export class CloudQuotasClient { * A fully-qualified path representing organization_location_quotaAdjusterSettings resource. * @returns {string} A string representing the location. */ - matchLocationFromOrganizationLocationQuotaAdjusterSettingsName(organizationLocationQuotaAdjusterSettingsName: string) { - return this.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.match(organizationLocationQuotaAdjusterSettingsName).location; + matchLocationFromOrganizationLocationQuotaAdjusterSettingsName( + organizationLocationQuotaAdjusterSettingsName: string, + ) { + return this.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.match( + organizationLocationQuotaAdjusterSettingsName, + ).location; } /** @@ -1456,12 +1827,18 @@ export class CloudQuotasClient { * @param {string} quota_preference * @returns {string} Resource name string. */ - organizationLocationQuotaPreferencePath(organization:string,location:string,quotaPreference:string) { - return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.render({ - organization: organization, - location: location, - quota_preference: quotaPreference, - }); + organizationLocationQuotaPreferencePath( + organization: string, + location: string, + quotaPreference: string, + ) { + return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.render( + { + organization: organization, + location: location, + quota_preference: quotaPreference, + }, + ); } /** @@ -1471,8 +1848,12 @@ export class CloudQuotasClient { * A fully-qualified path representing organization_location_quota_preference resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationLocationQuotaPreferenceName(organizationLocationQuotaPreferenceName: string) { - return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match(organizationLocationQuotaPreferenceName).organization; + matchOrganizationFromOrganizationLocationQuotaPreferenceName( + organizationLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match( + organizationLocationQuotaPreferenceName, + ).organization; } /** @@ -1482,8 +1863,12 @@ export class CloudQuotasClient { * A fully-qualified path representing organization_location_quota_preference resource. * @returns {string} A string representing the location. */ - matchLocationFromOrganizationLocationQuotaPreferenceName(organizationLocationQuotaPreferenceName: string) { - return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match(organizationLocationQuotaPreferenceName).location; + matchLocationFromOrganizationLocationQuotaPreferenceName( + organizationLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match( + organizationLocationQuotaPreferenceName, + ).location; } /** @@ -1493,8 +1878,12 @@ export class CloudQuotasClient { * A fully-qualified path representing organization_location_quota_preference resource. * @returns {string} A string representing the quota_preference. */ - matchQuotaPreferenceFromOrganizationLocationQuotaPreferenceName(organizationLocationQuotaPreferenceName: string) { - return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match(organizationLocationQuotaPreferenceName).quota_preference; + matchQuotaPreferenceFromOrganizationLocationQuotaPreferenceName( + organizationLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match( + organizationLocationQuotaPreferenceName, + ).quota_preference; } /** @@ -1506,13 +1895,20 @@ export class CloudQuotasClient { * @param {string} quota_info * @returns {string} Resource name string. */ - organizationLocationServiceQuotaInfoPath(organization:string,location:string,service:string,quotaInfo:string) { - return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.render({ - organization: organization, - location: location, - service: service, - quota_info: quotaInfo, - }); + organizationLocationServiceQuotaInfoPath( + organization: string, + location: string, + service: string, + quotaInfo: string, + ) { + return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.render( + { + organization: organization, + location: location, + service: service, + quota_info: quotaInfo, + }, + ); } /** @@ -1522,8 +1918,12 @@ export class CloudQuotasClient { * A fully-qualified path representing organization_location_service_quota_info resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationLocationServiceQuotaInfoName(organizationLocationServiceQuotaInfoName: string) { - return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match(organizationLocationServiceQuotaInfoName).organization; + matchOrganizationFromOrganizationLocationServiceQuotaInfoName( + organizationLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match( + organizationLocationServiceQuotaInfoName, + ).organization; } /** @@ -1533,8 +1933,12 @@ export class CloudQuotasClient { * A fully-qualified path representing organization_location_service_quota_info resource. * @returns {string} A string representing the location. */ - matchLocationFromOrganizationLocationServiceQuotaInfoName(organizationLocationServiceQuotaInfoName: string) { - return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match(organizationLocationServiceQuotaInfoName).location; + matchLocationFromOrganizationLocationServiceQuotaInfoName( + organizationLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match( + organizationLocationServiceQuotaInfoName, + ).location; } /** @@ -1544,8 +1948,12 @@ export class CloudQuotasClient { * A fully-qualified path representing organization_location_service_quota_info resource. * @returns {string} A string representing the service. */ - matchServiceFromOrganizationLocationServiceQuotaInfoName(organizationLocationServiceQuotaInfoName: string) { - return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match(organizationLocationServiceQuotaInfoName).service; + matchServiceFromOrganizationLocationServiceQuotaInfoName( + organizationLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match( + organizationLocationServiceQuotaInfoName, + ).service; } /** @@ -1555,8 +1963,12 @@ export class CloudQuotasClient { * A fully-qualified path representing organization_location_service_quota_info resource. * @returns {string} A string representing the quota_info. */ - matchQuotaInfoFromOrganizationLocationServiceQuotaInfoName(organizationLocationServiceQuotaInfoName: string) { - return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match(organizationLocationServiceQuotaInfoName).quota_info; + matchQuotaInfoFromOrganizationLocationServiceQuotaInfoName( + organizationLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match( + organizationLocationServiceQuotaInfoName, + ).quota_info; } /** @@ -1566,7 +1978,7 @@ export class CloudQuotasClient { * @param {string} location * @returns {string} Resource name string. */ - projectLocationPath(project:string,location:string) { + projectLocationPath(project: string, location: string) { return this.pathTemplates.projectLocationPathTemplate.render({ project: project, location: location, @@ -1581,7 +1993,9 @@ export class CloudQuotasClient { * @returns {string} A string representing the project. */ matchProjectFromProjectLocationName(projectLocationName: string) { - return this.pathTemplates.projectLocationPathTemplate.match(projectLocationName).project; + return this.pathTemplates.projectLocationPathTemplate.match( + projectLocationName, + ).project; } /** @@ -1592,7 +2006,9 @@ export class CloudQuotasClient { * @returns {string} A string representing the location. */ matchLocationFromProjectLocationName(projectLocationName: string) { - return this.pathTemplates.projectLocationPathTemplate.match(projectLocationName).location; + return this.pathTemplates.projectLocationPathTemplate.match( + projectLocationName, + ).location; } /** @@ -1602,11 +2018,13 @@ export class CloudQuotasClient { * @param {string} location * @returns {string} Resource name string. */ - projectLocationQuotaAdjusterSettingsPath(project:string,location:string) { - return this.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.render({ - project: project, - location: location, - }); + projectLocationQuotaAdjusterSettingsPath(project: string, location: string) { + return this.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.render( + { + project: project, + location: location, + }, + ); } /** @@ -1616,8 +2034,12 @@ export class CloudQuotasClient { * A fully-qualified path representing project_location_quotaAdjusterSettings resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectLocationQuotaAdjusterSettingsName(projectLocationQuotaAdjusterSettingsName: string) { - return this.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.match(projectLocationQuotaAdjusterSettingsName).project; + matchProjectFromProjectLocationQuotaAdjusterSettingsName( + projectLocationQuotaAdjusterSettingsName: string, + ) { + return this.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.match( + projectLocationQuotaAdjusterSettingsName, + ).project; } /** @@ -1627,8 +2049,12 @@ export class CloudQuotasClient { * A fully-qualified path representing project_location_quotaAdjusterSettings resource. * @returns {string} A string representing the location. */ - matchLocationFromProjectLocationQuotaAdjusterSettingsName(projectLocationQuotaAdjusterSettingsName: string) { - return this.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.match(projectLocationQuotaAdjusterSettingsName).location; + matchLocationFromProjectLocationQuotaAdjusterSettingsName( + projectLocationQuotaAdjusterSettingsName: string, + ) { + return this.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.match( + projectLocationQuotaAdjusterSettingsName, + ).location; } /** @@ -1639,12 +2065,18 @@ export class CloudQuotasClient { * @param {string} quota_preference * @returns {string} Resource name string. */ - projectLocationQuotaPreferencePath(project:string,location:string,quotaPreference:string) { - return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.render({ - project: project, - location: location, - quota_preference: quotaPreference, - }); + projectLocationQuotaPreferencePath( + project: string, + location: string, + quotaPreference: string, + ) { + return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.render( + { + project: project, + location: location, + quota_preference: quotaPreference, + }, + ); } /** @@ -1654,8 +2086,12 @@ export class CloudQuotasClient { * A fully-qualified path representing project_location_quota_preference resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectLocationQuotaPreferenceName(projectLocationQuotaPreferenceName: string) { - return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.match(projectLocationQuotaPreferenceName).project; + matchProjectFromProjectLocationQuotaPreferenceName( + projectLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.match( + projectLocationQuotaPreferenceName, + ).project; } /** @@ -1665,8 +2101,12 @@ export class CloudQuotasClient { * A fully-qualified path representing project_location_quota_preference resource. * @returns {string} A string representing the location. */ - matchLocationFromProjectLocationQuotaPreferenceName(projectLocationQuotaPreferenceName: string) { - return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.match(projectLocationQuotaPreferenceName).location; + matchLocationFromProjectLocationQuotaPreferenceName( + projectLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.match( + projectLocationQuotaPreferenceName, + ).location; } /** @@ -1676,8 +2116,12 @@ export class CloudQuotasClient { * A fully-qualified path representing project_location_quota_preference resource. * @returns {string} A string representing the quota_preference. */ - matchQuotaPreferenceFromProjectLocationQuotaPreferenceName(projectLocationQuotaPreferenceName: string) { - return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.match(projectLocationQuotaPreferenceName).quota_preference; + matchQuotaPreferenceFromProjectLocationQuotaPreferenceName( + projectLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.match( + projectLocationQuotaPreferenceName, + ).quota_preference; } /** @@ -1688,7 +2132,11 @@ export class CloudQuotasClient { * @param {string} service * @returns {string} Resource name string. */ - projectLocationServicePath(project:string,location:string,service:string) { + projectLocationServicePath( + project: string, + location: string, + service: string, + ) { return this.pathTemplates.projectLocationServicePathTemplate.render({ project: project, location: location, @@ -1703,8 +2151,12 @@ export class CloudQuotasClient { * A fully-qualified path representing project_location_service resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectLocationServiceName(projectLocationServiceName: string) { - return this.pathTemplates.projectLocationServicePathTemplate.match(projectLocationServiceName).project; + matchProjectFromProjectLocationServiceName( + projectLocationServiceName: string, + ) { + return this.pathTemplates.projectLocationServicePathTemplate.match( + projectLocationServiceName, + ).project; } /** @@ -1714,8 +2166,12 @@ export class CloudQuotasClient { * A fully-qualified path representing project_location_service resource. * @returns {string} A string representing the location. */ - matchLocationFromProjectLocationServiceName(projectLocationServiceName: string) { - return this.pathTemplates.projectLocationServicePathTemplate.match(projectLocationServiceName).location; + matchLocationFromProjectLocationServiceName( + projectLocationServiceName: string, + ) { + return this.pathTemplates.projectLocationServicePathTemplate.match( + projectLocationServiceName, + ).location; } /** @@ -1725,8 +2181,12 @@ export class CloudQuotasClient { * A fully-qualified path representing project_location_service resource. * @returns {string} A string representing the service. */ - matchServiceFromProjectLocationServiceName(projectLocationServiceName: string) { - return this.pathTemplates.projectLocationServicePathTemplate.match(projectLocationServiceName).service; + matchServiceFromProjectLocationServiceName( + projectLocationServiceName: string, + ) { + return this.pathTemplates.projectLocationServicePathTemplate.match( + projectLocationServiceName, + ).service; } /** @@ -1738,13 +2198,20 @@ export class CloudQuotasClient { * @param {string} quota_info * @returns {string} Resource name string. */ - projectLocationServiceQuotaInfoPath(project:string,location:string,service:string,quotaInfo:string) { - return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.render({ - project: project, - location: location, - service: service, - quota_info: quotaInfo, - }); + projectLocationServiceQuotaInfoPath( + project: string, + location: string, + service: string, + quotaInfo: string, + ) { + return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.render( + { + project: project, + location: location, + service: service, + quota_info: quotaInfo, + }, + ); } /** @@ -1754,8 +2221,12 @@ export class CloudQuotasClient { * A fully-qualified path representing project_location_service_quota_info resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectLocationServiceQuotaInfoName(projectLocationServiceQuotaInfoName: string) { - return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match(projectLocationServiceQuotaInfoName).project; + matchProjectFromProjectLocationServiceQuotaInfoName( + projectLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match( + projectLocationServiceQuotaInfoName, + ).project; } /** @@ -1765,8 +2236,12 @@ export class CloudQuotasClient { * A fully-qualified path representing project_location_service_quota_info resource. * @returns {string} A string representing the location. */ - matchLocationFromProjectLocationServiceQuotaInfoName(projectLocationServiceQuotaInfoName: string) { - return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match(projectLocationServiceQuotaInfoName).location; + matchLocationFromProjectLocationServiceQuotaInfoName( + projectLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match( + projectLocationServiceQuotaInfoName, + ).location; } /** @@ -1776,8 +2251,12 @@ export class CloudQuotasClient { * A fully-qualified path representing project_location_service_quota_info resource. * @returns {string} A string representing the service. */ - matchServiceFromProjectLocationServiceQuotaInfoName(projectLocationServiceQuotaInfoName: string) { - return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match(projectLocationServiceQuotaInfoName).service; + matchServiceFromProjectLocationServiceQuotaInfoName( + projectLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match( + projectLocationServiceQuotaInfoName, + ).service; } /** @@ -1787,8 +2266,12 @@ export class CloudQuotasClient { * A fully-qualified path representing project_location_service_quota_info resource. * @returns {string} A string representing the quota_info. */ - matchQuotaInfoFromProjectLocationServiceQuotaInfoName(projectLocationServiceQuotaInfoName: string) { - return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match(projectLocationServiceQuotaInfoName).quota_info; + matchQuotaInfoFromProjectLocationServiceQuotaInfoName( + projectLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match( + projectLocationServiceQuotaInfoName, + ).quota_info; } /** @@ -1799,7 +2282,7 @@ export class CloudQuotasClient { */ close(): Promise { if (this.cloudQuotasStub && !this._terminated) { - return this.cloudQuotasStub.then(stub => { + return this.cloudQuotasStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1807,4 +2290,4 @@ export class CloudQuotasClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-api-cloudquotas/src/v1beta/index.ts b/packages/google-api-cloudquotas/src/v1beta/index.ts index f8841fc1e1ba..217da146b1b0 100644 --- a/packages/google-api-cloudquotas/src/v1beta/index.ts +++ b/packages/google-api-cloudquotas/src/v1beta/index.ts @@ -16,5 +16,5 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {CloudQuotasClient} from './cloud_quotas_client'; -export {QuotaAdjusterSettingsManagerClient} from './quota_adjuster_settings_manager_client'; +export { CloudQuotasClient } from './cloud_quotas_client'; +export { QuotaAdjusterSettingsManagerClient } from './quota_adjuster_settings_manager_client'; diff --git a/packages/google-api-cloudquotas/src/v1beta/quota_adjuster_settings_manager_client.ts b/packages/google-api-cloudquotas/src/v1beta/quota_adjuster_settings_manager_client.ts index 49def0699577..b07b3a24cfd2 100644 --- a/packages/google-api-cloudquotas/src/v1beta/quota_adjuster_settings_manager_client.ts +++ b/packages/google-api-cloudquotas/src/v1beta/quota_adjuster_settings_manager_client.ts @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -49,7 +54,7 @@ export class QuotaAdjusterSettingsManagerClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('cloudquotas'); @@ -62,9 +67,9 @@ export class QuotaAdjusterSettingsManagerClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - pathTemplates: {[name: string]: gax.PathTemplate}; - quotaAdjusterSettingsManagerStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + pathTemplates: { [name: string]: gax.PathTemplate }; + quotaAdjusterSettingsManagerStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of QuotaAdjusterSettingsManagerClient. @@ -105,21 +110,43 @@ export class QuotaAdjusterSettingsManagerClient { * const client = new QuotaAdjusterSettingsManagerClient({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 QuotaAdjusterSettingsManagerClient; - 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 staticMembers = this + .constructor as typeof QuotaAdjusterSettingsManagerClient; + 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 = 'cloudquotas.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -144,7 +171,7 @@ export class QuotaAdjusterSettingsManagerClient { 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; @@ -158,10 +185,7 @@ export class QuotaAdjusterSettingsManagerClient { } // 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 { @@ -182,39 +206,51 @@ export class QuotaAdjusterSettingsManagerClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { - folderLocationQuotaAdjusterSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/locations/{location}/quotaAdjusterSettings' - ), - folderLocationQuotaPreferencePathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/locations/{location}/quotaPreferences/{quota_preference}' - ), - folderLocationServiceQuotaInfoPathTemplate: new this._gaxModule.PathTemplate( - 'folders/{folder}/locations/{location}/services/{service}/quotaInfos/{quota_info}' - ), - organizationLocationQuotaAdjusterSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/locations/{location}/quotaAdjusterSettings' - ), - organizationLocationQuotaPreferencePathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/locations/{location}/quotaPreferences/{quota_preference}' - ), - organizationLocationServiceQuotaInfoPathTemplate: new this._gaxModule.PathTemplate( - 'organizations/{organization}/locations/{location}/services/{service}/quotaInfos/{quota_info}' - ), - projectLocationQuotaAdjusterSettingsPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/quotaAdjusterSettings' - ), - projectLocationQuotaPreferencePathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/quotaPreferences/{quota_preference}' - ), - projectLocationServiceQuotaInfoPathTemplate: new this._gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/services/{service}/quotaInfos/{quota_info}' - ), + folderLocationQuotaAdjusterSettingsPathTemplate: + new this._gaxModule.PathTemplate( + 'folders/{folder}/locations/{location}/quotaAdjusterSettings', + ), + folderLocationQuotaPreferencePathTemplate: + new this._gaxModule.PathTemplate( + 'folders/{folder}/locations/{location}/quotaPreferences/{quota_preference}', + ), + folderLocationServiceQuotaInfoPathTemplate: + new this._gaxModule.PathTemplate( + 'folders/{folder}/locations/{location}/services/{service}/quotaInfos/{quota_info}', + ), + organizationLocationQuotaAdjusterSettingsPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/locations/{location}/quotaAdjusterSettings', + ), + organizationLocationQuotaPreferencePathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/locations/{location}/quotaPreferences/{quota_preference}', + ), + organizationLocationServiceQuotaInfoPathTemplate: + new this._gaxModule.PathTemplate( + 'organizations/{organization}/locations/{location}/services/{service}/quotaInfos/{quota_info}', + ), + projectLocationQuotaAdjusterSettingsPathTemplate: + new this._gaxModule.PathTemplate( + 'projects/{project}/locations/{location}/quotaAdjusterSettings', + ), + projectLocationQuotaPreferencePathTemplate: + new this._gaxModule.PathTemplate( + 'projects/{project}/locations/{location}/quotaPreferences/{quota_preference}', + ), + projectLocationServiceQuotaInfoPathTemplate: + new this._gaxModule.PathTemplate( + 'projects/{project}/locations/{location}/services/{service}/quotaInfos/{quota_info}', + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.api.cloudquotas.v1beta.QuotaAdjusterSettingsManager', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.api.cloudquotas.v1beta.QuotaAdjusterSettingsManager', + 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 @@ -245,36 +281,44 @@ export class QuotaAdjusterSettingsManagerClient { // Put together the "service stub" for // google.api.cloudquotas.v1beta.QuotaAdjusterSettingsManager. this.quotaAdjusterSettingsManagerStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.api.cloudquotas.v1beta.QuotaAdjusterSettingsManager') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (this._protos as any).google.api.cloudquotas.v1beta.QuotaAdjusterSettingsManager, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.api.cloudquotas.v1beta.QuotaAdjusterSettingsManager', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any + (this._protos as any).google.api.cloudquotas.v1beta + .QuotaAdjusterSettingsManager, + 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 quotaAdjusterSettingsManagerStubMethods = - ['updateQuotaAdjusterSettings', 'getQuotaAdjusterSettings']; + const quotaAdjusterSettingsManagerStubMethods = [ + 'updateQuotaAdjusterSettings', + 'getQuotaAdjusterSettings', + ]; for (const methodName of quotaAdjusterSettingsManagerStubMethods) { const callPromise = this.quotaAdjusterSettingsManagerStub.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 = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -289,8 +333,14 @@ export class QuotaAdjusterSettingsManagerClient { * @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 'cloudquotas.googleapis.com'; } @@ -301,8 +351,14 @@ export class QuotaAdjusterSettingsManagerClient { * @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 'cloudquotas.googleapis.com'; } @@ -333,9 +389,7 @@ export class QuotaAdjusterSettingsManagerClient { * @returns {string[]} List of default scopes. */ static get scopes() { - return [ - 'https://www.googleapis.com/auth/cloud-platform' - ]; + return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise; @@ -344,8 +398,9 @@ export class QuotaAdjusterSettingsManagerClient { * 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; @@ -356,197 +411,296 @@ export class QuotaAdjusterSettingsManagerClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Updates the QuotaAdjusterSettings for the specified resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.api.cloudquotas.v1beta.QuotaAdjusterSettings} request.quotaAdjusterSettings - * Required. The QuotaAdjusterSettings to update. - * @param {google.protobuf.FieldMask} [request.updateMask] - * Optional. The list of fields to update. - * @param {boolean} [request.validateOnly] - * Optional. If set to true, checks the syntax of the request but doesn't - * update the quota adjuster settings value. Note that although a request can - * be valid, that doesn't guarantee that the request will be fulfilled. - * @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.api.cloudquotas.v1beta.QuotaAdjusterSettings|QuotaAdjusterSettings}. - * 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/v1beta/quota_adjuster_settings_manager.update_quota_adjuster_settings.js - * region_tag:cloudquotas_v1beta_generated_QuotaAdjusterSettingsManager_UpdateQuotaAdjusterSettings_async - */ + /** + * Updates the QuotaAdjusterSettings for the specified resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.api.cloudquotas.v1beta.QuotaAdjusterSettings} request.quotaAdjusterSettings + * Required. The QuotaAdjusterSettings to update. + * @param {google.protobuf.FieldMask} [request.updateMask] + * Optional. The list of fields to update. + * @param {boolean} [request.validateOnly] + * Optional. If set to true, checks the syntax of the request but doesn't + * update the quota adjuster settings value. Note that although a request can + * be valid, that doesn't guarantee that the request will be fulfilled. + * @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.api.cloudquotas.v1beta.QuotaAdjusterSettings|QuotaAdjusterSettings}. + * 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/v1beta/quota_adjuster_settings_manager.update_quota_adjuster_settings.js + * region_tag:cloudquotas_v1beta_generated_QuotaAdjusterSettingsManager_UpdateQuotaAdjusterSettings_async + */ updateQuotaAdjusterSettings( - request?: protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, - protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, + ( + | protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest + | undefined + ), + {} | undefined, + ] + >; updateQuotaAdjusterSettings( - request: protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, - protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, + | protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateQuotaAdjusterSettings( - request: protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest, - callback: Callback< - protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, - protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest, + callback: Callback< + protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, + | protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; updateQuotaAdjusterSettings( - request?: protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, - protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, - protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, - protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, + | protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, + ( + | protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest + | 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({ - 'quota_adjuster_settings.name': request.quotaAdjusterSettings!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'quota_adjuster_settings.name': + request.quotaAdjusterSettings!.name ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateQuotaAdjusterSettings request %j', request); - const wrappedCallback: Callback< - protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, - protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, + | protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateQuotaAdjusterSettings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateQuotaAdjusterSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, - protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateQuotaAdjusterSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .updateQuotaAdjusterSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, + ( + | protos.google.api.cloudquotas.v1beta.IUpdateQuotaAdjusterSettingsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateQuotaAdjusterSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Gets the QuotaAdjusterSettings for the specified resource. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Name of the `quotaAdjusterSettings` configuration. Only a single - * setting per project is supported. - * @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.api.cloudquotas.v1beta.QuotaAdjusterSettings|QuotaAdjusterSettings}. - * 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/v1beta/quota_adjuster_settings_manager.get_quota_adjuster_settings.js - * region_tag:cloudquotas_v1beta_generated_QuotaAdjusterSettingsManager_GetQuotaAdjusterSettings_async - */ + /** + * Gets the QuotaAdjusterSettings for the specified resource. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Name of the `quotaAdjusterSettings` configuration. Only a single + * setting per project is supported. + * @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.api.cloudquotas.v1beta.QuotaAdjusterSettings|QuotaAdjusterSettings}. + * 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/v1beta/quota_adjuster_settings_manager.get_quota_adjuster_settings.js + * region_tag:cloudquotas_v1beta_generated_QuotaAdjusterSettingsManager_GetQuotaAdjusterSettings_async + */ getQuotaAdjusterSettings( - request?: protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest, - options?: CallOptions): - Promise<[ - protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, - protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest|undefined, {}|undefined - ]>; + request?: protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, + ( + | protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest + | undefined + ), + {} | undefined, + ] + >; getQuotaAdjusterSettings( - request: protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest, - options: CallOptions, - callback: Callback< - protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, - protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest, + options: CallOptions, + callback: Callback< + protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, + | protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getQuotaAdjusterSettings( - request: protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest, - callback: Callback< - protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, - protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest, + callback: Callback< + protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, + | protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): void; getQuotaAdjusterSettings( - request?: protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, - protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, - protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, - protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest|undefined, {}|undefined - ]>|void { + | protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, + | protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, + ( + | protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest + | 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('getQuotaAdjusterSettings request %j', request); - const wrappedCallback: Callback< - protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, - protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, + | protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getQuotaAdjusterSettings response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getQuotaAdjusterSettings(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, - protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest|undefined, - {}|undefined - ]) => { - this._log.info('getQuotaAdjusterSettings response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .getQuotaAdjusterSettings(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings, + ( + | protos.google.api.cloudquotas.v1beta.IGetQuotaAdjusterSettingsRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getQuotaAdjusterSettings response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); @@ -563,11 +717,13 @@ export class QuotaAdjusterSettingsManagerClient { * @param {string} location * @returns {string} Resource name string. */ - folderLocationQuotaAdjusterSettingsPath(folder:string,location:string) { - return this.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.render({ - folder: folder, - location: location, - }); + folderLocationQuotaAdjusterSettingsPath(folder: string, location: string) { + return this.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.render( + { + folder: folder, + location: location, + }, + ); } /** @@ -577,8 +733,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing folder_location_quotaAdjusterSettings resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderLocationQuotaAdjusterSettingsName(folderLocationQuotaAdjusterSettingsName: string) { - return this.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.match(folderLocationQuotaAdjusterSettingsName).folder; + matchFolderFromFolderLocationQuotaAdjusterSettingsName( + folderLocationQuotaAdjusterSettingsName: string, + ) { + return this.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.match( + folderLocationQuotaAdjusterSettingsName, + ).folder; } /** @@ -588,8 +748,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing folder_location_quotaAdjusterSettings resource. * @returns {string} A string representing the location. */ - matchLocationFromFolderLocationQuotaAdjusterSettingsName(folderLocationQuotaAdjusterSettingsName: string) { - return this.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.match(folderLocationQuotaAdjusterSettingsName).location; + matchLocationFromFolderLocationQuotaAdjusterSettingsName( + folderLocationQuotaAdjusterSettingsName: string, + ) { + return this.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.match( + folderLocationQuotaAdjusterSettingsName, + ).location; } /** @@ -600,7 +764,11 @@ export class QuotaAdjusterSettingsManagerClient { * @param {string} quota_preference * @returns {string} Resource name string. */ - folderLocationQuotaPreferencePath(folder:string,location:string,quotaPreference:string) { + folderLocationQuotaPreferencePath( + folder: string, + location: string, + quotaPreference: string, + ) { return this.pathTemplates.folderLocationQuotaPreferencePathTemplate.render({ folder: folder, location: location, @@ -615,8 +783,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing folder_location_quota_preference resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderLocationQuotaPreferenceName(folderLocationQuotaPreferenceName: string) { - return this.pathTemplates.folderLocationQuotaPreferencePathTemplate.match(folderLocationQuotaPreferenceName).folder; + matchFolderFromFolderLocationQuotaPreferenceName( + folderLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.folderLocationQuotaPreferencePathTemplate.match( + folderLocationQuotaPreferenceName, + ).folder; } /** @@ -626,8 +798,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing folder_location_quota_preference resource. * @returns {string} A string representing the location. */ - matchLocationFromFolderLocationQuotaPreferenceName(folderLocationQuotaPreferenceName: string) { - return this.pathTemplates.folderLocationQuotaPreferencePathTemplate.match(folderLocationQuotaPreferenceName).location; + matchLocationFromFolderLocationQuotaPreferenceName( + folderLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.folderLocationQuotaPreferencePathTemplate.match( + folderLocationQuotaPreferenceName, + ).location; } /** @@ -637,8 +813,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing folder_location_quota_preference resource. * @returns {string} A string representing the quota_preference. */ - matchQuotaPreferenceFromFolderLocationQuotaPreferenceName(folderLocationQuotaPreferenceName: string) { - return this.pathTemplates.folderLocationQuotaPreferencePathTemplate.match(folderLocationQuotaPreferenceName).quota_preference; + matchQuotaPreferenceFromFolderLocationQuotaPreferenceName( + folderLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.folderLocationQuotaPreferencePathTemplate.match( + folderLocationQuotaPreferenceName, + ).quota_preference; } /** @@ -650,13 +830,20 @@ export class QuotaAdjusterSettingsManagerClient { * @param {string} quota_info * @returns {string} Resource name string. */ - folderLocationServiceQuotaInfoPath(folder:string,location:string,service:string,quotaInfo:string) { - return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.render({ - folder: folder, - location: location, - service: service, - quota_info: quotaInfo, - }); + folderLocationServiceQuotaInfoPath( + folder: string, + location: string, + service: string, + quotaInfo: string, + ) { + return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.render( + { + folder: folder, + location: location, + service: service, + quota_info: quotaInfo, + }, + ); } /** @@ -666,8 +853,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing folder_location_service_quota_info resource. * @returns {string} A string representing the folder. */ - matchFolderFromFolderLocationServiceQuotaInfoName(folderLocationServiceQuotaInfoName: string) { - return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match(folderLocationServiceQuotaInfoName).folder; + matchFolderFromFolderLocationServiceQuotaInfoName( + folderLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match( + folderLocationServiceQuotaInfoName, + ).folder; } /** @@ -677,8 +868,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing folder_location_service_quota_info resource. * @returns {string} A string representing the location. */ - matchLocationFromFolderLocationServiceQuotaInfoName(folderLocationServiceQuotaInfoName: string) { - return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match(folderLocationServiceQuotaInfoName).location; + matchLocationFromFolderLocationServiceQuotaInfoName( + folderLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match( + folderLocationServiceQuotaInfoName, + ).location; } /** @@ -688,8 +883,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing folder_location_service_quota_info resource. * @returns {string} A string representing the service. */ - matchServiceFromFolderLocationServiceQuotaInfoName(folderLocationServiceQuotaInfoName: string) { - return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match(folderLocationServiceQuotaInfoName).service; + matchServiceFromFolderLocationServiceQuotaInfoName( + folderLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match( + folderLocationServiceQuotaInfoName, + ).service; } /** @@ -699,8 +898,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing folder_location_service_quota_info resource. * @returns {string} A string representing the quota_info. */ - matchQuotaInfoFromFolderLocationServiceQuotaInfoName(folderLocationServiceQuotaInfoName: string) { - return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match(folderLocationServiceQuotaInfoName).quota_info; + matchQuotaInfoFromFolderLocationServiceQuotaInfoName( + folderLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match( + folderLocationServiceQuotaInfoName, + ).quota_info; } /** @@ -710,11 +913,16 @@ export class QuotaAdjusterSettingsManagerClient { * @param {string} location * @returns {string} Resource name string. */ - organizationLocationQuotaAdjusterSettingsPath(organization:string,location:string) { - return this.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.render({ - organization: organization, - location: location, - }); + organizationLocationQuotaAdjusterSettingsPath( + organization: string, + location: string, + ) { + return this.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.render( + { + organization: organization, + location: location, + }, + ); } /** @@ -724,8 +932,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing organization_location_quotaAdjusterSettings resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationLocationQuotaAdjusterSettingsName(organizationLocationQuotaAdjusterSettingsName: string) { - return this.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.match(organizationLocationQuotaAdjusterSettingsName).organization; + matchOrganizationFromOrganizationLocationQuotaAdjusterSettingsName( + organizationLocationQuotaAdjusterSettingsName: string, + ) { + return this.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.match( + organizationLocationQuotaAdjusterSettingsName, + ).organization; } /** @@ -735,8 +947,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing organization_location_quotaAdjusterSettings resource. * @returns {string} A string representing the location. */ - matchLocationFromOrganizationLocationQuotaAdjusterSettingsName(organizationLocationQuotaAdjusterSettingsName: string) { - return this.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.match(organizationLocationQuotaAdjusterSettingsName).location; + matchLocationFromOrganizationLocationQuotaAdjusterSettingsName( + organizationLocationQuotaAdjusterSettingsName: string, + ) { + return this.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.match( + organizationLocationQuotaAdjusterSettingsName, + ).location; } /** @@ -747,12 +963,18 @@ export class QuotaAdjusterSettingsManagerClient { * @param {string} quota_preference * @returns {string} Resource name string. */ - organizationLocationQuotaPreferencePath(organization:string,location:string,quotaPreference:string) { - return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.render({ - organization: organization, - location: location, - quota_preference: quotaPreference, - }); + organizationLocationQuotaPreferencePath( + organization: string, + location: string, + quotaPreference: string, + ) { + return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.render( + { + organization: organization, + location: location, + quota_preference: quotaPreference, + }, + ); } /** @@ -762,8 +984,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing organization_location_quota_preference resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationLocationQuotaPreferenceName(organizationLocationQuotaPreferenceName: string) { - return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match(organizationLocationQuotaPreferenceName).organization; + matchOrganizationFromOrganizationLocationQuotaPreferenceName( + organizationLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match( + organizationLocationQuotaPreferenceName, + ).organization; } /** @@ -773,8 +999,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing organization_location_quota_preference resource. * @returns {string} A string representing the location. */ - matchLocationFromOrganizationLocationQuotaPreferenceName(organizationLocationQuotaPreferenceName: string) { - return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match(organizationLocationQuotaPreferenceName).location; + matchLocationFromOrganizationLocationQuotaPreferenceName( + organizationLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match( + organizationLocationQuotaPreferenceName, + ).location; } /** @@ -784,8 +1014,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing organization_location_quota_preference resource. * @returns {string} A string representing the quota_preference. */ - matchQuotaPreferenceFromOrganizationLocationQuotaPreferenceName(organizationLocationQuotaPreferenceName: string) { - return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match(organizationLocationQuotaPreferenceName).quota_preference; + matchQuotaPreferenceFromOrganizationLocationQuotaPreferenceName( + organizationLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match( + organizationLocationQuotaPreferenceName, + ).quota_preference; } /** @@ -797,13 +1031,20 @@ export class QuotaAdjusterSettingsManagerClient { * @param {string} quota_info * @returns {string} Resource name string. */ - organizationLocationServiceQuotaInfoPath(organization:string,location:string,service:string,quotaInfo:string) { - return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.render({ - organization: organization, - location: location, - service: service, - quota_info: quotaInfo, - }); + organizationLocationServiceQuotaInfoPath( + organization: string, + location: string, + service: string, + quotaInfo: string, + ) { + return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.render( + { + organization: organization, + location: location, + service: service, + quota_info: quotaInfo, + }, + ); } /** @@ -813,8 +1054,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing organization_location_service_quota_info resource. * @returns {string} A string representing the organization. */ - matchOrganizationFromOrganizationLocationServiceQuotaInfoName(organizationLocationServiceQuotaInfoName: string) { - return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match(organizationLocationServiceQuotaInfoName).organization; + matchOrganizationFromOrganizationLocationServiceQuotaInfoName( + organizationLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match( + organizationLocationServiceQuotaInfoName, + ).organization; } /** @@ -824,8 +1069,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing organization_location_service_quota_info resource. * @returns {string} A string representing the location. */ - matchLocationFromOrganizationLocationServiceQuotaInfoName(organizationLocationServiceQuotaInfoName: string) { - return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match(organizationLocationServiceQuotaInfoName).location; + matchLocationFromOrganizationLocationServiceQuotaInfoName( + organizationLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match( + organizationLocationServiceQuotaInfoName, + ).location; } /** @@ -835,8 +1084,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing organization_location_service_quota_info resource. * @returns {string} A string representing the service. */ - matchServiceFromOrganizationLocationServiceQuotaInfoName(organizationLocationServiceQuotaInfoName: string) { - return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match(organizationLocationServiceQuotaInfoName).service; + matchServiceFromOrganizationLocationServiceQuotaInfoName( + organizationLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match( + organizationLocationServiceQuotaInfoName, + ).service; } /** @@ -846,8 +1099,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing organization_location_service_quota_info resource. * @returns {string} A string representing the quota_info. */ - matchQuotaInfoFromOrganizationLocationServiceQuotaInfoName(organizationLocationServiceQuotaInfoName: string) { - return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match(organizationLocationServiceQuotaInfoName).quota_info; + matchQuotaInfoFromOrganizationLocationServiceQuotaInfoName( + organizationLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match( + organizationLocationServiceQuotaInfoName, + ).quota_info; } /** @@ -857,11 +1114,13 @@ export class QuotaAdjusterSettingsManagerClient { * @param {string} location * @returns {string} Resource name string. */ - projectLocationQuotaAdjusterSettingsPath(project:string,location:string) { - return this.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.render({ - project: project, - location: location, - }); + projectLocationQuotaAdjusterSettingsPath(project: string, location: string) { + return this.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.render( + { + project: project, + location: location, + }, + ); } /** @@ -871,8 +1130,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing project_location_quotaAdjusterSettings resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectLocationQuotaAdjusterSettingsName(projectLocationQuotaAdjusterSettingsName: string) { - return this.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.match(projectLocationQuotaAdjusterSettingsName).project; + matchProjectFromProjectLocationQuotaAdjusterSettingsName( + projectLocationQuotaAdjusterSettingsName: string, + ) { + return this.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.match( + projectLocationQuotaAdjusterSettingsName, + ).project; } /** @@ -882,8 +1145,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing project_location_quotaAdjusterSettings resource. * @returns {string} A string representing the location. */ - matchLocationFromProjectLocationQuotaAdjusterSettingsName(projectLocationQuotaAdjusterSettingsName: string) { - return this.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.match(projectLocationQuotaAdjusterSettingsName).location; + matchLocationFromProjectLocationQuotaAdjusterSettingsName( + projectLocationQuotaAdjusterSettingsName: string, + ) { + return this.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.match( + projectLocationQuotaAdjusterSettingsName, + ).location; } /** @@ -894,12 +1161,18 @@ export class QuotaAdjusterSettingsManagerClient { * @param {string} quota_preference * @returns {string} Resource name string. */ - projectLocationQuotaPreferencePath(project:string,location:string,quotaPreference:string) { - return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.render({ - project: project, - location: location, - quota_preference: quotaPreference, - }); + projectLocationQuotaPreferencePath( + project: string, + location: string, + quotaPreference: string, + ) { + return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.render( + { + project: project, + location: location, + quota_preference: quotaPreference, + }, + ); } /** @@ -909,8 +1182,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing project_location_quota_preference resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectLocationQuotaPreferenceName(projectLocationQuotaPreferenceName: string) { - return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.match(projectLocationQuotaPreferenceName).project; + matchProjectFromProjectLocationQuotaPreferenceName( + projectLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.match( + projectLocationQuotaPreferenceName, + ).project; } /** @@ -920,8 +1197,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing project_location_quota_preference resource. * @returns {string} A string representing the location. */ - matchLocationFromProjectLocationQuotaPreferenceName(projectLocationQuotaPreferenceName: string) { - return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.match(projectLocationQuotaPreferenceName).location; + matchLocationFromProjectLocationQuotaPreferenceName( + projectLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.match( + projectLocationQuotaPreferenceName, + ).location; } /** @@ -931,8 +1212,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing project_location_quota_preference resource. * @returns {string} A string representing the quota_preference. */ - matchQuotaPreferenceFromProjectLocationQuotaPreferenceName(projectLocationQuotaPreferenceName: string) { - return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.match(projectLocationQuotaPreferenceName).quota_preference; + matchQuotaPreferenceFromProjectLocationQuotaPreferenceName( + projectLocationQuotaPreferenceName: string, + ) { + return this.pathTemplates.projectLocationQuotaPreferencePathTemplate.match( + projectLocationQuotaPreferenceName, + ).quota_preference; } /** @@ -944,13 +1229,20 @@ export class QuotaAdjusterSettingsManagerClient { * @param {string} quota_info * @returns {string} Resource name string. */ - projectLocationServiceQuotaInfoPath(project:string,location:string,service:string,quotaInfo:string) { - return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.render({ - project: project, - location: location, - service: service, - quota_info: quotaInfo, - }); + projectLocationServiceQuotaInfoPath( + project: string, + location: string, + service: string, + quotaInfo: string, + ) { + return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.render( + { + project: project, + location: location, + service: service, + quota_info: quotaInfo, + }, + ); } /** @@ -960,8 +1252,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing project_location_service_quota_info resource. * @returns {string} A string representing the project. */ - matchProjectFromProjectLocationServiceQuotaInfoName(projectLocationServiceQuotaInfoName: string) { - return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match(projectLocationServiceQuotaInfoName).project; + matchProjectFromProjectLocationServiceQuotaInfoName( + projectLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match( + projectLocationServiceQuotaInfoName, + ).project; } /** @@ -971,8 +1267,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing project_location_service_quota_info resource. * @returns {string} A string representing the location. */ - matchLocationFromProjectLocationServiceQuotaInfoName(projectLocationServiceQuotaInfoName: string) { - return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match(projectLocationServiceQuotaInfoName).location; + matchLocationFromProjectLocationServiceQuotaInfoName( + projectLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match( + projectLocationServiceQuotaInfoName, + ).location; } /** @@ -982,8 +1282,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing project_location_service_quota_info resource. * @returns {string} A string representing the service. */ - matchServiceFromProjectLocationServiceQuotaInfoName(projectLocationServiceQuotaInfoName: string) { - return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match(projectLocationServiceQuotaInfoName).service; + matchServiceFromProjectLocationServiceQuotaInfoName( + projectLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match( + projectLocationServiceQuotaInfoName, + ).service; } /** @@ -993,8 +1297,12 @@ export class QuotaAdjusterSettingsManagerClient { * A fully-qualified path representing project_location_service_quota_info resource. * @returns {string} A string representing the quota_info. */ - matchQuotaInfoFromProjectLocationServiceQuotaInfoName(projectLocationServiceQuotaInfoName: string) { - return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match(projectLocationServiceQuotaInfoName).quota_info; + matchQuotaInfoFromProjectLocationServiceQuotaInfoName( + projectLocationServiceQuotaInfoName: string, + ) { + return this.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match( + projectLocationServiceQuotaInfoName, + ).quota_info; } /** @@ -1005,7 +1313,7 @@ export class QuotaAdjusterSettingsManagerClient { */ close(): Promise { if (this.quotaAdjusterSettingsManagerStub && !this._terminated) { - return this.quotaAdjusterSettingsManagerStub.then(stub => { + return this.quotaAdjusterSettingsManagerStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -1013,4 +1321,4 @@ export class QuotaAdjusterSettingsManagerClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-api-cloudquotas/system-test/fixtures/sample/src/index.ts b/packages/google-api-cloudquotas/system-test/fixtures/sample/src/index.ts index b083ef68f939..10b35ab87161 100644 --- a/packages/google-api-cloudquotas/system-test/fixtures/sample/src/index.ts +++ b/packages/google-api-cloudquotas/system-test/fixtures/sample/src/index.ts @@ -16,7 +16,7 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {CloudQuotasClient} from '@google-cloud/cloudquotas'; +import { CloudQuotasClient } from '@google-cloud/cloudquotas'; // check that the client class type name can be used function doStuffWithCloudQuotasClient(client: CloudQuotasClient) { diff --git a/packages/google-api-cloudquotas/system-test/install.ts b/packages/google-api-cloudquotas/system-test/install.ts index 394f3362d203..ccf167042d2e 100644 --- a/packages/google-api-cloudquotas/system-test/install.ts +++ b/packages/google-api-cloudquotas/system-test/install.ts @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - ts: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/packages/google-api-cloudquotas/test/gapic_cloud_quotas_v1.ts b/packages/google-api-cloudquotas/test/gapic_cloud_quotas_v1.ts index c1be953b9469..5f91ecfb54db 100644 --- a/packages/google-api-cloudquotas/test/gapic_cloud_quotas_v1.ts +++ b/packages/google-api-cloudquotas/test/gapic_cloud_quotas_v1.ts @@ -19,1556 +19,2144 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as cloudquotasModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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 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.CloudQuotasClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new cloudquotasModule.v1.CloudQuotasClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'cloudquotas.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new cloudquotasModule.v1.CloudQuotasClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new cloudquotasModule.v1.CloudQuotasClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'cloudquotas.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 = cloudquotasModule.v1.CloudQuotasClient.servicePath; - assert.strictEqual(servicePath, 'cloudquotas.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = cloudquotasModule.v1.CloudQuotasClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'cloudquotas.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudquotas.example.com'); - }); + it('has universeDomain', () => { + const client = new cloudquotasModule.v1.CloudQuotasClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudquotas.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 = cloudquotasModule.v1.CloudQuotasClient.servicePath; + assert.strictEqual(servicePath, 'cloudquotas.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = cloudquotasModule.v1.CloudQuotasClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'cloudquotas.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudquotas.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 cloudquotasModule.v1.CloudQuotasClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudquotas.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 cloudquotasModule.v1.CloudQuotasClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudquotas.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 cloudquotasModule.v1.CloudQuotasClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudquotas.example.com'); + }); - it('has port', () => { - const port = cloudquotasModule.v1.CloudQuotasClient.port; - assert(port); - assert(typeof port === 'number'); + 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 cloudquotasModule.v1.CloudQuotasClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudquotas.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with no option', () => { - const client = new cloudquotasModule.v1.CloudQuotasClient(); - assert(client); + 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 cloudquotasModule.v1.CloudQuotasClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudquotas.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with gRPC fallback', () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - fallback: true, - }); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new cloudquotasModule.v1.CloudQuotasClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.cloudQuotasStub, undefined); - await client.initialize(); - assert(client.cloudQuotasStub); - }); + it('has port', () => { + const port = cloudquotasModule.v1.CloudQuotasClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the initialized client', done => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.cloudQuotasStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new cloudquotasModule.v1.CloudQuotasClient(); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.cloudQuotasStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new cloudquotasModule.v1.CloudQuotasClient({ - 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 initialize method and supports deferred initialization', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.cloudQuotasStub, undefined); + await client.initialize(); + assert(client.cloudQuotasStub); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new cloudquotasModule.v1.CloudQuotasClient({ - 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('has close method for the initialized client', (done) => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.cloudQuotasStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('getQuotaInfo', () => { - it('invokes getQuotaInfo without error', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.GetQuotaInfoRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.GetQuotaInfoRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.cloudquotas.v1.QuotaInfo() - ); - client.innerApiCalls.getQuotaInfo = stubSimpleCall(expectedResponse); - const [response] = await client.getQuotaInfo(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getQuotaInfo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQuotaInfo 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 cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.cloudQuotasStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getQuotaInfo without error using callback', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.GetQuotaInfoRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.GetQuotaInfoRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.cloudquotas.v1.QuotaInfo() - ); - client.innerApiCalls.getQuotaInfo = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getQuotaInfo( - request, - (err?: Error|null, result?: protos.google.api.cloudquotas.v1.IQuotaInfo|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getQuotaInfo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQuotaInfo 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 cloudquotasModule.v1.CloudQuotasClient({ + 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 getQuotaInfo with error', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.GetQuotaInfoRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.GetQuotaInfoRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getQuotaInfo = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getQuotaInfo(request), expectedError); - const actualRequest = (client.innerApiCalls.getQuotaInfo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQuotaInfo 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 cloudquotasModule.v1.CloudQuotasClient({ + 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('getQuotaInfo', () => { + it('invokes getQuotaInfo without error', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.GetQuotaInfoRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.GetQuotaInfoRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.cloudquotas.v1.QuotaInfo(), + ); + client.innerApiCalls.getQuotaInfo = stubSimpleCall(expectedResponse); + const [response] = await client.getQuotaInfo(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getQuotaInfo as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQuotaInfo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getQuotaInfo with closed client', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.GetQuotaInfoRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.GetQuotaInfoRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getQuotaInfo(request), expectedError); - }); + it('invokes getQuotaInfo without error using callback', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.GetQuotaInfoRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.GetQuotaInfoRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.cloudquotas.v1.QuotaInfo(), + ); + client.innerApiCalls.getQuotaInfo = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getQuotaInfo( + request, + ( + err?: Error | null, + result?: protos.google.api.cloudquotas.v1.IQuotaInfo | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getQuotaInfo as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQuotaInfo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getQuotaPreference', () => { - it('invokes getQuotaPreference without error', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.GetQuotaPreferenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.GetQuotaPreferenceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.cloudquotas.v1.QuotaPreference() - ); - client.innerApiCalls.getQuotaPreference = stubSimpleCall(expectedResponse); - const [response] = await client.getQuotaPreference(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getQuotaPreference as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQuotaPreference as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getQuotaInfo with error', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.GetQuotaInfoRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.GetQuotaInfoRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getQuotaInfo = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getQuotaInfo(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getQuotaInfo as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQuotaInfo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getQuotaPreference without error using callback', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.GetQuotaPreferenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.GetQuotaPreferenceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.cloudquotas.v1.QuotaPreference() - ); - client.innerApiCalls.getQuotaPreference = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getQuotaPreference( - request, - (err?: Error|null, result?: protos.google.api.cloudquotas.v1.IQuotaPreference|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getQuotaPreference as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQuotaPreference as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getQuotaInfo with closed client', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.GetQuotaInfoRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.GetQuotaInfoRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getQuotaInfo(request), expectedError); + }); + }); + + describe('getQuotaPreference', () => { + it('invokes getQuotaPreference without error', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.GetQuotaPreferenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.GetQuotaPreferenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.cloudquotas.v1.QuotaPreference(), + ); + client.innerApiCalls.getQuotaPreference = + stubSimpleCall(expectedResponse); + const [response] = await client.getQuotaPreference(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getQuotaPreference as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQuotaPreference as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getQuotaPreference with error', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.GetQuotaPreferenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.GetQuotaPreferenceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getQuotaPreference = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getQuotaPreference(request), expectedError); - const actualRequest = (client.innerApiCalls.getQuotaPreference as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQuotaPreference as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getQuotaPreference without error using callback', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.GetQuotaPreferenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.GetQuotaPreferenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.cloudquotas.v1.QuotaPreference(), + ); + client.innerApiCalls.getQuotaPreference = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getQuotaPreference( + request, + ( + err?: Error | null, + result?: protos.google.api.cloudquotas.v1.IQuotaPreference | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getQuotaPreference as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQuotaPreference as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getQuotaPreference with closed client', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.GetQuotaPreferenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.GetQuotaPreferenceRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getQuotaPreference(request), expectedError); - }); + it('invokes getQuotaPreference with error', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.GetQuotaPreferenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.GetQuotaPreferenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getQuotaPreference = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getQuotaPreference(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getQuotaPreference as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQuotaPreference as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createQuotaPreference', () => { - it('invokes createQuotaPreference without error', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.CreateQuotaPreferenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.CreateQuotaPreferenceRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.cloudquotas.v1.QuotaPreference() - ); - client.innerApiCalls.createQuotaPreference = stubSimpleCall(expectedResponse); - const [response] = await client.createQuotaPreference(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createQuotaPreference as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createQuotaPreference as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getQuotaPreference with closed client', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.GetQuotaPreferenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.GetQuotaPreferenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getQuotaPreference(request), expectedError); + }); + }); + + describe('createQuotaPreference', () => { + it('invokes createQuotaPreference without error', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.CreateQuotaPreferenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.CreateQuotaPreferenceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.cloudquotas.v1.QuotaPreference(), + ); + client.innerApiCalls.createQuotaPreference = + stubSimpleCall(expectedResponse); + const [response] = await client.createQuotaPreference(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createQuotaPreference as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createQuotaPreference as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createQuotaPreference without error using callback', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.CreateQuotaPreferenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.CreateQuotaPreferenceRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.cloudquotas.v1.QuotaPreference() - ); - client.innerApiCalls.createQuotaPreference = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createQuotaPreference( - request, - (err?: Error|null, result?: protos.google.api.cloudquotas.v1.IQuotaPreference|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createQuotaPreference as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createQuotaPreference as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createQuotaPreference without error using callback', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.CreateQuotaPreferenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.CreateQuotaPreferenceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.cloudquotas.v1.QuotaPreference(), + ); + client.innerApiCalls.createQuotaPreference = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createQuotaPreference( + request, + ( + err?: Error | null, + result?: protos.google.api.cloudquotas.v1.IQuotaPreference | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createQuotaPreference as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createQuotaPreference as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createQuotaPreference with error', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.CreateQuotaPreferenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.CreateQuotaPreferenceRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createQuotaPreference = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createQuotaPreference(request), expectedError); - const actualRequest = (client.innerApiCalls.createQuotaPreference as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createQuotaPreference as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createQuotaPreference with error', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.CreateQuotaPreferenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.CreateQuotaPreferenceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createQuotaPreference = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createQuotaPreference(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createQuotaPreference as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createQuotaPreference as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createQuotaPreference with closed client', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.CreateQuotaPreferenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.CreateQuotaPreferenceRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createQuotaPreference(request), expectedError); - }); + it('invokes createQuotaPreference with closed client', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.CreateQuotaPreferenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.CreateQuotaPreferenceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createQuotaPreference(request), + expectedError, + ); + }); + }); + + describe('updateQuotaPreference', () => { + it('invokes updateQuotaPreference without error', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.UpdateQuotaPreferenceRequest(), + ); + request.quotaPreference ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.UpdateQuotaPreferenceRequest', + ['quotaPreference', 'name'], + ); + request.quotaPreference.name = defaultValue1; + const expectedHeaderRequestParams = `quota_preference.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.cloudquotas.v1.QuotaPreference(), + ); + client.innerApiCalls.updateQuotaPreference = + stubSimpleCall(expectedResponse); + const [response] = await client.updateQuotaPreference(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateQuotaPreference as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateQuotaPreference as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateQuotaPreference', () => { - it('invokes updateQuotaPreference without error', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.UpdateQuotaPreferenceRequest() - ); - request.quotaPreference ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.UpdateQuotaPreferenceRequest', ['quotaPreference', 'name']); - request.quotaPreference.name = defaultValue1; - const expectedHeaderRequestParams = `quota_preference.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.cloudquotas.v1.QuotaPreference() - ); - client.innerApiCalls.updateQuotaPreference = stubSimpleCall(expectedResponse); - const [response] = await client.updateQuotaPreference(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateQuotaPreference as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateQuotaPreference as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateQuotaPreference without error using callback', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.UpdateQuotaPreferenceRequest(), + ); + request.quotaPreference ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.UpdateQuotaPreferenceRequest', + ['quotaPreference', 'name'], + ); + request.quotaPreference.name = defaultValue1; + const expectedHeaderRequestParams = `quota_preference.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.cloudquotas.v1.QuotaPreference(), + ); + client.innerApiCalls.updateQuotaPreference = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateQuotaPreference( + request, + ( + err?: Error | null, + result?: protos.google.api.cloudquotas.v1.IQuotaPreference | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateQuotaPreference as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateQuotaPreference as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateQuotaPreference without error using callback', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.UpdateQuotaPreferenceRequest() - ); - request.quotaPreference ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.UpdateQuotaPreferenceRequest', ['quotaPreference', 'name']); - request.quotaPreference.name = defaultValue1; - const expectedHeaderRequestParams = `quota_preference.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.cloudquotas.v1.QuotaPreference() - ); - client.innerApiCalls.updateQuotaPreference = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateQuotaPreference( - request, - (err?: Error|null, result?: protos.google.api.cloudquotas.v1.IQuotaPreference|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateQuotaPreference as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateQuotaPreference as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateQuotaPreference with error', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.UpdateQuotaPreferenceRequest(), + ); + request.quotaPreference ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.UpdateQuotaPreferenceRequest', + ['quotaPreference', 'name'], + ); + request.quotaPreference.name = defaultValue1; + const expectedHeaderRequestParams = `quota_preference.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateQuotaPreference = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateQuotaPreference(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateQuotaPreference as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateQuotaPreference as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateQuotaPreference with error', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.UpdateQuotaPreferenceRequest() - ); - request.quotaPreference ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.UpdateQuotaPreferenceRequest', ['quotaPreference', 'name']); - request.quotaPreference.name = defaultValue1; - const expectedHeaderRequestParams = `quota_preference.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateQuotaPreference = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateQuotaPreference(request), expectedError); - const actualRequest = (client.innerApiCalls.updateQuotaPreference as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateQuotaPreference as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateQuotaPreference with closed client', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.UpdateQuotaPreferenceRequest(), + ); + request.quotaPreference ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.UpdateQuotaPreferenceRequest', + ['quotaPreference', 'name'], + ); + request.quotaPreference.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateQuotaPreference(request), + expectedError, + ); + }); + }); + + describe('listQuotaInfos', () => { + it('invokes listQuotaInfos without error', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.ListQuotaInfosRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.ListQuotaInfosRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), + generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), + generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), + ]; + client.innerApiCalls.listQuotaInfos = stubSimpleCall(expectedResponse); + const [response] = await client.listQuotaInfos(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listQuotaInfos as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listQuotaInfos as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateQuotaPreference with closed client', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.UpdateQuotaPreferenceRequest() - ); - request.quotaPreference ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.UpdateQuotaPreferenceRequest', ['quotaPreference', 'name']); - request.quotaPreference.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateQuotaPreference(request), expectedError); - }); + it('invokes listQuotaInfos without error using callback', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.ListQuotaInfosRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.ListQuotaInfosRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), + generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), + generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), + ]; + client.innerApiCalls.listQuotaInfos = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listQuotaInfos( + request, + ( + err?: Error | null, + result?: protos.google.api.cloudquotas.v1.IQuotaInfo[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listQuotaInfos as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listQuotaInfos as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listQuotaInfos', () => { - it('invokes listQuotaInfos without error', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.ListQuotaInfosRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.ListQuotaInfosRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), - ]; - client.innerApiCalls.listQuotaInfos = stubSimpleCall(expectedResponse); - const [response] = await client.listQuotaInfos(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listQuotaInfos as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listQuotaInfos as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listQuotaInfos with error', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.ListQuotaInfosRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.ListQuotaInfosRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listQuotaInfos = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listQuotaInfos(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listQuotaInfos as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listQuotaInfos as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listQuotaInfos without error using callback', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.ListQuotaInfosRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.ListQuotaInfosRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), - ]; - client.innerApiCalls.listQuotaInfos = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listQuotaInfos( - request, - (err?: Error|null, result?: protos.google.api.cloudquotas.v1.IQuotaInfo[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listQuotaInfos as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listQuotaInfos as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listQuotaInfosStream without error', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.ListQuotaInfosRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.ListQuotaInfosRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), + generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), + generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), + ]; + client.descriptors.page.listQuotaInfos.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listQuotaInfosStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.cloudquotas.v1.QuotaInfo[] = []; + stream.on( + 'data', + (response: protos.google.api.cloudquotas.v1.QuotaInfo) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listQuotaInfos with error', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.ListQuotaInfosRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.ListQuotaInfosRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listQuotaInfos = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listQuotaInfos(request), expectedError); - const actualRequest = (client.innerApiCalls.listQuotaInfos as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listQuotaInfos as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listQuotaInfos.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listQuotaInfos, request), + ); + assert( + (client.descriptors.page.listQuotaInfos.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listQuotaInfosStream without error', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.ListQuotaInfosRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.ListQuotaInfosRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), - ]; - client.descriptors.page.listQuotaInfos.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listQuotaInfosStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.cloudquotas.v1.QuotaInfo[] = []; - stream.on('data', (response: protos.google.api.cloudquotas.v1.QuotaInfo) => { - 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.listQuotaInfos.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listQuotaInfos, request)); - assert( - (client.descriptors.page.listQuotaInfos.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listQuotaInfosStream with error', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.ListQuotaInfosRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.ListQuotaInfosRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listQuotaInfos.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listQuotaInfosStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.cloudquotas.v1.QuotaInfo[] = []; + stream.on( + 'data', + (response: protos.google.api.cloudquotas.v1.QuotaInfo) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listQuotaInfosStream with error', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.ListQuotaInfosRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.ListQuotaInfosRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listQuotaInfos.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listQuotaInfosStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.cloudquotas.v1.QuotaInfo[] = []; - stream.on('data', (response: protos.google.api.cloudquotas.v1.QuotaInfo) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listQuotaInfos.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listQuotaInfos, request)); - assert( - (client.descriptors.page.listQuotaInfos.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listQuotaInfos.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listQuotaInfos, request), + ); + assert( + (client.descriptors.page.listQuotaInfos.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listQuotaInfos without error', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.ListQuotaInfosRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.ListQuotaInfosRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), - ]; - client.descriptors.page.listQuotaInfos.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.api.cloudquotas.v1.IQuotaInfo[] = []; - const iterable = client.listQuotaInfosAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listQuotaInfos.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listQuotaInfos.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listQuotaInfos without error', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.ListQuotaInfosRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.ListQuotaInfosRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), + generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), + generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaInfo()), + ]; + client.descriptors.page.listQuotaInfos.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.api.cloudquotas.v1.IQuotaInfo[] = []; + const iterable = client.listQuotaInfosAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listQuotaInfos.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listQuotaInfos.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listQuotaInfos with error', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.ListQuotaInfosRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.ListQuotaInfosRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listQuotaInfos.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listQuotaInfosAsync(request); - await assert.rejects(async () => { - const responses: protos.google.api.cloudquotas.v1.IQuotaInfo[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listQuotaInfos.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listQuotaInfos.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listQuotaInfos with error', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.ListQuotaInfosRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.ListQuotaInfosRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listQuotaInfos.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listQuotaInfosAsync(request); + await assert.rejects(async () => { + const responses: protos.google.api.cloudquotas.v1.IQuotaInfo[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listQuotaInfos.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listQuotaInfos.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listQuotaPreferences', () => { + it('invokes listQuotaPreferences without error', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.ListQuotaPreferencesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.ListQuotaPreferencesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.cloudquotas.v1.QuotaPreference(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1.QuotaPreference(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1.QuotaPreference(), + ), + ]; + client.innerApiCalls.listQuotaPreferences = + stubSimpleCall(expectedResponse); + const [response] = await client.listQuotaPreferences(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listQuotaPreferences as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listQuotaPreferences as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listQuotaPreferences', () => { - it('invokes listQuotaPreferences without error', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.ListQuotaPreferencesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.ListQuotaPreferencesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaPreference()), - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaPreference()), - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaPreference()), - ]; - client.innerApiCalls.listQuotaPreferences = stubSimpleCall(expectedResponse); - const [response] = await client.listQuotaPreferences(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listQuotaPreferences as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listQuotaPreferences as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listQuotaPreferences without error using callback', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.ListQuotaPreferencesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.ListQuotaPreferencesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.cloudquotas.v1.QuotaPreference(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1.QuotaPreference(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1.QuotaPreference(), + ), + ]; + client.innerApiCalls.listQuotaPreferences = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listQuotaPreferences( + request, + ( + err?: Error | null, + result?: protos.google.api.cloudquotas.v1.IQuotaPreference[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listQuotaPreferences as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listQuotaPreferences as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listQuotaPreferences without error using callback', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.ListQuotaPreferencesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.ListQuotaPreferencesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaPreference()), - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaPreference()), - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaPreference()), - ]; - client.innerApiCalls.listQuotaPreferences = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listQuotaPreferences( - request, - (err?: Error|null, result?: protos.google.api.cloudquotas.v1.IQuotaPreference[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listQuotaPreferences as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listQuotaPreferences as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listQuotaPreferences with error', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.ListQuotaPreferencesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.ListQuotaPreferencesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listQuotaPreferences = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listQuotaPreferences(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listQuotaPreferences as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listQuotaPreferences as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listQuotaPreferences with error', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.ListQuotaPreferencesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.ListQuotaPreferencesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listQuotaPreferences = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listQuotaPreferences(request), expectedError); - const actualRequest = (client.innerApiCalls.listQuotaPreferences as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listQuotaPreferences as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listQuotaPreferencesStream without error', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.ListQuotaPreferencesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.ListQuotaPreferencesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.cloudquotas.v1.QuotaPreference(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1.QuotaPreference(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1.QuotaPreference(), + ), + ]; + client.descriptors.page.listQuotaPreferences.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listQuotaPreferencesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.cloudquotas.v1.QuotaPreference[] = + []; + stream.on( + 'data', + (response: protos.google.api.cloudquotas.v1.QuotaPreference) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listQuotaPreferencesStream without error', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.ListQuotaPreferencesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.ListQuotaPreferencesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaPreference()), - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaPreference()), - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaPreference()), - ]; - client.descriptors.page.listQuotaPreferences.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listQuotaPreferencesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.cloudquotas.v1.QuotaPreference[] = []; - stream.on('data', (response: protos.google.api.cloudquotas.v1.QuotaPreference) => { - 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.listQuotaPreferences.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listQuotaPreferences, request)); - assert( - (client.descriptors.page.listQuotaPreferences.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listQuotaPreferences.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listQuotaPreferences, request), + ); + assert( + (client.descriptors.page.listQuotaPreferences.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listQuotaPreferencesStream with error', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.ListQuotaPreferencesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.ListQuotaPreferencesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listQuotaPreferences.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listQuotaPreferencesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.cloudquotas.v1.QuotaPreference[] = []; - stream.on('data', (response: protos.google.api.cloudquotas.v1.QuotaPreference) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listQuotaPreferences.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listQuotaPreferences, request)); - assert( - (client.descriptors.page.listQuotaPreferences.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listQuotaPreferencesStream with error', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.ListQuotaPreferencesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.ListQuotaPreferencesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listQuotaPreferences.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listQuotaPreferencesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.cloudquotas.v1.QuotaPreference[] = + []; + stream.on( + 'data', + (response: protos.google.api.cloudquotas.v1.QuotaPreference) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with listQuotaPreferences without error', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.ListQuotaPreferencesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.ListQuotaPreferencesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaPreference()), - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaPreference()), - generateSampleMessage(new protos.google.api.cloudquotas.v1.QuotaPreference()), - ]; - client.descriptors.page.listQuotaPreferences.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.api.cloudquotas.v1.IQuotaPreference[] = []; - const iterable = client.listQuotaPreferencesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listQuotaPreferences.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listQuotaPreferences.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listQuotaPreferences.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listQuotaPreferences, request), + ); + assert( + (client.descriptors.page.listQuotaPreferences.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listQuotaPreferences with error', async () => { - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1.ListQuotaPreferencesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1.ListQuotaPreferencesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listQuotaPreferences.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listQuotaPreferencesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.api.cloudquotas.v1.IQuotaPreference[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listQuotaPreferences.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listQuotaPreferences.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listQuotaPreferences without error', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.ListQuotaPreferencesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.ListQuotaPreferencesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.cloudquotas.v1.QuotaPreference(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1.QuotaPreference(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1.QuotaPreference(), + ), + ]; + client.descriptors.page.listQuotaPreferences.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.api.cloudquotas.v1.IQuotaPreference[] = []; + const iterable = client.listQuotaPreferencesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listQuotaPreferences.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listQuotaPreferences.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('folderLocationQuotaPreference', async () => { - const fakePath = "/rendered/path/folderLocationQuotaPreference"; - const expectedParameters = { - folder: "folderValue", - location: "locationValue", - quota_preference: "quotaPreferenceValue", - }; - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderLocationQuotaPreferencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLocationQuotaPreferencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLocationQuotaPreferencePath', () => { - const result = client.folderLocationQuotaPreferencePath("folderValue", "locationValue", "quotaPreferenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLocationQuotaPreferencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLocationQuotaPreferenceName', () => { - const result = client.matchFolderFromFolderLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromFolderLocationQuotaPreferenceName', () => { - const result = client.matchLocationFromFolderLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.folderLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchQuotaPreferenceFromFolderLocationQuotaPreferenceName', () => { - const result = client.matchQuotaPreferenceFromFolderLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "quotaPreferenceValue"); - assert((client.pathTemplates.folderLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listQuotaPreferences with error', async () => { + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1.ListQuotaPreferencesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1.ListQuotaPreferencesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listQuotaPreferences.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listQuotaPreferencesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.api.cloudquotas.v1.IQuotaPreference[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listQuotaPreferences.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listQuotaPreferences.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('folderLocationQuotaPreference', async () => { + const fakePath = '/rendered/path/folderLocationQuotaPreference'; + const expectedParameters = { + folder: 'folderValue', + location: 'locationValue', + quota_preference: 'quotaPreferenceValue', + }; + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderLocationQuotaPreferencePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.folderLocationQuotaPreferencePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('folderLocationQuotaPreferencePath', () => { + const result = client.folderLocationQuotaPreferencePath( + 'folderValue', + 'locationValue', + 'quotaPreferenceValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderLocationQuotaPreferencePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLocationQuotaPreferenceName', () => { + const result = + client.matchFolderFromFolderLocationQuotaPreferenceName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromFolderLocationQuotaPreferenceName', () => { + const result = + client.matchLocationFromFolderLocationQuotaPreferenceName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.folderLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchQuotaPreferenceFromFolderLocationQuotaPreferenceName', () => { + const result = + client.matchQuotaPreferenceFromFolderLocationQuotaPreferenceName( + fakePath, + ); + assert.strictEqual(result, 'quotaPreferenceValue'); + assert( + ( + client.pathTemplates.folderLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderLocationServiceQuotaInfo', async () => { - const fakePath = "/rendered/path/folderLocationServiceQuotaInfo"; - const expectedParameters = { - folder: "folderValue", - location: "locationValue", - service: "serviceValue", - quota_info: "quotaInfoValue", - }; - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLocationServiceQuotaInfoPath', () => { - const result = client.folderLocationServiceQuotaInfoPath("folderValue", "locationValue", "serviceValue", "quotaInfoValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLocationServiceQuotaInfoName', () => { - const result = client.matchFolderFromFolderLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromFolderLocationServiceQuotaInfoName', () => { - const result = client.matchLocationFromFolderLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderLocationServiceQuotaInfoName', () => { - const result = client.matchServiceFromFolderLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchQuotaInfoFromFolderLocationServiceQuotaInfoName', () => { - const result = client.matchQuotaInfoFromFolderLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "quotaInfoValue"); - assert((client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderLocationServiceQuotaInfo', async () => { + const fakePath = '/rendered/path/folderLocationServiceQuotaInfo'; + const expectedParameters = { + folder: 'folderValue', + location: 'locationValue', + service: 'serviceValue', + quota_info: 'quotaInfoValue', + }; + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('folderLocationServiceQuotaInfoPath', () => { + const result = client.folderLocationServiceQuotaInfoPath( + 'folderValue', + 'locationValue', + 'serviceValue', + 'quotaInfoValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLocationServiceQuotaInfoName', () => { + const result = + client.matchFolderFromFolderLocationServiceQuotaInfoName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromFolderLocationServiceQuotaInfoName', () => { + const result = + client.matchLocationFromFolderLocationServiceQuotaInfoName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderLocationServiceQuotaInfoName', () => { + const result = + client.matchServiceFromFolderLocationServiceQuotaInfoName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchQuotaInfoFromFolderLocationServiceQuotaInfoName', () => { + const result = + client.matchQuotaInfoFromFolderLocationServiceQuotaInfoName(fakePath); + assert.strictEqual(result, 'quotaInfoValue'); + assert( + ( + client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLocationQuotaPreference', async () => { - const fakePath = "/rendered/path/organizationLocationQuotaPreference"; - const expectedParameters = { - organization: "organizationValue", - location: "locationValue", - quota_preference: "quotaPreferenceValue", - }; - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLocationQuotaPreferencePath', () => { - const result = client.organizationLocationQuotaPreferencePath("organizationValue", "locationValue", "quotaPreferenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLocationQuotaPreferenceName', () => { - const result = client.matchOrganizationFromOrganizationLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromOrganizationLocationQuotaPreferenceName', () => { - const result = client.matchLocationFromOrganizationLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchQuotaPreferenceFromOrganizationLocationQuotaPreferenceName', () => { - const result = client.matchQuotaPreferenceFromOrganizationLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "quotaPreferenceValue"); - assert((client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLocationQuotaPreference', async () => { + const fakePath = '/rendered/path/organizationLocationQuotaPreference'; + const expectedParameters = { + organization: 'organizationValue', + location: 'locationValue', + quota_preference: 'quotaPreferenceValue', + }; + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationLocationQuotaPreferencePath', () => { + const result = client.organizationLocationQuotaPreferencePath( + 'organizationValue', + 'locationValue', + 'quotaPreferenceValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationLocationQuotaPreferencePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLocationQuotaPreferenceName', () => { + const result = + client.matchOrganizationFromOrganizationLocationQuotaPreferenceName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromOrganizationLocationQuotaPreferenceName', () => { + const result = + client.matchLocationFromOrganizationLocationQuotaPreferenceName( + fakePath, + ); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.organizationLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchQuotaPreferenceFromOrganizationLocationQuotaPreferenceName', () => { + const result = + client.matchQuotaPreferenceFromOrganizationLocationQuotaPreferenceName( + fakePath, + ); + assert.strictEqual(result, 'quotaPreferenceValue'); + assert( + ( + client.pathTemplates.organizationLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLocationServiceQuotaInfo', async () => { - const fakePath = "/rendered/path/organizationLocationServiceQuotaInfo"; - const expectedParameters = { - organization: "organizationValue", - location: "locationValue", - service: "serviceValue", - quota_info: "quotaInfoValue", - }; - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLocationServiceQuotaInfoPath', () => { - const result = client.organizationLocationServiceQuotaInfoPath("organizationValue", "locationValue", "serviceValue", "quotaInfoValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLocationServiceQuotaInfoName', () => { - const result = client.matchOrganizationFromOrganizationLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromOrganizationLocationServiceQuotaInfoName', () => { - const result = client.matchLocationFromOrganizationLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromOrganizationLocationServiceQuotaInfoName', () => { - const result = client.matchServiceFromOrganizationLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchQuotaInfoFromOrganizationLocationServiceQuotaInfoName', () => { - const result = client.matchQuotaInfoFromOrganizationLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "quotaInfoValue"); - assert((client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLocationServiceQuotaInfo', async () => { + const fakePath = '/rendered/path/organizationLocationServiceQuotaInfo'; + const expectedParameters = { + organization: 'organizationValue', + location: 'locationValue', + service: 'serviceValue', + quota_info: 'quotaInfoValue', + }; + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationLocationServiceQuotaInfoPath', () => { + const result = client.organizationLocationServiceQuotaInfoPath( + 'organizationValue', + 'locationValue', + 'serviceValue', + 'quotaInfoValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates + .organizationLocationServiceQuotaInfoPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLocationServiceQuotaInfoName', () => { + const result = + client.matchOrganizationFromOrganizationLocationServiceQuotaInfoName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates + .organizationLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromOrganizationLocationServiceQuotaInfoName', () => { + const result = + client.matchLocationFromOrganizationLocationServiceQuotaInfoName( + fakePath, + ); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates + .organizationLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationLocationServiceQuotaInfoName', () => { + const result = + client.matchServiceFromOrganizationLocationServiceQuotaInfoName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates + .organizationLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchQuotaInfoFromOrganizationLocationServiceQuotaInfoName', () => { + const result = + client.matchQuotaInfoFromOrganizationLocationServiceQuotaInfoName( + fakePath, + ); + assert.strictEqual(result, 'quotaInfoValue'); + assert( + ( + client.pathTemplates + .organizationLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocation', async () => { - const fakePath = "/rendered/path/projectLocation"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - }; - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectLocationPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationPath', () => { - const result = client.projectLocationPath("projectValue", "locationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationName', () => { - const result = client.matchProjectFromProjectLocationName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationName', () => { - const result = client.matchLocationFromProjectLocationName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocation', async () => { + const fakePath = '/rendered/path/projectLocation'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + }; + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectLocationPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectLocationPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectLocationPath', () => { + const result = client.projectLocationPath( + 'projectValue', + 'locationValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectLocationPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationName', () => { + const result = client.matchProjectFromProjectLocationName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectLocationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationName', () => { + const result = client.matchLocationFromProjectLocationName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.projectLocationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocationQuotaPreference', async () => { - const fakePath = "/rendered/path/projectLocationQuotaPreference"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - quota_preference: "quotaPreferenceValue", - }; - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectLocationQuotaPreferencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationQuotaPreferencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationQuotaPreferencePath', () => { - const result = client.projectLocationQuotaPreferencePath("projectValue", "locationValue", "quotaPreferenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationQuotaPreferencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationQuotaPreferenceName', () => { - const result = client.matchProjectFromProjectLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationQuotaPreferenceName', () => { - const result = client.matchLocationFromProjectLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchQuotaPreferenceFromProjectLocationQuotaPreferenceName', () => { - const result = client.matchQuotaPreferenceFromProjectLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "quotaPreferenceValue"); - assert((client.pathTemplates.projectLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocationQuotaPreference', async () => { + const fakePath = '/rendered/path/projectLocationQuotaPreference'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + quota_preference: 'quotaPreferenceValue', + }; + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectLocationQuotaPreferencePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectLocationQuotaPreferencePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('projectLocationQuotaPreferencePath', () => { + const result = client.projectLocationQuotaPreferencePath( + 'projectValue', + 'locationValue', + 'quotaPreferenceValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectLocationQuotaPreferencePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationQuotaPreferenceName', () => { + const result = + client.matchProjectFromProjectLocationQuotaPreferenceName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationQuotaPreferenceName', () => { + const result = + client.matchLocationFromProjectLocationQuotaPreferenceName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.projectLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchQuotaPreferenceFromProjectLocationQuotaPreferenceName', () => { + const result = + client.matchQuotaPreferenceFromProjectLocationQuotaPreferenceName( + fakePath, + ); + assert.strictEqual(result, 'quotaPreferenceValue'); + assert( + ( + client.pathTemplates.projectLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocationService', async () => { - const fakePath = "/rendered/path/projectLocationService"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - service: "serviceValue", - }; - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectLocationServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationServicePath', () => { - const result = client.projectLocationServicePath("projectValue", "locationValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationServiceName', () => { - const result = client.matchProjectFromProjectLocationServiceName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationServiceName', () => { - const result = client.matchLocationFromProjectLocationServiceName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromProjectLocationServiceName', () => { - const result = client.matchServiceFromProjectLocationServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectLocationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocationService', async () => { + const fakePath = '/rendered/path/projectLocationService'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + service: 'serviceValue', + }; + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectLocationServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectLocationServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectLocationServicePath', () => { + const result = client.projectLocationServicePath( + 'projectValue', + 'locationValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectLocationServicePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationServiceName', () => { + const result = + client.matchProjectFromProjectLocationServiceName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectLocationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationServiceName', () => { + const result = + client.matchLocationFromProjectLocationServiceName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.projectLocationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectLocationServiceName', () => { + const result = + client.matchServiceFromProjectLocationServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.projectLocationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocationServiceQuotaInfo', async () => { - const fakePath = "/rendered/path/projectLocationServiceQuotaInfo"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - service: "serviceValue", - quota_info: "quotaInfoValue", - }; - const client = new cloudquotasModule.v1.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationServiceQuotaInfoPath', () => { - const result = client.projectLocationServiceQuotaInfoPath("projectValue", "locationValue", "serviceValue", "quotaInfoValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationServiceQuotaInfoName', () => { - const result = client.matchProjectFromProjectLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationServiceQuotaInfoName', () => { - const result = client.matchLocationFromProjectLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromProjectLocationServiceQuotaInfoName', () => { - const result = client.matchServiceFromProjectLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchQuotaInfoFromProjectLocationServiceQuotaInfoName', () => { - const result = client.matchQuotaInfoFromProjectLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "quotaInfoValue"); - assert((client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocationServiceQuotaInfo', async () => { + const fakePath = '/rendered/path/projectLocationServiceQuotaInfo'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + service: 'serviceValue', + quota_info: 'quotaInfoValue', + }; + const client = new cloudquotasModule.v1.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('projectLocationServiceQuotaInfoPath', () => { + const result = client.projectLocationServiceQuotaInfoPath( + 'projectValue', + 'locationValue', + 'serviceValue', + 'quotaInfoValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationServiceQuotaInfoName', () => { + const result = + client.matchProjectFromProjectLocationServiceQuotaInfoName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationServiceQuotaInfoName', () => { + const result = + client.matchLocationFromProjectLocationServiceQuotaInfoName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectLocationServiceQuotaInfoName', () => { + const result = + client.matchServiceFromProjectLocationServiceQuotaInfoName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchQuotaInfoFromProjectLocationServiceQuotaInfoName', () => { + const result = + client.matchQuotaInfoFromProjectLocationServiceQuotaInfoName( + fakePath, + ); + assert.strictEqual(result, 'quotaInfoValue'); + assert( + ( + client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-api-cloudquotas/test/gapic_cloud_quotas_v1beta.ts b/packages/google-api-cloudquotas/test/gapic_cloud_quotas_v1beta.ts index d76779837a8c..3e3f17e7bc85 100644 --- a/packages/google-api-cloudquotas/test/gapic_cloud_quotas_v1beta.ts +++ b/packages/google-api-cloudquotas/test/gapic_cloud_quotas_v1beta.ts @@ -19,1670 +19,2375 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as cloudquotasModule from '../src'; -import {PassThrough} from 'stream'; +import { PassThrough } from 'stream'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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 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('v1beta.CloudQuotasClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'cloudquotas.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'cloudquotas.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 = cloudquotasModule.v1beta.CloudQuotasClient.servicePath; - assert.strictEqual(servicePath, 'cloudquotas.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = cloudquotasModule.v1beta.CloudQuotasClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'cloudquotas.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudquotas.example.com'); - }); + it('has universeDomain', () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudquotas.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 = + cloudquotasModule.v1beta.CloudQuotasClient.servicePath; + assert.strictEqual(servicePath, 'cloudquotas.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + cloudquotasModule.v1beta.CloudQuotasClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'cloudquotas.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudquotas.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 cloudquotasModule.v1beta.CloudQuotasClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudquotas.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 cloudquotasModule.v1beta.CloudQuotasClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudquotas.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 cloudquotasModule.v1beta.CloudQuotasClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudquotas.example.com'); + }); - it('has port', () => { - const port = cloudquotasModule.v1beta.CloudQuotasClient.port; - assert(port); - assert(typeof port === 'number'); + 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 cloudquotasModule.v1beta.CloudQuotasClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudquotas.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with no option', () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient(); - assert(client); + 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 cloudquotasModule.v1beta.CloudQuotasClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudquotas.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with gRPC fallback', () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - fallback: true, - }); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new cloudquotasModule.v1beta.CloudQuotasClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.cloudQuotasStub, undefined); - await client.initialize(); - assert(client.cloudQuotasStub); - }); + it('has port', () => { + const port = cloudquotasModule.v1beta.CloudQuotasClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the initialized client', done => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.cloudQuotasStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient(); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.cloudQuotasStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + fallback: true, + }); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - 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 initialize method and supports deferred initialization', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.cloudQuotasStub, undefined); + await client.initialize(); + assert(client.cloudQuotasStub); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - 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('has close method for the initialized client', (done) => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.cloudQuotasStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('getQuotaInfo', () => { - it('invokes getQuotaInfo without error', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.GetQuotaInfoRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.GetQuotaInfoRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.QuotaInfo() - ); - client.innerApiCalls.getQuotaInfo = stubSimpleCall(expectedResponse); - const [response] = await client.getQuotaInfo(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getQuotaInfo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQuotaInfo 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 cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.cloudQuotasStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes getQuotaInfo without error using callback', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.GetQuotaInfoRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.GetQuotaInfoRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.QuotaInfo() - ); - client.innerApiCalls.getQuotaInfo = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getQuotaInfo( - request, - (err?: Error|null, result?: protos.google.api.cloudquotas.v1beta.IQuotaInfo|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getQuotaInfo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQuotaInfo 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 cloudquotasModule.v1beta.CloudQuotasClient({ + 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 getQuotaInfo with error', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.GetQuotaInfoRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.GetQuotaInfoRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getQuotaInfo = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getQuotaInfo(request), expectedError); - const actualRequest = (client.innerApiCalls.getQuotaInfo as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQuotaInfo 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 cloudquotasModule.v1beta.CloudQuotasClient({ + 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('getQuotaInfo', () => { + it('invokes getQuotaInfo without error', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.GetQuotaInfoRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.GetQuotaInfoRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaInfo(), + ); + client.innerApiCalls.getQuotaInfo = stubSimpleCall(expectedResponse); + const [response] = await client.getQuotaInfo(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getQuotaInfo as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQuotaInfo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getQuotaInfo with closed client', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.GetQuotaInfoRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.GetQuotaInfoRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getQuotaInfo(request), expectedError); - }); + it('invokes getQuotaInfo without error using callback', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.GetQuotaInfoRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.GetQuotaInfoRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaInfo(), + ); + client.innerApiCalls.getQuotaInfo = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getQuotaInfo( + request, + ( + err?: Error | null, + result?: protos.google.api.cloudquotas.v1beta.IQuotaInfo | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getQuotaInfo as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQuotaInfo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getQuotaPreference', () => { - it('invokes getQuotaPreference without error', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.GetQuotaPreferenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.GetQuotaPreferenceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.QuotaPreference() - ); - client.innerApiCalls.getQuotaPreference = stubSimpleCall(expectedResponse); - const [response] = await client.getQuotaPreference(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getQuotaPreference as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQuotaPreference as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getQuotaInfo with error', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.GetQuotaInfoRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.GetQuotaInfoRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getQuotaInfo = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getQuotaInfo(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getQuotaInfo as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQuotaInfo as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getQuotaPreference without error using callback', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.GetQuotaPreferenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.GetQuotaPreferenceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.QuotaPreference() - ); - client.innerApiCalls.getQuotaPreference = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getQuotaPreference( - request, - (err?: Error|null, result?: protos.google.api.cloudquotas.v1beta.IQuotaPreference|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getQuotaPreference as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQuotaPreference as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getQuotaInfo with closed client', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.GetQuotaInfoRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.GetQuotaInfoRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getQuotaInfo(request), expectedError); + }); + }); + + describe('getQuotaPreference', () => { + it('invokes getQuotaPreference without error', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.GetQuotaPreferenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.GetQuotaPreferenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaPreference(), + ); + client.innerApiCalls.getQuotaPreference = + stubSimpleCall(expectedResponse); + const [response] = await client.getQuotaPreference(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getQuotaPreference as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQuotaPreference as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getQuotaPreference with error', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.GetQuotaPreferenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.GetQuotaPreferenceRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getQuotaPreference = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getQuotaPreference(request), expectedError); - const actualRequest = (client.innerApiCalls.getQuotaPreference as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQuotaPreference as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getQuotaPreference without error using callback', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.GetQuotaPreferenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.GetQuotaPreferenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaPreference(), + ); + client.innerApiCalls.getQuotaPreference = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getQuotaPreference( + request, + ( + err?: Error | null, + result?: protos.google.api.cloudquotas.v1beta.IQuotaPreference | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getQuotaPreference as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQuotaPreference as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getQuotaPreference with closed client', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.GetQuotaPreferenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.GetQuotaPreferenceRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getQuotaPreference(request), expectedError); - }); + it('invokes getQuotaPreference with error', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.GetQuotaPreferenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.GetQuotaPreferenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getQuotaPreference = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.getQuotaPreference(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getQuotaPreference as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQuotaPreference as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createQuotaPreference', () => { - it('invokes createQuotaPreference without error', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.CreateQuotaPreferenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.CreateQuotaPreferenceRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.QuotaPreference() - ); - client.innerApiCalls.createQuotaPreference = stubSimpleCall(expectedResponse); - const [response] = await client.createQuotaPreference(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createQuotaPreference as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createQuotaPreference as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getQuotaPreference with closed client', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.GetQuotaPreferenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.GetQuotaPreferenceRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.getQuotaPreference(request), expectedError); + }); + }); + + describe('createQuotaPreference', () => { + it('invokes createQuotaPreference without error', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.CreateQuotaPreferenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.CreateQuotaPreferenceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaPreference(), + ); + client.innerApiCalls.createQuotaPreference = + stubSimpleCall(expectedResponse); + const [response] = await client.createQuotaPreference(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createQuotaPreference as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createQuotaPreference as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createQuotaPreference without error using callback', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.CreateQuotaPreferenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.CreateQuotaPreferenceRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.QuotaPreference() - ); - client.innerApiCalls.createQuotaPreference = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createQuotaPreference( - request, - (err?: Error|null, result?: protos.google.api.cloudquotas.v1beta.IQuotaPreference|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createQuotaPreference as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createQuotaPreference as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createQuotaPreference without error using callback', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.CreateQuotaPreferenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.CreateQuotaPreferenceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaPreference(), + ); + client.innerApiCalls.createQuotaPreference = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createQuotaPreference( + request, + ( + err?: Error | null, + result?: protos.google.api.cloudquotas.v1beta.IQuotaPreference | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createQuotaPreference as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createQuotaPreference as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createQuotaPreference with error', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.CreateQuotaPreferenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.CreateQuotaPreferenceRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createQuotaPreference = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createQuotaPreference(request), expectedError); - const actualRequest = (client.innerApiCalls.createQuotaPreference as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createQuotaPreference as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createQuotaPreference with error', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.CreateQuotaPreferenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.CreateQuotaPreferenceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createQuotaPreference = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.createQuotaPreference(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.createQuotaPreference as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createQuotaPreference as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createQuotaPreference with closed client', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.CreateQuotaPreferenceRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.CreateQuotaPreferenceRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createQuotaPreference(request), expectedError); - }); + it('invokes createQuotaPreference with closed client', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.CreateQuotaPreferenceRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.CreateQuotaPreferenceRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.createQuotaPreference(request), + expectedError, + ); + }); + }); + + describe('updateQuotaPreference', () => { + it('invokes updateQuotaPreference without error', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.UpdateQuotaPreferenceRequest(), + ); + request.quotaPreference ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.UpdateQuotaPreferenceRequest', + ['quotaPreference', 'name'], + ); + request.quotaPreference.name = defaultValue1; + const expectedHeaderRequestParams = `quota_preference.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaPreference(), + ); + client.innerApiCalls.updateQuotaPreference = + stubSimpleCall(expectedResponse); + const [response] = await client.updateQuotaPreference(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateQuotaPreference as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateQuotaPreference as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateQuotaPreference', () => { - it('invokes updateQuotaPreference without error', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.UpdateQuotaPreferenceRequest() - ); - request.quotaPreference ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.UpdateQuotaPreferenceRequest', ['quotaPreference', 'name']); - request.quotaPreference.name = defaultValue1; - const expectedHeaderRequestParams = `quota_preference.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.QuotaPreference() - ); - client.innerApiCalls.updateQuotaPreference = stubSimpleCall(expectedResponse); - const [response] = await client.updateQuotaPreference(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateQuotaPreference as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateQuotaPreference as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateQuotaPreference without error using callback', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.UpdateQuotaPreferenceRequest(), + ); + request.quotaPreference ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.UpdateQuotaPreferenceRequest', + ['quotaPreference', 'name'], + ); + request.quotaPreference.name = defaultValue1; + const expectedHeaderRequestParams = `quota_preference.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaPreference(), + ); + client.innerApiCalls.updateQuotaPreference = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateQuotaPreference( + request, + ( + err?: Error | null, + result?: protos.google.api.cloudquotas.v1beta.IQuotaPreference | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateQuotaPreference as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateQuotaPreference as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateQuotaPreference without error using callback', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.UpdateQuotaPreferenceRequest() - ); - request.quotaPreference ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.UpdateQuotaPreferenceRequest', ['quotaPreference', 'name']); - request.quotaPreference.name = defaultValue1; - const expectedHeaderRequestParams = `quota_preference.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.QuotaPreference() - ); - client.innerApiCalls.updateQuotaPreference = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateQuotaPreference( - request, - (err?: Error|null, result?: protos.google.api.cloudquotas.v1beta.IQuotaPreference|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateQuotaPreference as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateQuotaPreference as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateQuotaPreference with error', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.UpdateQuotaPreferenceRequest(), + ); + request.quotaPreference ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.UpdateQuotaPreferenceRequest', + ['quotaPreference', 'name'], + ); + request.quotaPreference.name = defaultValue1; + const expectedHeaderRequestParams = `quota_preference.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateQuotaPreference = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateQuotaPreference(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateQuotaPreference as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateQuotaPreference as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateQuotaPreference with error', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.UpdateQuotaPreferenceRequest() - ); - request.quotaPreference ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.UpdateQuotaPreferenceRequest', ['quotaPreference', 'name']); - request.quotaPreference.name = defaultValue1; - const expectedHeaderRequestParams = `quota_preference.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateQuotaPreference = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateQuotaPreference(request), expectedError); - const actualRequest = (client.innerApiCalls.updateQuotaPreference as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateQuotaPreference as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateQuotaPreference with closed client', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.UpdateQuotaPreferenceRequest(), + ); + request.quotaPreference ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.UpdateQuotaPreferenceRequest', + ['quotaPreference', 'name'], + ); + request.quotaPreference.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateQuotaPreference(request), + expectedError, + ); + }); + }); + + describe('listQuotaInfos', () => { + it('invokes listQuotaInfos without error', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.ListQuotaInfosRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.ListQuotaInfosRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaInfo(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaInfo(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaInfo(), + ), + ]; + client.innerApiCalls.listQuotaInfos = stubSimpleCall(expectedResponse); + const [response] = await client.listQuotaInfos(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listQuotaInfos as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listQuotaInfos as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateQuotaPreference with closed client', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.UpdateQuotaPreferenceRequest() - ); - request.quotaPreference ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.UpdateQuotaPreferenceRequest', ['quotaPreference', 'name']); - request.quotaPreference.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateQuotaPreference(request), expectedError); - }); + it('invokes listQuotaInfos without error using callback', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.ListQuotaInfosRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.ListQuotaInfosRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaInfo(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaInfo(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaInfo(), + ), + ]; + client.innerApiCalls.listQuotaInfos = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listQuotaInfos( + request, + ( + err?: Error | null, + result?: protos.google.api.cloudquotas.v1beta.IQuotaInfo[] | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listQuotaInfos as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listQuotaInfos as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listQuotaInfos', () => { - it('invokes listQuotaInfos without error', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.ListQuotaInfosRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.ListQuotaInfosRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaInfo()), - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaInfo()), - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaInfo()), - ]; - client.innerApiCalls.listQuotaInfos = stubSimpleCall(expectedResponse); - const [response] = await client.listQuotaInfos(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listQuotaInfos as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listQuotaInfos as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listQuotaInfos with error', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.ListQuotaInfosRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.ListQuotaInfosRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listQuotaInfos = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listQuotaInfos(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listQuotaInfos as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listQuotaInfos as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listQuotaInfos without error using callback', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.ListQuotaInfosRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.ListQuotaInfosRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaInfo()), - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaInfo()), - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaInfo()), - ]; - client.innerApiCalls.listQuotaInfos = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listQuotaInfos( - request, - (err?: Error|null, result?: protos.google.api.cloudquotas.v1beta.IQuotaInfo[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listQuotaInfos as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listQuotaInfos as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listQuotaInfosStream without error', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.ListQuotaInfosRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.ListQuotaInfosRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaInfo(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaInfo(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaInfo(), + ), + ]; + client.descriptors.page.listQuotaInfos.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listQuotaInfosStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.cloudquotas.v1beta.QuotaInfo[] = []; + stream.on( + 'data', + (response: protos.google.api.cloudquotas.v1beta.QuotaInfo) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listQuotaInfos with error', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.ListQuotaInfosRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.ListQuotaInfosRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listQuotaInfos = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listQuotaInfos(request), expectedError); - const actualRequest = (client.innerApiCalls.listQuotaInfos as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listQuotaInfos as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listQuotaInfos.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listQuotaInfos, request), + ); + assert( + (client.descriptors.page.listQuotaInfos.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listQuotaInfosStream without error', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.ListQuotaInfosRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.ListQuotaInfosRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaInfo()), - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaInfo()), - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaInfo()), - ]; - client.descriptors.page.listQuotaInfos.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listQuotaInfosStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.cloudquotas.v1beta.QuotaInfo[] = []; - stream.on('data', (response: protos.google.api.cloudquotas.v1beta.QuotaInfo) => { - 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.listQuotaInfos.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listQuotaInfos, request)); - assert( - (client.descriptors.page.listQuotaInfos.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listQuotaInfosStream with error', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.ListQuotaInfosRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.ListQuotaInfosRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listQuotaInfos.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listQuotaInfosStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.cloudquotas.v1beta.QuotaInfo[] = []; + stream.on( + 'data', + (response: protos.google.api.cloudquotas.v1beta.QuotaInfo) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listQuotaInfosStream with error', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.ListQuotaInfosRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.ListQuotaInfosRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listQuotaInfos.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listQuotaInfosStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.cloudquotas.v1beta.QuotaInfo[] = []; - stream.on('data', (response: protos.google.api.cloudquotas.v1beta.QuotaInfo) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listQuotaInfos.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listQuotaInfos, request)); - assert( - (client.descriptors.page.listQuotaInfos.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listQuotaInfos.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listQuotaInfos, request), + ); + assert( + (client.descriptors.page.listQuotaInfos.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listQuotaInfos without error', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.ListQuotaInfosRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.ListQuotaInfosRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaInfo()), - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaInfo()), - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaInfo()), - ]; - client.descriptors.page.listQuotaInfos.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.api.cloudquotas.v1beta.IQuotaInfo[] = []; - const iterable = client.listQuotaInfosAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listQuotaInfos.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listQuotaInfos.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listQuotaInfos without error', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.ListQuotaInfosRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.ListQuotaInfosRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaInfo(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaInfo(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaInfo(), + ), + ]; + client.descriptors.page.listQuotaInfos.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.api.cloudquotas.v1beta.IQuotaInfo[] = []; + const iterable = client.listQuotaInfosAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listQuotaInfos.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listQuotaInfos.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listQuotaInfos with error', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.ListQuotaInfosRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.ListQuotaInfosRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listQuotaInfos.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listQuotaInfosAsync(request); - await assert.rejects(async () => { - const responses: protos.google.api.cloudquotas.v1beta.IQuotaInfo[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listQuotaInfos.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listQuotaInfos.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listQuotaInfos with error', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.ListQuotaInfosRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.ListQuotaInfosRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listQuotaInfos.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listQuotaInfosAsync(request); + await assert.rejects(async () => { + const responses: protos.google.api.cloudquotas.v1beta.IQuotaInfo[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listQuotaInfos.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listQuotaInfos.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('listQuotaPreferences', () => { + it('invokes listQuotaPreferences without error', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaPreference(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaPreference(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaPreference(), + ), + ]; + client.innerApiCalls.listQuotaPreferences = + stubSimpleCall(expectedResponse); + const [response] = await client.listQuotaPreferences(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listQuotaPreferences as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listQuotaPreferences as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listQuotaPreferences', () => { - it('invokes listQuotaPreferences without error', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaPreference()), - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaPreference()), - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaPreference()), - ]; - client.innerApiCalls.listQuotaPreferences = stubSimpleCall(expectedResponse); - const [response] = await client.listQuotaPreferences(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listQuotaPreferences as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listQuotaPreferences as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listQuotaPreferences without error using callback', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaPreference(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaPreference(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaPreference(), + ), + ]; + client.innerApiCalls.listQuotaPreferences = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listQuotaPreferences( + request, + ( + err?: Error | null, + result?: + | protos.google.api.cloudquotas.v1beta.IQuotaPreference[] + | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listQuotaPreferences as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listQuotaPreferences as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listQuotaPreferences without error using callback', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaPreference()), - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaPreference()), - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaPreference()), - ]; - client.innerApiCalls.listQuotaPreferences = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listQuotaPreferences( - request, - (err?: Error|null, result?: protos.google.api.cloudquotas.v1beta.IQuotaPreference[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listQuotaPreferences as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listQuotaPreferences as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listQuotaPreferences with error', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listQuotaPreferences = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.listQuotaPreferences(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listQuotaPreferences as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listQuotaPreferences as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listQuotaPreferences with error', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listQuotaPreferences = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listQuotaPreferences(request), expectedError); - const actualRequest = (client.innerApiCalls.listQuotaPreferences as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listQuotaPreferences as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listQuotaPreferencesStream without error', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaPreference(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaPreference(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaPreference(), + ), + ]; + client.descriptors.page.listQuotaPreferences.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listQuotaPreferencesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.cloudquotas.v1beta.QuotaPreference[] = + []; + stream.on( + 'data', + (response: protos.google.api.cloudquotas.v1beta.QuotaPreference) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('invokes listQuotaPreferencesStream without error', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaPreference()), - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaPreference()), - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaPreference()), - ]; - client.descriptors.page.listQuotaPreferences.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listQuotaPreferencesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.cloudquotas.v1beta.QuotaPreference[] = []; - stream.on('data', (response: protos.google.api.cloudquotas.v1beta.QuotaPreference) => { - 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.listQuotaPreferences.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listQuotaPreferences, request)); - assert( - (client.descriptors.page.listQuotaPreferences.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listQuotaPreferences.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listQuotaPreferences, request), + ); + assert( + (client.descriptors.page.listQuotaPreferences.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('invokes listQuotaPreferencesStream with error', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listQuotaPreferences.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listQuotaPreferencesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.api.cloudquotas.v1beta.QuotaPreference[] = []; - stream.on('data', (response: protos.google.api.cloudquotas.v1beta.QuotaPreference) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listQuotaPreferences.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listQuotaPreferences, request)); - assert( - (client.descriptors.page.listQuotaPreferences.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + it('invokes listQuotaPreferencesStream with error', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listQuotaPreferences.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listQuotaPreferencesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.api.cloudquotas.v1beta.QuotaPreference[] = + []; + stream.on( + 'data', + (response: protos.google.api.cloudquotas.v1beta.QuotaPreference) => { + responses.push(response); + }, + ); + stream.on('end', () => { + resolve(responses); }); - - it('uses async iteration with listQuotaPreferences without error', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaPreference()), - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaPreference()), - generateSampleMessage(new protos.google.api.cloudquotas.v1beta.QuotaPreference()), - ]; - client.descriptors.page.listQuotaPreferences.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.api.cloudquotas.v1beta.IQuotaPreference[] = []; - const iterable = client.listQuotaPreferencesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listQuotaPreferences.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listQuotaPreferences.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + stream.on('error', (err: Error) => { + reject(err); }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listQuotaPreferences.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listQuotaPreferences, request), + ); + assert( + (client.descriptors.page.listQuotaPreferences.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); - it('uses async iteration with listQuotaPreferences with error', async () => { - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listQuotaPreferences.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listQuotaPreferencesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.api.cloudquotas.v1beta.IQuotaPreference[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listQuotaPreferences.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listQuotaPreferences.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listQuotaPreferences without error', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaPreference(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaPreference(), + ), + generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaPreference(), + ), + ]; + client.descriptors.page.listQuotaPreferences.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.api.cloudquotas.v1beta.IQuotaPreference[] = + []; + const iterable = client.listQuotaPreferencesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listQuotaPreferences.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listQuotaPreferences.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); }); - describe('Path templates', () => { - - describe('folderLocationQuotaAdjusterSettings', async () => { - const fakePath = "/rendered/path/folderLocationQuotaAdjusterSettings"; - const expectedParameters = { - folder: "folderValue", - location: "locationValue", - }; - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLocationQuotaAdjusterSettingsPath', () => { - const result = client.folderLocationQuotaAdjusterSettingsPath("folderValue", "locationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLocationQuotaAdjusterSettingsName', () => { - const result = client.matchFolderFromFolderLocationQuotaAdjusterSettingsName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromFolderLocationQuotaAdjusterSettingsName', () => { - const result = client.matchLocationFromFolderLocationQuotaAdjusterSettingsName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('uses async iteration with listQuotaPreferences with error', async () => { + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.ListQuotaPreferencesRequest', + ['parent'], + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listQuotaPreferences.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listQuotaPreferencesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.api.cloudquotas.v1beta.IQuotaPreference[] = + []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listQuotaPreferences.asyncIterate as SinonStub + ).getCall(0).args[1], + request, + ); + assert( + (client.descriptors.page.listQuotaPreferences.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams), + ); + }); + }); + + describe('Path templates', () => { + describe('folderLocationQuotaAdjusterSettings', async () => { + const fakePath = '/rendered/path/folderLocationQuotaAdjusterSettings'; + const expectedParameters = { + folder: 'folderValue', + location: 'locationValue', + }; + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('folderLocationQuotaAdjusterSettingsPath', () => { + const result = client.folderLocationQuotaAdjusterSettingsPath( + 'folderValue', + 'locationValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLocationQuotaAdjusterSettingsName', () => { + const result = + client.matchFolderFromFolderLocationQuotaAdjusterSettingsName( + fakePath, + ); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromFolderLocationQuotaAdjusterSettingsName', () => { + const result = + client.matchLocationFromFolderLocationQuotaAdjusterSettingsName( + fakePath, + ); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderLocationQuotaPreference', async () => { - const fakePath = "/rendered/path/folderLocationQuotaPreference"; - const expectedParameters = { - folder: "folderValue", - location: "locationValue", - quota_preference: "quotaPreferenceValue", - }; - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderLocationQuotaPreferencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLocationQuotaPreferencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLocationQuotaPreferencePath', () => { - const result = client.folderLocationQuotaPreferencePath("folderValue", "locationValue", "quotaPreferenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLocationQuotaPreferencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLocationQuotaPreferenceName', () => { - const result = client.matchFolderFromFolderLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromFolderLocationQuotaPreferenceName', () => { - const result = client.matchLocationFromFolderLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.folderLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchQuotaPreferenceFromFolderLocationQuotaPreferenceName', () => { - const result = client.matchQuotaPreferenceFromFolderLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "quotaPreferenceValue"); - assert((client.pathTemplates.folderLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderLocationQuotaPreference', async () => { + const fakePath = '/rendered/path/folderLocationQuotaPreference'; + const expectedParameters = { + folder: 'folderValue', + location: 'locationValue', + quota_preference: 'quotaPreferenceValue', + }; + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderLocationQuotaPreferencePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.folderLocationQuotaPreferencePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('folderLocationQuotaPreferencePath', () => { + const result = client.folderLocationQuotaPreferencePath( + 'folderValue', + 'locationValue', + 'quotaPreferenceValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderLocationQuotaPreferencePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLocationQuotaPreferenceName', () => { + const result = + client.matchFolderFromFolderLocationQuotaPreferenceName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromFolderLocationQuotaPreferenceName', () => { + const result = + client.matchLocationFromFolderLocationQuotaPreferenceName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.folderLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchQuotaPreferenceFromFolderLocationQuotaPreferenceName', () => { + const result = + client.matchQuotaPreferenceFromFolderLocationQuotaPreferenceName( + fakePath, + ); + assert.strictEqual(result, 'quotaPreferenceValue'); + assert( + ( + client.pathTemplates.folderLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderLocationServiceQuotaInfo', async () => { - const fakePath = "/rendered/path/folderLocationServiceQuotaInfo"; - const expectedParameters = { - folder: "folderValue", - location: "locationValue", - service: "serviceValue", - quota_info: "quotaInfoValue", - }; - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLocationServiceQuotaInfoPath', () => { - const result = client.folderLocationServiceQuotaInfoPath("folderValue", "locationValue", "serviceValue", "quotaInfoValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLocationServiceQuotaInfoName', () => { - const result = client.matchFolderFromFolderLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromFolderLocationServiceQuotaInfoName', () => { - const result = client.matchLocationFromFolderLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderLocationServiceQuotaInfoName', () => { - const result = client.matchServiceFromFolderLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchQuotaInfoFromFolderLocationServiceQuotaInfoName', () => { - const result = client.matchQuotaInfoFromFolderLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "quotaInfoValue"); - assert((client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderLocationServiceQuotaInfo', async () => { + const fakePath = '/rendered/path/folderLocationServiceQuotaInfo'; + const expectedParameters = { + folder: 'folderValue', + location: 'locationValue', + service: 'serviceValue', + quota_info: 'quotaInfoValue', + }; + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('folderLocationServiceQuotaInfoPath', () => { + const result = client.folderLocationServiceQuotaInfoPath( + 'folderValue', + 'locationValue', + 'serviceValue', + 'quotaInfoValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLocationServiceQuotaInfoName', () => { + const result = + client.matchFolderFromFolderLocationServiceQuotaInfoName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromFolderLocationServiceQuotaInfoName', () => { + const result = + client.matchLocationFromFolderLocationServiceQuotaInfoName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderLocationServiceQuotaInfoName', () => { + const result = + client.matchServiceFromFolderLocationServiceQuotaInfoName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchQuotaInfoFromFolderLocationServiceQuotaInfoName', () => { + const result = + client.matchQuotaInfoFromFolderLocationServiceQuotaInfoName(fakePath); + assert.strictEqual(result, 'quotaInfoValue'); + assert( + ( + client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLocationQuotaAdjusterSettings', async () => { - const fakePath = "/rendered/path/organizationLocationQuotaAdjusterSettings"; - const expectedParameters = { - organization: "organizationValue", - location: "locationValue", - }; - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLocationQuotaAdjusterSettingsPath', () => { - const result = client.organizationLocationQuotaAdjusterSettingsPath("organizationValue", "locationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLocationQuotaAdjusterSettingsName', () => { - const result = client.matchOrganizationFromOrganizationLocationQuotaAdjusterSettingsName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromOrganizationLocationQuotaAdjusterSettingsName', () => { - const result = client.matchLocationFromOrganizationLocationQuotaAdjusterSettingsName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLocationQuotaAdjusterSettings', async () => { + const fakePath = + '/rendered/path/organizationLocationQuotaAdjusterSettings'; + const expectedParameters = { + organization: 'organizationValue', + location: 'locationValue', + }; + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationLocationQuotaAdjusterSettingsPath', () => { + const result = client.organizationLocationQuotaAdjusterSettingsPath( + 'organizationValue', + 'locationValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates + .organizationLocationQuotaAdjusterSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLocationQuotaAdjusterSettingsName', () => { + const result = + client.matchOrganizationFromOrganizationLocationQuotaAdjusterSettingsName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates + .organizationLocationQuotaAdjusterSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromOrganizationLocationQuotaAdjusterSettingsName', () => { + const result = + client.matchLocationFromOrganizationLocationQuotaAdjusterSettingsName( + fakePath, + ); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates + .organizationLocationQuotaAdjusterSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLocationQuotaPreference', async () => { - const fakePath = "/rendered/path/organizationLocationQuotaPreference"; - const expectedParameters = { - organization: "organizationValue", - location: "locationValue", - quota_preference: "quotaPreferenceValue", - }; - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLocationQuotaPreferencePath', () => { - const result = client.organizationLocationQuotaPreferencePath("organizationValue", "locationValue", "quotaPreferenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLocationQuotaPreferenceName', () => { - const result = client.matchOrganizationFromOrganizationLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromOrganizationLocationQuotaPreferenceName', () => { - const result = client.matchLocationFromOrganizationLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchQuotaPreferenceFromOrganizationLocationQuotaPreferenceName', () => { - const result = client.matchQuotaPreferenceFromOrganizationLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "quotaPreferenceValue"); - assert((client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLocationQuotaPreference', async () => { + const fakePath = '/rendered/path/organizationLocationQuotaPreference'; + const expectedParameters = { + organization: 'organizationValue', + location: 'locationValue', + quota_preference: 'quotaPreferenceValue', + }; + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationLocationQuotaPreferencePath', () => { + const result = client.organizationLocationQuotaPreferencePath( + 'organizationValue', + 'locationValue', + 'quotaPreferenceValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationLocationQuotaPreferencePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLocationQuotaPreferenceName', () => { + const result = + client.matchOrganizationFromOrganizationLocationQuotaPreferenceName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromOrganizationLocationQuotaPreferenceName', () => { + const result = + client.matchLocationFromOrganizationLocationQuotaPreferenceName( + fakePath, + ); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.organizationLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchQuotaPreferenceFromOrganizationLocationQuotaPreferenceName', () => { + const result = + client.matchQuotaPreferenceFromOrganizationLocationQuotaPreferenceName( + fakePath, + ); + assert.strictEqual(result, 'quotaPreferenceValue'); + assert( + ( + client.pathTemplates.organizationLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLocationServiceQuotaInfo', async () => { - const fakePath = "/rendered/path/organizationLocationServiceQuotaInfo"; - const expectedParameters = { - organization: "organizationValue", - location: "locationValue", - service: "serviceValue", - quota_info: "quotaInfoValue", - }; - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLocationServiceQuotaInfoPath', () => { - const result = client.organizationLocationServiceQuotaInfoPath("organizationValue", "locationValue", "serviceValue", "quotaInfoValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLocationServiceQuotaInfoName', () => { - const result = client.matchOrganizationFromOrganizationLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromOrganizationLocationServiceQuotaInfoName', () => { - const result = client.matchLocationFromOrganizationLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromOrganizationLocationServiceQuotaInfoName', () => { - const result = client.matchServiceFromOrganizationLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchQuotaInfoFromOrganizationLocationServiceQuotaInfoName', () => { - const result = client.matchQuotaInfoFromOrganizationLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "quotaInfoValue"); - assert((client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLocationServiceQuotaInfo', async () => { + const fakePath = '/rendered/path/organizationLocationServiceQuotaInfo'; + const expectedParameters = { + organization: 'organizationValue', + location: 'locationValue', + service: 'serviceValue', + quota_info: 'quotaInfoValue', + }; + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationLocationServiceQuotaInfoPath', () => { + const result = client.organizationLocationServiceQuotaInfoPath( + 'organizationValue', + 'locationValue', + 'serviceValue', + 'quotaInfoValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates + .organizationLocationServiceQuotaInfoPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLocationServiceQuotaInfoName', () => { + const result = + client.matchOrganizationFromOrganizationLocationServiceQuotaInfoName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates + .organizationLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromOrganizationLocationServiceQuotaInfoName', () => { + const result = + client.matchLocationFromOrganizationLocationServiceQuotaInfoName( + fakePath, + ); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates + .organizationLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationLocationServiceQuotaInfoName', () => { + const result = + client.matchServiceFromOrganizationLocationServiceQuotaInfoName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates + .organizationLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchQuotaInfoFromOrganizationLocationServiceQuotaInfoName', () => { + const result = + client.matchQuotaInfoFromOrganizationLocationServiceQuotaInfoName( + fakePath, + ); + assert.strictEqual(result, 'quotaInfoValue'); + assert( + ( + client.pathTemplates + .organizationLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocation', async () => { - const fakePath = "/rendered/path/projectLocation"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - }; - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectLocationPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationPath', () => { - const result = client.projectLocationPath("projectValue", "locationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationName', () => { - const result = client.matchProjectFromProjectLocationName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationName', () => { - const result = client.matchLocationFromProjectLocationName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocation', async () => { + const fakePath = '/rendered/path/projectLocation'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + }; + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectLocationPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectLocationPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectLocationPath', () => { + const result = client.projectLocationPath( + 'projectValue', + 'locationValue', + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectLocationPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationName', () => { + const result = client.matchProjectFromProjectLocationName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectLocationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationName', () => { + const result = client.matchLocationFromProjectLocationName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.projectLocationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocationQuotaAdjusterSettings', async () => { - const fakePath = "/rendered/path/projectLocationQuotaAdjusterSettings"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - }; - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationQuotaAdjusterSettingsPath', () => { - const result = client.projectLocationQuotaAdjusterSettingsPath("projectValue", "locationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationQuotaAdjusterSettingsName', () => { - const result = client.matchProjectFromProjectLocationQuotaAdjusterSettingsName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationQuotaAdjusterSettingsName', () => { - const result = client.matchLocationFromProjectLocationQuotaAdjusterSettingsName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocationQuotaAdjusterSettings', async () => { + const fakePath = '/rendered/path/projectLocationQuotaAdjusterSettings'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + }; + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('projectLocationQuotaAdjusterSettingsPath', () => { + const result = client.projectLocationQuotaAdjusterSettingsPath( + 'projectValue', + 'locationValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates + .projectLocationQuotaAdjusterSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationQuotaAdjusterSettingsName', () => { + const result = + client.matchProjectFromProjectLocationQuotaAdjusterSettingsName( + fakePath, + ); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates + .projectLocationQuotaAdjusterSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationQuotaAdjusterSettingsName', () => { + const result = + client.matchLocationFromProjectLocationQuotaAdjusterSettingsName( + fakePath, + ); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates + .projectLocationQuotaAdjusterSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocationQuotaPreference', async () => { - const fakePath = "/rendered/path/projectLocationQuotaPreference"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - quota_preference: "quotaPreferenceValue", - }; - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectLocationQuotaPreferencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationQuotaPreferencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationQuotaPreferencePath', () => { - const result = client.projectLocationQuotaPreferencePath("projectValue", "locationValue", "quotaPreferenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationQuotaPreferencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationQuotaPreferenceName', () => { - const result = client.matchProjectFromProjectLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationQuotaPreferenceName', () => { - const result = client.matchLocationFromProjectLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchQuotaPreferenceFromProjectLocationQuotaPreferenceName', () => { - const result = client.matchQuotaPreferenceFromProjectLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "quotaPreferenceValue"); - assert((client.pathTemplates.projectLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocationQuotaPreference', async () => { + const fakePath = '/rendered/path/projectLocationQuotaPreference'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + quota_preference: 'quotaPreferenceValue', + }; + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectLocationQuotaPreferencePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectLocationQuotaPreferencePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('projectLocationQuotaPreferencePath', () => { + const result = client.projectLocationQuotaPreferencePath( + 'projectValue', + 'locationValue', + 'quotaPreferenceValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectLocationQuotaPreferencePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationQuotaPreferenceName', () => { + const result = + client.matchProjectFromProjectLocationQuotaPreferenceName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationQuotaPreferenceName', () => { + const result = + client.matchLocationFromProjectLocationQuotaPreferenceName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.projectLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchQuotaPreferenceFromProjectLocationQuotaPreferenceName', () => { + const result = + client.matchQuotaPreferenceFromProjectLocationQuotaPreferenceName( + fakePath, + ); + assert.strictEqual(result, 'quotaPreferenceValue'); + assert( + ( + client.pathTemplates.projectLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocationService', async () => { - const fakePath = "/rendered/path/projectLocationService"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - service: "serviceValue", - }; - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectLocationServicePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationServicePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationServicePath', () => { - const result = client.projectLocationServicePath("projectValue", "locationValue", "serviceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationServicePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationServiceName', () => { - const result = client.matchProjectFromProjectLocationServiceName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationServiceName', () => { - const result = client.matchLocationFromProjectLocationServiceName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromProjectLocationServiceName', () => { - const result = client.matchServiceFromProjectLocationServiceName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectLocationServicePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocationService', async () => { + const fakePath = '/rendered/path/projectLocationService'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + service: 'serviceValue', + }; + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectLocationServicePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectLocationServicePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectLocationServicePath', () => { + const result = client.projectLocationServicePath( + 'projectValue', + 'locationValue', + 'serviceValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectLocationServicePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationServiceName', () => { + const result = + client.matchProjectFromProjectLocationServiceName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectLocationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationServiceName', () => { + const result = + client.matchLocationFromProjectLocationServiceName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.projectLocationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectLocationServiceName', () => { + const result = + client.matchServiceFromProjectLocationServiceName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.projectLocationServicePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocationServiceQuotaInfo', async () => { - const fakePath = "/rendered/path/projectLocationServiceQuotaInfo"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - service: "serviceValue", - quota_info: "quotaInfoValue", - }; - const client = new cloudquotasModule.v1beta.CloudQuotasClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationServiceQuotaInfoPath', () => { - const result = client.projectLocationServiceQuotaInfoPath("projectValue", "locationValue", "serviceValue", "quotaInfoValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationServiceQuotaInfoName', () => { - const result = client.matchProjectFromProjectLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationServiceQuotaInfoName', () => { - const result = client.matchLocationFromProjectLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromProjectLocationServiceQuotaInfoName', () => { - const result = client.matchServiceFromProjectLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchQuotaInfoFromProjectLocationServiceQuotaInfoName', () => { - const result = client.matchQuotaInfoFromProjectLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "quotaInfoValue"); - assert((client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocationServiceQuotaInfo', async () => { + const fakePath = '/rendered/path/projectLocationServiceQuotaInfo'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + service: 'serviceValue', + quota_info: 'quotaInfoValue', + }; + const client = new cloudquotasModule.v1beta.CloudQuotasClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('projectLocationServiceQuotaInfoPath', () => { + const result = client.projectLocationServiceQuotaInfoPath( + 'projectValue', + 'locationValue', + 'serviceValue', + 'quotaInfoValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationServiceQuotaInfoName', () => { + const result = + client.matchProjectFromProjectLocationServiceQuotaInfoName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationServiceQuotaInfoName', () => { + const result = + client.matchLocationFromProjectLocationServiceQuotaInfoName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectLocationServiceQuotaInfoName', () => { + const result = + client.matchServiceFromProjectLocationServiceQuotaInfoName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchQuotaInfoFromProjectLocationServiceQuotaInfoName', () => { + const result = + client.matchQuotaInfoFromProjectLocationServiceQuotaInfoName( + fakePath, + ); + assert.strictEqual(result, 'quotaInfoValue'); + assert( + ( + client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-api-cloudquotas/test/gapic_quota_adjuster_settings_manager_v1beta.ts b/packages/google-api-cloudquotas/test/gapic_quota_adjuster_settings_manager_v1beta.ts index 545584848030..3761dfd9e35d 100644 --- a/packages/google-api-cloudquotas/test/gapic_quota_adjuster_settings_manager_v1beta.ts +++ b/packages/google-api-cloudquotas/test/gapic_quota_adjuster_settings_manager_v1beta.ts @@ -19,833 +19,1338 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as quotaadjustersettingsmanagerModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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); } describe('v1beta.QuotaAdjusterSettingsManagerClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'cloudquotas.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient(); - 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 = quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient.servicePath; - assert.strictEqual(servicePath, 'cloudquotas.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'cloudquotas.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudquotas.example.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'cloudquotas.googleapis.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudquotas.example.com'); - }); + it('has universeDomain', () => { + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.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 quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudquotas.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 quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'cloudquotas.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 quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + quotaadjustersettingsmanagerModule.v1beta + .QuotaAdjusterSettingsManagerClient.servicePath; + assert.strictEqual(servicePath, 'cloudquotas.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + quotaadjustersettingsmanagerModule.v1beta + .QuotaAdjusterSettingsManagerClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'cloudquotas.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { universeDomain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudquotas.example.com'); + }); - it('has port', () => { - const port = quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { universe_domain: 'example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudquotas.example.com'); + }); - it('should create a client with no option', () => { - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient(); - assert(client); + 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 quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudquotas.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('should create a client with gRPC fallback', () => { - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({ - fallback: true, - }); - assert(client); + 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 quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { universeDomain: 'configured.example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'cloudquotas.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 quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { universe_domain: 'example.com', universeDomain: 'example.net' }, + ); + }); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.quotaAdjusterSettingsManagerStub, undefined); - await client.initialize(); - assert(client.quotaAdjusterSettingsManagerStub); - }); + it('has port', () => { + const port = + quotaadjustersettingsmanagerModule.v1beta + .QuotaAdjusterSettingsManagerClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has close method for the initialized client', done => { - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.quotaAdjusterSettingsManagerStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with no option', () => { + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient(); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.quotaAdjusterSettingsManagerStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { + fallback: true, + }, + ); + assert(client); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({ - 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 initialize method and supports deferred initialization', async () => { + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.quotaAdjusterSettingsManagerStub, undefined); + await client.initialize(); + assert(client.quotaAdjusterSettingsManagerStub); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({ - 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('has close method for the initialized client', (done) => { + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + client.initialize().catch((err) => { + throw err; + }); + assert(client.quotaAdjusterSettingsManagerStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('updateQuotaAdjusterSettings', () => { - it('invokes updateQuotaAdjusterSettings without error', async () => { - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.UpdateQuotaAdjusterSettingsRequest() - ); - request.quotaAdjusterSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.UpdateQuotaAdjusterSettingsRequest', ['quotaAdjusterSettings', 'name']); - request.quotaAdjusterSettings.name = defaultValue1; - const expectedHeaderRequestParams = `quota_adjuster_settings.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.QuotaAdjusterSettings() - ); - client.innerApiCalls.updateQuotaAdjusterSettings = stubSimpleCall(expectedResponse); - const [response] = await client.updateQuotaAdjusterSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateQuotaAdjusterSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateQuotaAdjusterSettings 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 quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + assert.strictEqual(client.quotaAdjusterSettingsManagerStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('invokes updateQuotaAdjusterSettings without error using callback', async () => { - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.UpdateQuotaAdjusterSettingsRequest() - ); - request.quotaAdjusterSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.UpdateQuotaAdjusterSettingsRequest', ['quotaAdjusterSettings', 'name']); - request.quotaAdjusterSettings.name = defaultValue1; - const expectedHeaderRequestParams = `quota_adjuster_settings.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.QuotaAdjusterSettings() - ); - client.innerApiCalls.updateQuotaAdjusterSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateQuotaAdjusterSettings( - request, - (err?: Error|null, result?: protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateQuotaAdjusterSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateQuotaAdjusterSettings 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 quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { + 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 updateQuotaAdjusterSettings with error', async () => { - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.UpdateQuotaAdjusterSettingsRequest() - ); - request.quotaAdjusterSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.UpdateQuotaAdjusterSettingsRequest', ['quotaAdjusterSettings', 'name']); - request.quotaAdjusterSettings.name = defaultValue1; - const expectedHeaderRequestParams = `quota_adjuster_settings.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateQuotaAdjusterSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateQuotaAdjusterSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.updateQuotaAdjusterSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateQuotaAdjusterSettings 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 quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { + 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('updateQuotaAdjusterSettings', () => { + it('invokes updateQuotaAdjusterSettings without error', async () => { + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.UpdateQuotaAdjusterSettingsRequest(), + ); + request.quotaAdjusterSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.UpdateQuotaAdjusterSettingsRequest', + ['quotaAdjusterSettings', 'name'], + ); + request.quotaAdjusterSettings.name = defaultValue1; + const expectedHeaderRequestParams = `quota_adjuster_settings.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaAdjusterSettings(), + ); + client.innerApiCalls.updateQuotaAdjusterSettings = + stubSimpleCall(expectedResponse); + const [response] = await client.updateQuotaAdjusterSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateQuotaAdjusterSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateQuotaAdjusterSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateQuotaAdjusterSettings with closed client', async () => { - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.UpdateQuotaAdjusterSettingsRequest() - ); - request.quotaAdjusterSettings ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.UpdateQuotaAdjusterSettingsRequest', ['quotaAdjusterSettings', 'name']); - request.quotaAdjusterSettings.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateQuotaAdjusterSettings(request), expectedError); - }); + it('invokes updateQuotaAdjusterSettings without error using callback', async () => { + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.UpdateQuotaAdjusterSettingsRequest(), + ); + request.quotaAdjusterSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.UpdateQuotaAdjusterSettingsRequest', + ['quotaAdjusterSettings', 'name'], + ); + request.quotaAdjusterSettings.name = defaultValue1; + const expectedHeaderRequestParams = `quota_adjuster_settings.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaAdjusterSettings(), + ); + client.innerApiCalls.updateQuotaAdjusterSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateQuotaAdjusterSettings( + request, + ( + err?: Error | null, + result?: protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateQuotaAdjusterSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateQuotaAdjusterSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getQuotaAdjusterSettings', () => { - it('invokes getQuotaAdjusterSettings without error', async () => { - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.GetQuotaAdjusterSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.GetQuotaAdjusterSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.QuotaAdjusterSettings() - ); - client.innerApiCalls.getQuotaAdjusterSettings = stubSimpleCall(expectedResponse); - const [response] = await client.getQuotaAdjusterSettings(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getQuotaAdjusterSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQuotaAdjusterSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateQuotaAdjusterSettings with error', async () => { + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.UpdateQuotaAdjusterSettingsRequest(), + ); + request.quotaAdjusterSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.UpdateQuotaAdjusterSettingsRequest', + ['quotaAdjusterSettings', 'name'], + ); + request.quotaAdjusterSettings.name = defaultValue1; + const expectedHeaderRequestParams = `quota_adjuster_settings.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateQuotaAdjusterSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.updateQuotaAdjusterSettings(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.updateQuotaAdjusterSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateQuotaAdjusterSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getQuotaAdjusterSettings without error using callback', async () => { - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.GetQuotaAdjusterSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.GetQuotaAdjusterSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.QuotaAdjusterSettings() - ); - client.innerApiCalls.getQuotaAdjusterSettings = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getQuotaAdjusterSettings( - request, - (err?: Error|null, result?: protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getQuotaAdjusterSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQuotaAdjusterSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateQuotaAdjusterSettings with closed client', async () => { + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.UpdateQuotaAdjusterSettingsRequest(), + ); + request.quotaAdjusterSettings ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.UpdateQuotaAdjusterSettingsRequest', + ['quotaAdjusterSettings', 'name'], + ); + request.quotaAdjusterSettings.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.updateQuotaAdjusterSettings(request), + expectedError, + ); + }); + }); + + describe('getQuotaAdjusterSettings', () => { + it('invokes getQuotaAdjusterSettings without error', async () => { + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.GetQuotaAdjusterSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.GetQuotaAdjusterSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaAdjusterSettings(), + ); + client.innerApiCalls.getQuotaAdjusterSettings = + stubSimpleCall(expectedResponse); + const [response] = await client.getQuotaAdjusterSettings(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getQuotaAdjusterSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQuotaAdjusterSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getQuotaAdjusterSettings with error', async () => { - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.GetQuotaAdjusterSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.GetQuotaAdjusterSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getQuotaAdjusterSettings = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getQuotaAdjusterSettings(request), expectedError); - const actualRequest = (client.innerApiCalls.getQuotaAdjusterSettings as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getQuotaAdjusterSettings as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getQuotaAdjusterSettings without error using callback', async () => { + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.GetQuotaAdjusterSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.GetQuotaAdjusterSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.QuotaAdjusterSettings(), + ); + client.innerApiCalls.getQuotaAdjusterSettings = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getQuotaAdjusterSettings( + request, + ( + err?: Error | null, + result?: protos.google.api.cloudquotas.v1beta.IQuotaAdjusterSettings | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getQuotaAdjusterSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQuotaAdjusterSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getQuotaAdjusterSettings with closed client', async () => { - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.cloudquotas.v1beta.GetQuotaAdjusterSettingsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.cloudquotas.v1beta.GetQuotaAdjusterSettingsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getQuotaAdjusterSettings(request), expectedError); - }); + it('invokes getQuotaAdjusterSettings with error', async () => { + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.GetQuotaAdjusterSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.GetQuotaAdjusterSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getQuotaAdjusterSettings = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects( + client.getQuotaAdjusterSettings(request), + expectedError, + ); + const actualRequest = ( + client.innerApiCalls.getQuotaAdjusterSettings as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getQuotaAdjusterSettings as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('Path templates', () => { - - describe('folderLocationQuotaAdjusterSettings', async () => { - const fakePath = "/rendered/path/folderLocationQuotaAdjusterSettings"; - const expectedParameters = { - folder: "folderValue", - location: "locationValue", - }; - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLocationQuotaAdjusterSettingsPath', () => { - const result = client.folderLocationQuotaAdjusterSettingsPath("folderValue", "locationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLocationQuotaAdjusterSettingsName', () => { - const result = client.matchFolderFromFolderLocationQuotaAdjusterSettingsName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromFolderLocationQuotaAdjusterSettingsName', () => { - const result = client.matchLocationFromFolderLocationQuotaAdjusterSettingsName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + it('invokes getQuotaAdjusterSettings with closed client', async () => { + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.cloudquotas.v1beta.GetQuotaAdjusterSettingsRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.cloudquotas.v1beta.GetQuotaAdjusterSettingsRequest', + ['name'], + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects( + client.getQuotaAdjusterSettings(request), + expectedError, + ); + }); + }); + + describe('Path templates', () => { + describe('folderLocationQuotaAdjusterSettings', async () => { + const fakePath = '/rendered/path/folderLocationQuotaAdjusterSettings'; + const expectedParameters = { + folder: 'folderValue', + location: 'locationValue', + }; + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('folderLocationQuotaAdjusterSettingsPath', () => { + const result = client.folderLocationQuotaAdjusterSettingsPath( + 'folderValue', + 'locationValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLocationQuotaAdjusterSettingsName', () => { + const result = + client.matchFolderFromFolderLocationQuotaAdjusterSettingsName( + fakePath, + ); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromFolderLocationQuotaAdjusterSettingsName', () => { + const result = + client.matchLocationFromFolderLocationQuotaAdjusterSettingsName( + fakePath, + ); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.folderLocationQuotaAdjusterSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderLocationQuotaPreference', async () => { - const fakePath = "/rendered/path/folderLocationQuotaPreference"; - const expectedParameters = { - folder: "folderValue", - location: "locationValue", - quota_preference: "quotaPreferenceValue", - }; - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderLocationQuotaPreferencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLocationQuotaPreferencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLocationQuotaPreferencePath', () => { - const result = client.folderLocationQuotaPreferencePath("folderValue", "locationValue", "quotaPreferenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLocationQuotaPreferencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLocationQuotaPreferenceName', () => { - const result = client.matchFolderFromFolderLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromFolderLocationQuotaPreferenceName', () => { - const result = client.matchLocationFromFolderLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.folderLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchQuotaPreferenceFromFolderLocationQuotaPreferenceName', () => { - const result = client.matchQuotaPreferenceFromFolderLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "quotaPreferenceValue"); - assert((client.pathTemplates.folderLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderLocationQuotaPreference', async () => { + const fakePath = '/rendered/path/folderLocationQuotaPreference'; + const expectedParameters = { + folder: 'folderValue', + location: 'locationValue', + quota_preference: 'quotaPreferenceValue', + }; + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.folderLocationQuotaPreferencePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.folderLocationQuotaPreferencePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('folderLocationQuotaPreferencePath', () => { + const result = client.folderLocationQuotaPreferencePath( + 'folderValue', + 'locationValue', + 'quotaPreferenceValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderLocationQuotaPreferencePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLocationQuotaPreferenceName', () => { + const result = + client.matchFolderFromFolderLocationQuotaPreferenceName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromFolderLocationQuotaPreferenceName', () => { + const result = + client.matchLocationFromFolderLocationQuotaPreferenceName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.folderLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchQuotaPreferenceFromFolderLocationQuotaPreferenceName', () => { + const result = + client.matchQuotaPreferenceFromFolderLocationQuotaPreferenceName( + fakePath, + ); + assert.strictEqual(result, 'quotaPreferenceValue'); + assert( + ( + client.pathTemplates.folderLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('folderLocationServiceQuotaInfo', async () => { - const fakePath = "/rendered/path/folderLocationServiceQuotaInfo"; - const expectedParameters = { - folder: "folderValue", - location: "locationValue", - service: "serviceValue", - quota_info: "quotaInfoValue", - }; - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('folderLocationServiceQuotaInfoPath', () => { - const result = client.folderLocationServiceQuotaInfoPath("folderValue", "locationValue", "serviceValue", "quotaInfoValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchFolderFromFolderLocationServiceQuotaInfoName', () => { - const result = client.matchFolderFromFolderLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "folderValue"); - assert((client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromFolderLocationServiceQuotaInfoName', () => { - const result = client.matchLocationFromFolderLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromFolderLocationServiceQuotaInfoName', () => { - const result = client.matchServiceFromFolderLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchQuotaInfoFromFolderLocationServiceQuotaInfoName', () => { - const result = client.matchQuotaInfoFromFolderLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "quotaInfoValue"); - assert((client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('folderLocationServiceQuotaInfo', async () => { + const fakePath = '/rendered/path/folderLocationServiceQuotaInfo'; + const expectedParameters = { + folder: 'folderValue', + location: 'locationValue', + service: 'serviceValue', + quota_info: 'quotaInfoValue', + }; + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('folderLocationServiceQuotaInfoPath', () => { + const result = client.folderLocationServiceQuotaInfoPath( + 'folderValue', + 'locationValue', + 'serviceValue', + 'quotaInfoValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchFolderFromFolderLocationServiceQuotaInfoName', () => { + const result = + client.matchFolderFromFolderLocationServiceQuotaInfoName(fakePath); + assert.strictEqual(result, 'folderValue'); + assert( + ( + client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromFolderLocationServiceQuotaInfoName', () => { + const result = + client.matchLocationFromFolderLocationServiceQuotaInfoName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromFolderLocationServiceQuotaInfoName', () => { + const result = + client.matchServiceFromFolderLocationServiceQuotaInfoName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchQuotaInfoFromFolderLocationServiceQuotaInfoName', () => { + const result = + client.matchQuotaInfoFromFolderLocationServiceQuotaInfoName(fakePath); + assert.strictEqual(result, 'quotaInfoValue'); + assert( + ( + client.pathTemplates.folderLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLocationQuotaAdjusterSettings', async () => { - const fakePath = "/rendered/path/organizationLocationQuotaAdjusterSettings"; - const expectedParameters = { - organization: "organizationValue", - location: "locationValue", - }; - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLocationQuotaAdjusterSettingsPath', () => { - const result = client.organizationLocationQuotaAdjusterSettingsPath("organizationValue", "locationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLocationQuotaAdjusterSettingsName', () => { - const result = client.matchOrganizationFromOrganizationLocationQuotaAdjusterSettingsName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromOrganizationLocationQuotaAdjusterSettingsName', () => { - const result = client.matchLocationFromOrganizationLocationQuotaAdjusterSettingsName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLocationQuotaAdjusterSettings', async () => { + const fakePath = + '/rendered/path/organizationLocationQuotaAdjusterSettings'; + const expectedParameters = { + organization: 'organizationValue', + location: 'locationValue', + }; + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationLocationQuotaAdjusterSettingsPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationLocationQuotaAdjusterSettingsPath', () => { + const result = client.organizationLocationQuotaAdjusterSettingsPath( + 'organizationValue', + 'locationValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates + .organizationLocationQuotaAdjusterSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLocationQuotaAdjusterSettingsName', () => { + const result = + client.matchOrganizationFromOrganizationLocationQuotaAdjusterSettingsName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates + .organizationLocationQuotaAdjusterSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromOrganizationLocationQuotaAdjusterSettingsName', () => { + const result = + client.matchLocationFromOrganizationLocationQuotaAdjusterSettingsName( + fakePath, + ); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates + .organizationLocationQuotaAdjusterSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLocationQuotaPreference', async () => { - const fakePath = "/rendered/path/organizationLocationQuotaPreference"; - const expectedParameters = { - organization: "organizationValue", - location: "locationValue", - quota_preference: "quotaPreferenceValue", - }; - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLocationQuotaPreferencePath', () => { - const result = client.organizationLocationQuotaPreferencePath("organizationValue", "locationValue", "quotaPreferenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLocationQuotaPreferenceName', () => { - const result = client.matchOrganizationFromOrganizationLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromOrganizationLocationQuotaPreferenceName', () => { - const result = client.matchLocationFromOrganizationLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchQuotaPreferenceFromOrganizationLocationQuotaPreferenceName', () => { - const result = client.matchQuotaPreferenceFromOrganizationLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "quotaPreferenceValue"); - assert((client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLocationQuotaPreference', async () => { + const fakePath = '/rendered/path/organizationLocationQuotaPreference'; + const expectedParameters = { + organization: 'organizationValue', + location: 'locationValue', + quota_preference: 'quotaPreferenceValue', + }; + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationLocationQuotaPreferencePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationLocationQuotaPreferencePath', () => { + const result = client.organizationLocationQuotaPreferencePath( + 'organizationValue', + 'locationValue', + 'quotaPreferenceValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.organizationLocationQuotaPreferencePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLocationQuotaPreferenceName', () => { + const result = + client.matchOrganizationFromOrganizationLocationQuotaPreferenceName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates.organizationLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromOrganizationLocationQuotaPreferenceName', () => { + const result = + client.matchLocationFromOrganizationLocationQuotaPreferenceName( + fakePath, + ); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.organizationLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchQuotaPreferenceFromOrganizationLocationQuotaPreferenceName', () => { + const result = + client.matchQuotaPreferenceFromOrganizationLocationQuotaPreferenceName( + fakePath, + ); + assert.strictEqual(result, 'quotaPreferenceValue'); + assert( + ( + client.pathTemplates.organizationLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('organizationLocationServiceQuotaInfo', async () => { - const fakePath = "/rendered/path/organizationLocationServiceQuotaInfo"; - const expectedParameters = { - organization: "organizationValue", - location: "locationValue", - service: "serviceValue", - quota_info: "quotaInfoValue", - }; - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('organizationLocationServiceQuotaInfoPath', () => { - const result = client.organizationLocationServiceQuotaInfoPath("organizationValue", "locationValue", "serviceValue", "quotaInfoValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchOrganizationFromOrganizationLocationServiceQuotaInfoName', () => { - const result = client.matchOrganizationFromOrganizationLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "organizationValue"); - assert((client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromOrganizationLocationServiceQuotaInfoName', () => { - const result = client.matchLocationFromOrganizationLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromOrganizationLocationServiceQuotaInfoName', () => { - const result = client.matchServiceFromOrganizationLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchQuotaInfoFromOrganizationLocationServiceQuotaInfoName', () => { - const result = client.matchQuotaInfoFromOrganizationLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "quotaInfoValue"); - assert((client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('organizationLocationServiceQuotaInfo', async () => { + const fakePath = '/rendered/path/organizationLocationServiceQuotaInfo'; + const expectedParameters = { + organization: 'organizationValue', + location: 'locationValue', + service: 'serviceValue', + quota_info: 'quotaInfoValue', + }; + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.organizationLocationServiceQuotaInfoPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('organizationLocationServiceQuotaInfoPath', () => { + const result = client.organizationLocationServiceQuotaInfoPath( + 'organizationValue', + 'locationValue', + 'serviceValue', + 'quotaInfoValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates + .organizationLocationServiceQuotaInfoPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchOrganizationFromOrganizationLocationServiceQuotaInfoName', () => { + const result = + client.matchOrganizationFromOrganizationLocationServiceQuotaInfoName( + fakePath, + ); + assert.strictEqual(result, 'organizationValue'); + assert( + ( + client.pathTemplates + .organizationLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromOrganizationLocationServiceQuotaInfoName', () => { + const result = + client.matchLocationFromOrganizationLocationServiceQuotaInfoName( + fakePath, + ); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates + .organizationLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromOrganizationLocationServiceQuotaInfoName', () => { + const result = + client.matchServiceFromOrganizationLocationServiceQuotaInfoName( + fakePath, + ); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates + .organizationLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchQuotaInfoFromOrganizationLocationServiceQuotaInfoName', () => { + const result = + client.matchQuotaInfoFromOrganizationLocationServiceQuotaInfoName( + fakePath, + ); + assert.strictEqual(result, 'quotaInfoValue'); + assert( + ( + client.pathTemplates + .organizationLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocationQuotaAdjusterSettings', async () => { - const fakePath = "/rendered/path/projectLocationQuotaAdjusterSettings"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - }; - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationQuotaAdjusterSettingsPath', () => { - const result = client.projectLocationQuotaAdjusterSettingsPath("projectValue", "locationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationQuotaAdjusterSettingsName', () => { - const result = client.matchProjectFromProjectLocationQuotaAdjusterSettingsName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationQuotaAdjusterSettingsName', () => { - const result = client.matchLocationFromProjectLocationQuotaAdjusterSettingsName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocationQuotaAdjusterSettings', async () => { + const fakePath = '/rendered/path/projectLocationQuotaAdjusterSettings'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + }; + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectLocationQuotaAdjusterSettingsPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('projectLocationQuotaAdjusterSettingsPath', () => { + const result = client.projectLocationQuotaAdjusterSettingsPath( + 'projectValue', + 'locationValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates + .projectLocationQuotaAdjusterSettingsPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationQuotaAdjusterSettingsName', () => { + const result = + client.matchProjectFromProjectLocationQuotaAdjusterSettingsName( + fakePath, + ); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates + .projectLocationQuotaAdjusterSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationQuotaAdjusterSettingsName', () => { + const result = + client.matchLocationFromProjectLocationQuotaAdjusterSettingsName( + fakePath, + ); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates + .projectLocationQuotaAdjusterSettingsPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocationQuotaPreference', async () => { - const fakePath = "/rendered/path/projectLocationQuotaPreference"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - quota_preference: "quotaPreferenceValue", - }; - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectLocationQuotaPreferencePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationQuotaPreferencePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationQuotaPreferencePath', () => { - const result = client.projectLocationQuotaPreferencePath("projectValue", "locationValue", "quotaPreferenceValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationQuotaPreferencePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationQuotaPreferenceName', () => { - const result = client.matchProjectFromProjectLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationQuotaPreferenceName', () => { - const result = client.matchLocationFromProjectLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchQuotaPreferenceFromProjectLocationQuotaPreferenceName', () => { - const result = client.matchQuotaPreferenceFromProjectLocationQuotaPreferenceName(fakePath); - assert.strictEqual(result, "quotaPreferenceValue"); - assert((client.pathTemplates.projectLocationQuotaPreferencePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocationQuotaPreference', async () => { + const fakePath = '/rendered/path/projectLocationQuotaPreference'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + quota_preference: 'quotaPreferenceValue', + }; + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.projectLocationQuotaPreferencePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectLocationQuotaPreferencePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('projectLocationQuotaPreferencePath', () => { + const result = client.projectLocationQuotaPreferencePath( + 'projectValue', + 'locationValue', + 'quotaPreferenceValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectLocationQuotaPreferencePathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationQuotaPreferenceName', () => { + const result = + client.matchProjectFromProjectLocationQuotaPreferenceName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationQuotaPreferenceName', () => { + const result = + client.matchLocationFromProjectLocationQuotaPreferenceName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.projectLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchQuotaPreferenceFromProjectLocationQuotaPreferenceName', () => { + const result = + client.matchQuotaPreferenceFromProjectLocationQuotaPreferenceName( + fakePath, + ); + assert.strictEqual(result, 'quotaPreferenceValue'); + assert( + ( + client.pathTemplates.projectLocationQuotaPreferencePathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + }); - describe('projectLocationServiceQuotaInfo', async () => { - const fakePath = "/rendered/path/projectLocationServiceQuotaInfo"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - service: "serviceValue", - quota_info: "quotaInfoValue", - }; - const client = new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectLocationServiceQuotaInfoPath', () => { - const result = client.projectLocationServiceQuotaInfoPath("projectValue", "locationValue", "serviceValue", "quotaInfoValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectLocationServiceQuotaInfoName', () => { - const result = client.matchProjectFromProjectLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromProjectLocationServiceQuotaInfoName', () => { - const result = client.matchLocationFromProjectLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchServiceFromProjectLocationServiceQuotaInfoName', () => { - const result = client.matchServiceFromProjectLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "serviceValue"); - assert((client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchQuotaInfoFromProjectLocationServiceQuotaInfoName', () => { - const result = client.matchQuotaInfoFromProjectLocationServiceQuotaInfoName(fakePath); - assert.strictEqual(result, "quotaInfoValue"); - assert((client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('projectLocationServiceQuotaInfo', async () => { + const fakePath = '/rendered/path/projectLocationServiceQuotaInfo'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + service: 'serviceValue', + quota_info: 'quotaInfoValue', + }; + const client = + new quotaadjustersettingsmanagerModule.v1beta.QuotaAdjusterSettingsManagerClient( + { + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }, + ); + await client.initialize(); + client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('projectLocationServiceQuotaInfoPath', () => { + const result = client.projectLocationServiceQuotaInfoPath( + 'projectValue', + 'locationValue', + 'serviceValue', + 'quotaInfoValue', + ); + assert.strictEqual(result, fakePath); + assert( + ( + client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate + .render as SinonStub + ) + .getCall(-1) + .calledWith(expectedParameters), + ); + }); + + it('matchProjectFromProjectLocationServiceQuotaInfoName', () => { + const result = + client.matchProjectFromProjectLocationServiceQuotaInfoName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + ( + client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchLocationFromProjectLocationServiceQuotaInfoName', () => { + const result = + client.matchLocationFromProjectLocationServiceQuotaInfoName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + ( + client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchServiceFromProjectLocationServiceQuotaInfoName', () => { + const result = + client.matchServiceFromProjectLocationServiceQuotaInfoName(fakePath); + assert.strictEqual(result, 'serviceValue'); + assert( + ( + client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); + + it('matchQuotaInfoFromProjectLocationServiceQuotaInfoName', () => { + const result = + client.matchQuotaInfoFromProjectLocationServiceQuotaInfoName( + fakePath, + ); + assert.strictEqual(result, 'quotaInfoValue'); + assert( + ( + client.pathTemplates.projectLocationServiceQuotaInfoPathTemplate + .match as SinonStub + ) + .getCall(-1) + .calledWith(fakePath), + ); + }); }); + }); }); diff --git a/packages/google-api-cloudquotas/webpack.config.js b/packages/google-api-cloudquotas/webpack.config.js index 8ceeb0d692a8..80d563ebb4ac 100644 --- a/packages/google-api-cloudquotas/webpack.config.js +++ b/packages/google-api-cloudquotas/webpack.config.js @@ -1,4 +1,4 @@ -// Copyright 2026 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/packages/google-api-servicecontrol/.eslintignore b/packages/google-api-servicecontrol/.eslintignore new file mode 100644 index 000000000000..cfc348ec4d11 --- /dev/null +++ b/packages/google-api-servicecontrol/.eslintignore @@ -0,0 +1,7 @@ +**/node_modules +**/.coverage +build/ +docs/ +protos/ +system-test/ +samples/generated/ diff --git a/packages/google-api-servicecontrol/.eslintrc.json b/packages/google-api-servicecontrol/.eslintrc.json new file mode 100644 index 000000000000..3e8d97ccb390 --- /dev/null +++ b/packages/google-api-servicecontrol/.eslintrc.json @@ -0,0 +1,4 @@ +{ + "extends": "./node_modules/gts", + "root": true +} diff --git a/packages/google-api-servicecontrol/README.md b/packages/google-api-servicecontrol/README.md index bc530c0f5f1a..53a032e41cd0 100644 --- a/packages/google-api-servicecontrol/README.md +++ b/packages/google-api-servicecontrol/README.md @@ -98,7 +98,7 @@ More Information: [Google Cloud Platform Launch Stages][launch_stages] ## Contributing -Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-api-servicecontrol/CONTRIBUTING.md). +Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/google-cloud-node/blob/main/CONTRIBUTING.md). Please note that this `README.md` and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`) @@ -108,7 +108,7 @@ are generated from a central template. Apache Version 2.0 -See [LICENSE](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-api-servicecontrol/LICENSE) +See [LICENSE](https://github.com/googleapis/google-cloud-node/blob/main/LICENSE) [shell_img]: https://gstatic.com/cloudssh/images/open-btn.png [projects]: https://console.cloud.google.com/project diff --git a/packages/google-api-servicecontrol/protos/protos.d.ts b/packages/google-api-servicecontrol/protos/protos.d.ts index 63cc0b98edcd..94294c1c5b52 100644 --- a/packages/google-api-servicecontrol/protos/protos.d.ts +++ b/packages/google-api-servicecontrol/protos/protos.d.ts @@ -758,6 +758,7 @@ export namespace google { /** Edition enum. */ enum Edition { EDITION_UNKNOWN = 0, + EDITION_LEGACY = 900, EDITION_PROTO2 = 998, EDITION_PROTO3 = 999, EDITION_2023 = 1000, @@ -788,6 +789,9 @@ export namespace google { /** FileDescriptorProto weakDependency */ weakDependency?: (number[]|null); + /** FileDescriptorProto optionDependency */ + optionDependency?: (string[]|null); + /** FileDescriptorProto messageType */ messageType?: (google.protobuf.IDescriptorProto[]|null); @@ -837,6 +841,9 @@ export namespace google { /** FileDescriptorProto weakDependency. */ public weakDependency: number[]; + /** FileDescriptorProto optionDependency. */ + public optionDependency: string[]; + /** FileDescriptorProto messageType. */ public messageType: google.protobuf.IDescriptorProto[]; @@ -971,6 +978,9 @@ export namespace google { /** DescriptorProto reservedName */ reservedName?: (string[]|null); + + /** DescriptorProto visibility */ + visibility?: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility|null); } /** Represents a DescriptorProto. */ @@ -1012,6 +1022,9 @@ export namespace google { /** DescriptorProto reservedName. */ public reservedName: string[]; + /** DescriptorProto visibility. */ + public visibility: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility); + /** * Creates a new DescriptorProto instance using the specified properties. * @param [properties] Properties to set @@ -1859,6 +1872,9 @@ export namespace google { /** EnumDescriptorProto reservedName */ reservedName?: (string[]|null); + + /** EnumDescriptorProto visibility */ + visibility?: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility|null); } /** Represents an EnumDescriptorProto. */ @@ -1885,6 +1901,9 @@ export namespace google { /** EnumDescriptorProto reservedName. */ public reservedName: string[]; + /** EnumDescriptorProto visibility. */ + public visibility: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility); + /** * Creates a new EnumDescriptorProto instance using the specified properties. * @param [properties] Properties to set @@ -2813,6 +2832,9 @@ 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); } @@ -2862,6 +2884,9 @@ 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[]; @@ -3082,6 +3107,121 @@ export namespace google { */ public static getTypeUrl(typeUrlPrefix?: string): string; } + + /** Properties of a FeatureSupport. */ + interface IFeatureSupport { + + /** FeatureSupport editionIntroduced */ + editionIntroduced?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + + /** FeatureSupport editionDeprecated */ + editionDeprecated?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + + /** FeatureSupport deprecationWarning */ + deprecationWarning?: (string|null); + + /** FeatureSupport editionRemoved */ + editionRemoved?: (google.protobuf.Edition|keyof typeof 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|keyof typeof google.protobuf.Edition); + + /** FeatureSupport editionDeprecated. */ + public editionDeprecated: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** FeatureSupport deprecationWarning. */ + public deprecationWarning: string; + + /** FeatureSupport editionRemoved. */ + public editionRemoved: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** + * Creates a new FeatureSupport instance using the specified properties. + * @param [properties] Properties to set + * @returns FeatureSupport instance + */ + public static create(properties?: google.protobuf.FieldOptions.IFeatureSupport): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Encodes the specified FeatureSupport message. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @param message FeatureSupport message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.FieldOptions.IFeatureSupport, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FeatureSupport message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @param message FeatureSupport message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.FieldOptions.IFeatureSupport, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Verifies a FeatureSupport message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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. */ @@ -3320,6 +3460,9 @@ export namespace google { /** EnumValueOptions debugRedact */ debugRedact?: (boolean|null); + /** EnumValueOptions featureSupport */ + featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); + /** EnumValueOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } @@ -3342,6 +3485,9 @@ export namespace google { /** EnumValueOptions debugRedact. */ public debugRedact: boolean; + /** EnumValueOptions featureSupport. */ + public featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); + /** EnumValueOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -3931,6 +4077,12 @@ export namespace google { /** FeatureSet jsonFormat */ jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|keyof typeof google.protobuf.FeatureSet.JsonFormat|null); + + /** FeatureSet enforceNamingStyle */ + enforceNamingStyle?: (google.protobuf.FeatureSet.EnforceNamingStyle|keyof typeof google.protobuf.FeatureSet.EnforceNamingStyle|null); + + /** FeatureSet defaultSymbolVisibility */ + defaultSymbolVisibility?: (google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|keyof typeof google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|null); } /** Represents a FeatureSet. */ @@ -3960,6 +4112,12 @@ export namespace google { /** FeatureSet jsonFormat. */ public jsonFormat: (google.protobuf.FeatureSet.JsonFormat|keyof typeof google.protobuf.FeatureSet.JsonFormat); + /** FeatureSet enforceNamingStyle. */ + public enforceNamingStyle: (google.protobuf.FeatureSet.EnforceNamingStyle|keyof typeof google.protobuf.FeatureSet.EnforceNamingStyle); + + /** FeatureSet defaultSymbolVisibility. */ + public defaultSymbolVisibility: (google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|keyof typeof google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility); + /** * Creates a new FeatureSet instance using the specified properties. * @param [properties] Properties to set @@ -4082,6 +4240,116 @@ export namespace google { ALLOW = 1, LEGACY_BEST_EFFORT = 2 } + + /** EnforceNamingStyle enum. */ + enum EnforceNamingStyle { + ENFORCE_NAMING_STYLE_UNKNOWN = 0, + STYLE2024 = 1, + STYLE_LEGACY = 2 + } + + /** Properties of a VisibilityFeature. */ + interface IVisibilityFeature { + } + + /** Represents a VisibilityFeature. */ + class VisibilityFeature implements IVisibilityFeature { + + /** + * Constructs a new VisibilityFeature. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FeatureSet.IVisibilityFeature); + + /** + * Creates a new VisibilityFeature instance using the specified properties. + * @param [properties] Properties to set + * @returns VisibilityFeature instance + */ + public static create(properties?: google.protobuf.FeatureSet.IVisibilityFeature): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Encodes the specified VisibilityFeature message. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @param message VisibilityFeature message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.FeatureSet.IVisibilityFeature, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified VisibilityFeature message, length delimited. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @param message VisibilityFeature message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.FeatureSet.IVisibilityFeature, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Verifies a VisibilityFeature message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a VisibilityFeature message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns VisibilityFeature + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Creates a plain object from a VisibilityFeature message. Also converts values to other types if specified. + * @param message VisibilityFeature + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet.VisibilityFeature, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this VisibilityFeature to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for VisibilityFeature + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace VisibilityFeature { + + /** DefaultSymbolVisibility enum. */ + enum DefaultSymbolVisibility { + DEFAULT_SYMBOL_VISIBILITY_UNKNOWN = 0, + EXPORT_ALL = 1, + EXPORT_TOP_LEVEL = 2, + LOCAL_ALL = 3, + STRICT = 4 + } + } } /** Properties of a FeatureSetDefaults. */ @@ -4201,8 +4469,11 @@ export namespace google { /** FeatureSetEditionDefault edition */ edition?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); - /** FeatureSetEditionDefault features */ - features?: (google.protobuf.IFeatureSet|null); + /** FeatureSetEditionDefault overridableFeatures */ + overridableFeatures?: (google.protobuf.IFeatureSet|null); + + /** FeatureSetEditionDefault fixedFeatures */ + fixedFeatures?: (google.protobuf.IFeatureSet|null); } /** Represents a FeatureSetEditionDefault. */ @@ -4217,8 +4488,11 @@ export namespace google { /** FeatureSetEditionDefault edition. */ public edition: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); - /** FeatureSetEditionDefault features. */ - public features?: (google.protobuf.IFeatureSet|null); + /** FeatureSetEditionDefault overridableFeatures. */ + public overridableFeatures?: (google.protobuf.IFeatureSet|null); + + /** FeatureSetEditionDefault fixedFeatures. */ + public fixedFeatures?: (google.protobuf.IFeatureSet|null); /** * Creates a new FeatureSetEditionDefault instance using the specified properties. @@ -4750,6 +5024,13 @@ export namespace google { } } } + + /** SymbolVisibility enum. */ + enum SymbolVisibility { + VISIBILITY_UNSET = 0, + VISIBILITY_LOCAL = 1, + VISIBILITY_EXPORT = 2 + } } /** Namespace api. */ @@ -9602,6 +9883,9 @@ export namespace google { /** CommonLanguageSettings destinations */ destinations?: (google.api.ClientLibraryDestination[]|null); + + /** CommonLanguageSettings selectiveGapicGeneration */ + selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); } /** Represents a CommonLanguageSettings. */ @@ -9619,6 +9903,9 @@ export namespace google { /** CommonLanguageSettings destinations. */ public destinations: google.api.ClientLibraryDestination[]; + /** CommonLanguageSettings selectiveGapicGeneration. */ + public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + /** * Creates a new CommonLanguageSettings instance using the specified properties. * @param [properties] Properties to set @@ -10319,6 +10606,9 @@ export namespace google { /** PythonSettings common */ common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures */ + experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); } /** Represents a PythonSettings. */ @@ -10333,6 +10623,9 @@ export namespace google { /** PythonSettings common. */ public common?: (google.api.ICommonLanguageSettings|null); + /** PythonSettings experimentalFeatures. */ + public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + /** * Creates a new PythonSettings instance using the specified properties. * @param [properties] Properties to set @@ -10411,6 +10704,118 @@ 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); + + /** ExperimentalFeatures unversionedPackageDisabled */ + unversionedPackageDisabled?: (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; + + /** ExperimentalFeatures unversionedPackageDisabled. */ + public unversionedPackageDisabled: boolean; + + /** + * Creates a new ExperimentalFeatures instance using the specified properties. + * @param [properties] Properties to set + * @returns ExperimentalFeatures instance + */ + public static create(properties?: google.api.PythonSettings.IExperimentalFeatures): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Encodes the specified ExperimentalFeatures message. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @param message ExperimentalFeatures message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.PythonSettings.IExperimentalFeatures, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExperimentalFeatures message, length delimited. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @param message ExperimentalFeatures message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.PythonSettings.IExperimentalFeatures, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Verifies an ExperimentalFeatures message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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 { @@ -10737,6 +11142,9 @@ export namespace google { /** GoSettings common */ common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); } /** Represents a GoSettings. */ @@ -10751,6 +11159,9 @@ export namespace google { /** GoSettings common. */ public common?: (google.api.ICommonLanguageSettings|null); + /** GoSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + /** * Creates a new GoSettings instance using the specified properties. * @param [properties] Properties to set @@ -11075,6 +11486,109 @@ export namespace google { PACKAGE_MANAGER = 20 } + /** 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 new SelectiveGapicGeneration instance using the specified properties. + * @param [properties] Properties to set + * @returns SelectiveGapicGeneration instance + */ + public static create(properties?: google.api.ISelectiveGapicGeneration): google.api.SelectiveGapicGeneration; + + /** + * Encodes the specified SelectiveGapicGeneration message. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @param message SelectiveGapicGeneration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.ISelectiveGapicGeneration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SelectiveGapicGeneration message, length delimited. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @param message SelectiveGapicGeneration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.ISelectiveGapicGeneration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.SelectiveGapicGeneration; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.SelectiveGapicGeneration; + + /** + * Verifies a SelectiveGapicGeneration message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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. */ enum LaunchStage { LAUNCH_STAGE_UNSPECIFIED = 0, diff --git a/packages/google-api-servicecontrol/protos/protos.js b/packages/google-api-servicecontrol/protos/protos.js index 4229b7c4bf75..e5e5b982b6eb 100644 --- a/packages/google-api-servicecontrol/protos/protos.js +++ b/packages/google-api-servicecontrol/protos/protos.js @@ -1882,6 +1882,7 @@ * @name google.protobuf.Edition * @enum {number} * @property {number} EDITION_UNKNOWN=0 EDITION_UNKNOWN value + * @property {number} EDITION_LEGACY=900 EDITION_LEGACY value * @property {number} EDITION_PROTO2=998 EDITION_PROTO2 value * @property {number} EDITION_PROTO3=999 EDITION_PROTO3 value * @property {number} EDITION_2023=1000 EDITION_2023 value @@ -1896,6 +1897,7 @@ protobuf.Edition = (function() { var valuesById = {}, values = Object.create(valuesById); values[valuesById[0] = "EDITION_UNKNOWN"] = 0; + values[valuesById[900] = "EDITION_LEGACY"] = 900; values[valuesById[998] = "EDITION_PROTO2"] = 998; values[valuesById[999] = "EDITION_PROTO3"] = 999; values[valuesById[1000] = "EDITION_2023"] = 1000; @@ -1920,6 +1922,7 @@ * @property {Array.|null} [dependency] FileDescriptorProto dependency * @property {Array.|null} [publicDependency] FileDescriptorProto publicDependency * @property {Array.|null} [weakDependency] FileDescriptorProto weakDependency + * @property {Array.|null} [optionDependency] FileDescriptorProto optionDependency * @property {Array.|null} [messageType] FileDescriptorProto messageType * @property {Array.|null} [enumType] FileDescriptorProto enumType * @property {Array.|null} [service] FileDescriptorProto service @@ -1942,6 +1945,7 @@ this.dependency = []; this.publicDependency = []; this.weakDependency = []; + this.optionDependency = []; this.messageType = []; this.enumType = []; this.service = []; @@ -1992,6 +1996,14 @@ */ FileDescriptorProto.prototype.weakDependency = $util.emptyArray; + /** + * FileDescriptorProto optionDependency. + * @member {Array.} optionDependency + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.optionDependency = $util.emptyArray; + /** * FileDescriptorProto messageType. * @member {Array.} messageType @@ -2113,6 +2125,9 @@ writer.uint32(/* id 12, wireType 2 =*/98).string(message.syntax); if (message.edition != null && Object.hasOwnProperty.call(message, "edition")) writer.uint32(/* id 14, wireType 0 =*/112).int32(message.edition); + if (message.optionDependency != null && message.optionDependency.length) + for (var i = 0; i < message.optionDependency.length; ++i) + writer.uint32(/* id 15, wireType 2 =*/122).string(message.optionDependency[i]); return writer; }; @@ -2185,6 +2200,12 @@ message.weakDependency.push(reader.int32()); break; } + case 15: { + if (!(message.optionDependency && message.optionDependency.length)) + message.optionDependency = []; + message.optionDependency.push(reader.string()); + break; + } case 4: { if (!(message.messageType && message.messageType.length)) message.messageType = []; @@ -2287,6 +2308,13 @@ if (!$util.isInteger(message.weakDependency[i])) return "weakDependency: integer[] expected"; } + if (message.optionDependency != null && message.hasOwnProperty("optionDependency")) { + if (!Array.isArray(message.optionDependency)) + return "optionDependency: array expected"; + for (var i = 0; i < message.optionDependency.length; ++i) + if (!$util.isString(message.optionDependency[i])) + return "optionDependency: string[] expected"; + } if (message.messageType != null && message.hasOwnProperty("messageType")) { if (!Array.isArray(message.messageType)) return "messageType: array expected"; @@ -2341,6 +2369,7 @@ default: return "edition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -2393,6 +2422,13 @@ for (var i = 0; i < object.weakDependency.length; ++i) message.weakDependency[i] = object.weakDependency[i] | 0; } + if (object.optionDependency) { + if (!Array.isArray(object.optionDependency)) + throw TypeError(".google.protobuf.FileDescriptorProto.optionDependency: array expected"); + message.optionDependency = []; + for (var i = 0; i < object.optionDependency.length; ++i) + message.optionDependency[i] = String(object.optionDependency[i]); + } if (object.messageType) { if (!Array.isArray(object.messageType)) throw TypeError(".google.protobuf.FileDescriptorProto.messageType: array expected"); @@ -2456,6 +2492,10 @@ case 0: message.edition = 0; break; + case "EDITION_LEGACY": + case 900: + message.edition = 900; + break; case "EDITION_PROTO2": case 998: message.edition = 998; @@ -2521,6 +2561,7 @@ object.extension = []; object.publicDependency = []; object.weakDependency = []; + object.optionDependency = []; } if (options.defaults) { object.name = ""; @@ -2577,6 +2618,11 @@ 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; + if (message.optionDependency && message.optionDependency.length) { + object.optionDependency = []; + for (var j = 0; j < message.optionDependency.length; ++j) + object.optionDependency[j] = message.optionDependency[j]; + } return object; }; @@ -2625,6 +2671,7 @@ * @property {google.protobuf.IMessageOptions|null} [options] DescriptorProto options * @property {Array.|null} [reservedRange] DescriptorProto reservedRange * @property {Array.|null} [reservedName] DescriptorProto reservedName + * @property {google.protobuf.SymbolVisibility|null} [visibility] DescriptorProto visibility */ /** @@ -2730,6 +2777,14 @@ */ DescriptorProto.prototype.reservedName = $util.emptyArray; + /** + * DescriptorProto visibility. + * @member {google.protobuf.SymbolVisibility} visibility + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.visibility = 0; + /** * Creates a new DescriptorProto instance using the specified properties. * @function create @@ -2782,6 +2837,8 @@ if (message.reservedName != null && message.reservedName.length) for (var i = 0; i < message.reservedName.length; ++i) writer.uint32(/* id 10, wireType 2 =*/82).string(message.reservedName[i]); + if (message.visibility != null && Object.hasOwnProperty.call(message, "visibility")) + writer.uint32(/* id 11, wireType 0 =*/88).int32(message.visibility); return writer; }; @@ -2874,6 +2931,10 @@ message.reservedName.push(reader.string()); break; } + case 11: { + message.visibility = reader.int32(); + break; + } default: reader.skipType(tag & 7); break; @@ -2987,6 +3048,15 @@ if (!$util.isString(message.reservedName[i])) return "reservedName: string[] expected"; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + switch (message.visibility) { + default: + return "visibility: enum value expected"; + case 0: + case 1: + case 2: + break; + } return null; }; @@ -3086,6 +3156,26 @@ for (var i = 0; i < object.reservedName.length; ++i) message.reservedName[i] = String(object.reservedName[i]); } + switch (object.visibility) { + default: + if (typeof object.visibility === "number") { + message.visibility = object.visibility; + break; + } + break; + case "VISIBILITY_UNSET": + case 0: + message.visibility = 0; + break; + case "VISIBILITY_LOCAL": + case 1: + message.visibility = 1; + break; + case "VISIBILITY_EXPORT": + case 2: + message.visibility = 2; + break; + } return message; }; @@ -3115,6 +3205,7 @@ if (options.defaults) { object.name = ""; object.options = null; + object.visibility = options.enums === String ? "VISIBILITY_UNSET" : 0; } if (message.name != null && message.hasOwnProperty("name")) object.name = message.name; @@ -3160,6 +3251,8 @@ for (var j = 0; j < message.reservedName.length; ++j) object.reservedName[j] = message.reservedName[j]; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + object.visibility = options.enums === String ? $root.google.protobuf.SymbolVisibility[message.visibility] === undefined ? message.visibility : $root.google.protobuf.SymbolVisibility[message.visibility] : message.visibility; return object; }; @@ -5204,6 +5297,7 @@ * @property {google.protobuf.IEnumOptions|null} [options] EnumDescriptorProto options * @property {Array.|null} [reservedRange] EnumDescriptorProto reservedRange * @property {Array.|null} [reservedName] EnumDescriptorProto reservedName + * @property {google.protobuf.SymbolVisibility|null} [visibility] EnumDescriptorProto visibility */ /** @@ -5264,6 +5358,14 @@ */ EnumDescriptorProto.prototype.reservedName = $util.emptyArray; + /** + * EnumDescriptorProto visibility. + * @member {google.protobuf.SymbolVisibility} visibility + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.visibility = 0; + /** * Creates a new EnumDescriptorProto instance using the specified properties. * @function create @@ -5301,6 +5403,8 @@ if (message.reservedName != null && message.reservedName.length) for (var i = 0; i < message.reservedName.length; ++i) writer.uint32(/* id 5, wireType 2 =*/42).string(message.reservedName[i]); + if (message.visibility != null && Object.hasOwnProperty.call(message, "visibility")) + writer.uint32(/* id 6, wireType 0 =*/48).int32(message.visibility); return writer; }; @@ -5363,6 +5467,10 @@ message.reservedName.push(reader.string()); break; } + case 6: { + message.visibility = reader.int32(); + break; + } default: reader.skipType(tag & 7); break; @@ -5431,6 +5539,15 @@ if (!$util.isString(message.reservedName[i])) return "reservedName: string[] expected"; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + switch (message.visibility) { + default: + return "visibility: enum value expected"; + case 0: + case 1: + case 2: + break; + } return null; }; @@ -5480,6 +5597,26 @@ for (var i = 0; i < object.reservedName.length; ++i) message.reservedName[i] = String(object.reservedName[i]); } + switch (object.visibility) { + default: + if (typeof object.visibility === "number") { + message.visibility = object.visibility; + break; + } + break; + case "VISIBILITY_UNSET": + case 0: + message.visibility = 0; + break; + case "VISIBILITY_LOCAL": + case 1: + message.visibility = 1; + break; + case "VISIBILITY_EXPORT": + case 2: + message.visibility = 2; + break; + } return message; }; @@ -5504,6 +5641,7 @@ if (options.defaults) { object.name = ""; object.options = null; + object.visibility = options.enums === String ? "VISIBILITY_UNSET" : 0; } if (message.name != null && message.hasOwnProperty("name")) object.name = message.name; @@ -5524,6 +5662,8 @@ for (var j = 0; j < message.reservedName.length; ++j) object.reservedName[j] = message.reservedName[j]; } + if (message.visibility != null && message.hasOwnProperty("visibility")) + object.visibility = options.enums === String ? $root.google.protobuf.SymbolVisibility[message.visibility] === undefined ? message.visibility : $root.google.protobuf.SymbolVisibility[message.visibility] : message.visibility; return object; }; @@ -7769,6 +7909,7 @@ * @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 */ @@ -7886,6 +8027,14 @@ */ 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 @@ -7944,6 +8093,8 @@ $root.google.protobuf.FieldOptions.EditionDefault.encode(message.editionDefaults[i], writer.uint32(/* id 20, wireType 2 =*/162).fork()).ldelim(); if (message.features != null && Object.hasOwnProperty.call(message, "features")) $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 21, wireType 2 =*/170).fork()).ldelim(); + if (message.featureSupport != null && Object.hasOwnProperty.call(message, "featureSupport")) + $root.google.protobuf.FieldOptions.FeatureSupport.encode(message.featureSupport, writer.uint32(/* id 22, wireType 2 =*/178).fork()).ldelim(); if (message.uninterpretedOption != null && message.uninterpretedOption.length) for (var i = 0; i < message.uninterpretedOption.length; ++i) $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); @@ -8040,6 +8191,10 @@ message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); break; } + case 22: { + message.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.decode(reader, reader.uint32()); + break; + } case 999: { if (!(message.uninterpretedOption && message.uninterpretedOption.length)) message.uninterpretedOption = []; @@ -8160,6 +8315,11 @@ if (error) return "features." + error; } + if (message.featureSupport != null && message.hasOwnProperty("featureSupport")) { + var error = $root.google.protobuf.FieldOptions.FeatureSupport.verify(message.featureSupport); + if (error) + return "featureSupport." + error; + } if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { if (!Array.isArray(message.uninterpretedOption)) return "uninterpretedOption: array expected"; @@ -8324,6 +8484,11 @@ 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"); @@ -8366,6 +8531,7 @@ object.debugRedact = false; object.retention = options.enums === String ? "RETENTION_UNKNOWN" : 0; object.features = null; + object.featureSupport = 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; @@ -8397,6 +8563,8 @@ } 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) @@ -8662,6 +8830,7 @@ default: return "edition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -8703,6 +8872,10 @@ case 0: message.edition = 0; break; + case "EDITION_LEGACY": + case 900: + message.edition = 900; + break; case "EDITION_PROTO2": case 998: message.edition = 998; @@ -8802,122 +8975,604 @@ return EditionDefault; })(); - return FieldOptions; - })(); + FieldOptions.FeatureSupport = (function() { - protobuf.OneofOptions = (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 OneofOptions. - * @memberof google.protobuf - * @interface IOneofOptions - * @property {google.protobuf.IFeatureSet|null} [features] OneofOptions features - * @property {Array.|null} [uninterpretedOption] OneofOptions uninterpretedOption - */ + /** + * 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]]; + } - /** - * 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]]; - } + /** + * FeatureSupport editionIntroduced. + * @member {google.protobuf.Edition} editionIntroduced + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @instance + */ + FeatureSupport.prototype.editionIntroduced = 0; - /** - * OneofOptions features. - * @member {google.protobuf.IFeatureSet|null|undefined} features - * @memberof google.protobuf.OneofOptions - * @instance - */ - OneofOptions.prototype.features = null; + /** + * FeatureSupport editionDeprecated. + * @member {google.protobuf.Edition} editionDeprecated + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @instance + */ + FeatureSupport.prototype.editionDeprecated = 0; - /** - * OneofOptions uninterpretedOption. - * @member {Array.} uninterpretedOption - * @memberof google.protobuf.OneofOptions - * @instance - */ - OneofOptions.prototype.uninterpretedOption = $util.emptyArray; + /** + * FeatureSupport deprecationWarning. + * @member {string} deprecationWarning + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @instance + */ + FeatureSupport.prototype.deprecationWarning = ""; - /** - * Creates a new OneofOptions instance using the specified properties. - * @function create - * @memberof google.protobuf.OneofOptions - * @static - * @param {google.protobuf.IOneofOptions=} [properties] Properties to set - * @returns {google.protobuf.OneofOptions} OneofOptions instance - */ - OneofOptions.create = function create(properties) { - return new OneofOptions(properties); - }; + /** + * FeatureSupport editionRemoved. + * @member {google.protobuf.Edition} editionRemoved + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @instance + */ + FeatureSupport.prototype.editionRemoved = 0; - /** - * Encodes the specified OneofOptions message. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. - * @function encode - * @memberof google.protobuf.OneofOptions - * @static - * @param {google.protobuf.IOneofOptions} message OneofOptions message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - OneofOptions.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.features != null && Object.hasOwnProperty.call(message, "features")) - $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - if (message.uninterpretedOption != null && message.uninterpretedOption.length) - for (var i = 0; i < message.uninterpretedOption.length; ++i) - $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); - return writer; - }; + /** + * Creates a new FeatureSupport instance using the specified properties. + * @function create + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport=} [properties] Properties to set + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport instance + */ + FeatureSupport.create = function create(properties) { + return new FeatureSupport(properties); + }; - /** - * Encodes the specified OneofOptions message, length delimited. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. - * @function encodeDelimited - * @memberof google.protobuf.OneofOptions - * @static - * @param {google.protobuf.IOneofOptions} message OneofOptions message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - OneofOptions.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + /** + * Encodes the specified FeatureSupport message. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport} message FeatureSupport message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FeatureSupport.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.editionIntroduced != null && Object.hasOwnProperty.call(message, "editionIntroduced")) + writer.uint32(/* id 1, wireType 0 =*/8).int32(message.editionIntroduced); + if (message.editionDeprecated != null && Object.hasOwnProperty.call(message, "editionDeprecated")) + writer.uint32(/* id 2, wireType 0 =*/16).int32(message.editionDeprecated); + if (message.deprecationWarning != null && Object.hasOwnProperty.call(message, "deprecationWarning")) + writer.uint32(/* id 3, wireType 2 =*/26).string(message.deprecationWarning); + if (message.editionRemoved != null && Object.hasOwnProperty.call(message, "editionRemoved")) + writer.uint32(/* id 4, wireType 0 =*/32).int32(message.editionRemoved); + return writer; + }; - /** - * Decodes an OneofOptions message from the specified reader or buffer. - * @function decode - * @memberof google.protobuf.OneofOptions - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {google.protobuf.OneofOptions} OneofOptions - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - OneofOptions.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.OneofOptions(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + /** + * Encodes the specified FeatureSupport message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {google.protobuf.FieldOptions.IFeatureSupport} message FeatureSupport message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + FeatureSupport.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FeatureSupport.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FieldOptions.FeatureSupport(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.editionIntroduced = reader.int32(); + break; + } + case 2: { + message.editionDeprecated = reader.int32(); + break; + } + case 3: { + message.deprecationWarning = reader.string(); + break; + } + case 4: { + message.editionRemoved = reader.int32(); + break; + } + default: + reader.skipType(tag & 7); break; } - case 999: { - if (!(message.uninterpretedOption && message.uninterpretedOption.length)) + } + return message; + }; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + FeatureSupport.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a FeatureSupport message. + * @function verify + * @memberof google.protobuf.FieldOptions.FeatureSupport + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + FeatureSupport.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.editionIntroduced != null && message.hasOwnProperty("editionIntroduced")) + switch (message.editionIntroduced) { + default: + return "editionIntroduced: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + if (message.editionDeprecated != null && message.hasOwnProperty("editionDeprecated")) + switch (message.editionDeprecated) { + default: + return "editionDeprecated: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + if (message.deprecationWarning != null && message.hasOwnProperty("deprecationWarning")) + if (!$util.isString(message.deprecationWarning)) + return "deprecationWarning: string expected"; + if (message.editionRemoved != null && message.hasOwnProperty("editionRemoved")) + switch (message.editionRemoved) { + default: + return "editionRemoved: enum value expected"; + case 0: + case 900: + case 998: + case 999: + case 1000: + case 1001: + case 1: + case 2: + case 99997: + case 99998: + case 99999: + case 2147483647: + break; + } + return null; + }; + + /** + * 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; + })(); + + 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 a new OneofOptions instance using the specified properties. + * @function create + * @memberof google.protobuf.OneofOptions + * @static + * @param {google.protobuf.IOneofOptions=} [properties] Properties to set + * @returns {google.protobuf.OneofOptions} OneofOptions instance + */ + OneofOptions.create = function create(properties) { + return new OneofOptions(properties); + }; + + /** + * Encodes the specified OneofOptions message. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. + * @function encode + * @memberof google.protobuf.OneofOptions + * @static + * @param {google.protobuf.IOneofOptions} message OneofOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + OneofOptions.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.features != null && Object.hasOwnProperty.call(message, "features")) + $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.uninterpretedOption != null && message.uninterpretedOption.length) + for (var i = 0; i < message.uninterpretedOption.length; ++i) + $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); + return writer; + }; + + /** + * Encodes the specified OneofOptions message, length delimited. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.OneofOptions + * @static + * @param {google.protobuf.IOneofOptions} message OneofOptions message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + OneofOptions.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an OneofOptions message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.OneofOptions + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.OneofOptions} OneofOptions + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + OneofOptions.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.OneofOptions(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + break; + } + case 999: { + if (!(message.uninterpretedOption && message.uninterpretedOption.length)) message.uninterpretedOption = []; message.uninterpretedOption.push($root.google.protobuf.UninterpretedOption.decode(reader, reader.uint32())); break; @@ -9394,6 +10049,7 @@ * @property {boolean|null} [deprecated] EnumValueOptions deprecated * @property {google.protobuf.IFeatureSet|null} [features] EnumValueOptions features * @property {boolean|null} [debugRedact] EnumValueOptions debugRedact + * @property {google.protobuf.FieldOptions.IFeatureSupport|null} [featureSupport] EnumValueOptions featureSupport * @property {Array.|null} [uninterpretedOption] EnumValueOptions uninterpretedOption */ @@ -9437,6 +10093,14 @@ */ EnumValueOptions.prototype.debugRedact = false; + /** + * EnumValueOptions featureSupport. + * @member {google.protobuf.FieldOptions.IFeatureSupport|null|undefined} featureSupport + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.featureSupport = null; + /** * EnumValueOptions uninterpretedOption. * @member {Array.} uninterpretedOption @@ -9475,6 +10139,8 @@ $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); if (message.debugRedact != null && Object.hasOwnProperty.call(message, "debugRedact")) writer.uint32(/* id 3, wireType 0 =*/24).bool(message.debugRedact); + if (message.featureSupport != null && Object.hasOwnProperty.call(message, "featureSupport")) + $root.google.protobuf.FieldOptions.FeatureSupport.encode(message.featureSupport, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); if (message.uninterpretedOption != null && message.uninterpretedOption.length) for (var i = 0; i < message.uninterpretedOption.length; ++i) $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); @@ -9526,6 +10192,10 @@ message.debugRedact = reader.bool(); break; } + case 4: { + message.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.decode(reader, reader.uint32()); + break; + } case 999: { if (!(message.uninterpretedOption && message.uninterpretedOption.length)) message.uninterpretedOption = []; @@ -9578,6 +10248,11 @@ if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) if (typeof message.debugRedact !== "boolean") return "debugRedact: boolean expected"; + if (message.featureSupport != null && message.hasOwnProperty("featureSupport")) { + var error = $root.google.protobuf.FieldOptions.FeatureSupport.verify(message.featureSupport); + if (error) + return "featureSupport." + error; + } if (message.uninterpretedOption != null && message.hasOwnProperty("uninterpretedOption")) { if (!Array.isArray(message.uninterpretedOption)) return "uninterpretedOption: array expected"; @@ -9611,6 +10286,11 @@ } if (object.debugRedact != null) message.debugRedact = Boolean(object.debugRedact); + if (object.featureSupport != null) { + if (typeof object.featureSupport !== "object") + throw TypeError(".google.protobuf.EnumValueOptions.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.EnumValueOptions.uninterpretedOption: array expected"); @@ -9643,6 +10323,7 @@ object.deprecated = false; object.features = null; object.debugRedact = false; + object.featureSupport = null; } if (message.deprecated != null && message.hasOwnProperty("deprecated")) object.deprecated = message.deprecated; @@ -9650,6 +10331,8 @@ object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) object.debugRedact = message.debugRedact; + 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) @@ -11089,6 +11772,8 @@ * @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 + * @property {google.protobuf.FeatureSet.EnforceNamingStyle|null} [enforceNamingStyle] FeatureSet enforceNamingStyle + * @property {google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|null} [defaultSymbolVisibility] FeatureSet defaultSymbolVisibility */ /** @@ -11154,6 +11839,22 @@ */ FeatureSet.prototype.jsonFormat = 0; + /** + * FeatureSet enforceNamingStyle. + * @member {google.protobuf.FeatureSet.EnforceNamingStyle} enforceNamingStyle + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.enforceNamingStyle = 0; + + /** + * FeatureSet defaultSymbolVisibility. + * @member {google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility} defaultSymbolVisibility + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.defaultSymbolVisibility = 0; + /** * Creates a new FeatureSet instance using the specified properties. * @function create @@ -11190,6 +11891,10 @@ writer.uint32(/* id 5, wireType 0 =*/40).int32(message.messageEncoding); if (message.jsonFormat != null && Object.hasOwnProperty.call(message, "jsonFormat")) writer.uint32(/* id 6, wireType 0 =*/48).int32(message.jsonFormat); + if (message.enforceNamingStyle != null && Object.hasOwnProperty.call(message, "enforceNamingStyle")) + writer.uint32(/* id 7, wireType 0 =*/56).int32(message.enforceNamingStyle); + if (message.defaultSymbolVisibility != null && Object.hasOwnProperty.call(message, "defaultSymbolVisibility")) + writer.uint32(/* id 8, wireType 0 =*/64).int32(message.defaultSymbolVisibility); return writer; }; @@ -11250,6 +11955,14 @@ message.jsonFormat = reader.int32(); break; } + case 7: { + message.enforceNamingStyle = reader.int32(); + break; + } + case 8: { + message.defaultSymbolVisibility = reader.int32(); + break; + } default: reader.skipType(tag & 7); break; @@ -11340,6 +12053,26 @@ case 2: break; } + if (message.enforceNamingStyle != null && message.hasOwnProperty("enforceNamingStyle")) + switch (message.enforceNamingStyle) { + default: + return "enforceNamingStyle: enum value expected"; + case 0: + case 1: + case 2: + break; + } + if (message.defaultSymbolVisibility != null && message.hasOwnProperty("defaultSymbolVisibility")) + switch (message.defaultSymbolVisibility) { + default: + return "defaultSymbolVisibility: enum value expected"; + case 0: + case 1: + case 2: + case 3: + case 4: + break; + } return null; }; @@ -11479,6 +12212,54 @@ message.jsonFormat = 2; break; } + switch (object.enforceNamingStyle) { + default: + if (typeof object.enforceNamingStyle === "number") { + message.enforceNamingStyle = object.enforceNamingStyle; + break; + } + break; + case "ENFORCE_NAMING_STYLE_UNKNOWN": + case 0: + message.enforceNamingStyle = 0; + break; + case "STYLE2024": + case 1: + message.enforceNamingStyle = 1; + break; + case "STYLE_LEGACY": + case 2: + message.enforceNamingStyle = 2; + break; + } + switch (object.defaultSymbolVisibility) { + default: + if (typeof object.defaultSymbolVisibility === "number") { + message.defaultSymbolVisibility = object.defaultSymbolVisibility; + break; + } + break; + case "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN": + case 0: + message.defaultSymbolVisibility = 0; + break; + case "EXPORT_ALL": + case 1: + message.defaultSymbolVisibility = 1; + break; + case "EXPORT_TOP_LEVEL": + case 2: + message.defaultSymbolVisibility = 2; + break; + case "LOCAL_ALL": + case 3: + message.defaultSymbolVisibility = 3; + break; + case "STRICT": + case 4: + message.defaultSymbolVisibility = 4; + break; + } return message; }; @@ -11502,6 +12283,8 @@ 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; + object.enforceNamingStyle = options.enums === String ? "ENFORCE_NAMING_STYLE_UNKNOWN" : 0; + object.defaultSymbolVisibility = options.enums === String ? "DEFAULT_SYMBOL_VISIBILITY_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; @@ -11515,6 +12298,10 @@ 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; + if (message.enforceNamingStyle != null && message.hasOwnProperty("enforceNamingStyle")) + object.enforceNamingStyle = options.enums === String ? $root.google.protobuf.FeatureSet.EnforceNamingStyle[message.enforceNamingStyle] === undefined ? message.enforceNamingStyle : $root.google.protobuf.FeatureSet.EnforceNamingStyle[message.enforceNamingStyle] : message.enforceNamingStyle; + if (message.defaultSymbolVisibility != null && message.hasOwnProperty("defaultSymbolVisibility")) + object.defaultSymbolVisibility = options.enums === String ? $root.google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility[message.defaultSymbolVisibility] === undefined ? message.defaultSymbolVisibility : $root.google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility[message.defaultSymbolVisibility] : message.defaultSymbolVisibility; return object; }; @@ -11594,52 +12381,265 @@ return values; })(); - /** - * Utf8Validation enum. - * @name google.protobuf.FeatureSet.Utf8Validation - * @enum {number} - * @property {number} UTF8_VALIDATION_UNKNOWN=0 UTF8_VALIDATION_UNKNOWN value - * @property {number} VERIFY=2 VERIFY value - * @property {number} NONE=3 NONE value - */ - FeatureSet.Utf8Validation = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "UTF8_VALIDATION_UNKNOWN"] = 0; - values[valuesById[2] = "VERIFY"] = 2; - values[valuesById[3] = "NONE"] = 3; - return values; - })(); + /** + * Utf8Validation enum. + * @name google.protobuf.FeatureSet.Utf8Validation + * @enum {number} + * @property {number} UTF8_VALIDATION_UNKNOWN=0 UTF8_VALIDATION_UNKNOWN value + * @property {number} VERIFY=2 VERIFY value + * @property {number} NONE=3 NONE value + */ + FeatureSet.Utf8Validation = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "UTF8_VALIDATION_UNKNOWN"] = 0; + values[valuesById[2] = "VERIFY"] = 2; + values[valuesById[3] = "NONE"] = 3; + return values; + })(); + + /** + * MessageEncoding enum. + * @name google.protobuf.FeatureSet.MessageEncoding + * @enum {number} + * @property {number} MESSAGE_ENCODING_UNKNOWN=0 MESSAGE_ENCODING_UNKNOWN value + * @property {number} LENGTH_PREFIXED=1 LENGTH_PREFIXED value + * @property {number} DELIMITED=2 DELIMITED value + */ + FeatureSet.MessageEncoding = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "MESSAGE_ENCODING_UNKNOWN"] = 0; + values[valuesById[1] = "LENGTH_PREFIXED"] = 1; + values[valuesById[2] = "DELIMITED"] = 2; + return values; + })(); + + /** + * JsonFormat enum. + * @name google.protobuf.FeatureSet.JsonFormat + * @enum {number} + * @property {number} JSON_FORMAT_UNKNOWN=0 JSON_FORMAT_UNKNOWN value + * @property {number} ALLOW=1 ALLOW value + * @property {number} LEGACY_BEST_EFFORT=2 LEGACY_BEST_EFFORT value + */ + FeatureSet.JsonFormat = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "JSON_FORMAT_UNKNOWN"] = 0; + values[valuesById[1] = "ALLOW"] = 1; + values[valuesById[2] = "LEGACY_BEST_EFFORT"] = 2; + return values; + })(); + + /** + * EnforceNamingStyle enum. + * @name google.protobuf.FeatureSet.EnforceNamingStyle + * @enum {number} + * @property {number} ENFORCE_NAMING_STYLE_UNKNOWN=0 ENFORCE_NAMING_STYLE_UNKNOWN value + * @property {number} STYLE2024=1 STYLE2024 value + * @property {number} STYLE_LEGACY=2 STYLE_LEGACY value + */ + FeatureSet.EnforceNamingStyle = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ENFORCE_NAMING_STYLE_UNKNOWN"] = 0; + values[valuesById[1] = "STYLE2024"] = 1; + values[valuesById[2] = "STYLE_LEGACY"] = 2; + return values; + })(); + + FeatureSet.VisibilityFeature = (function() { + + /** + * Properties of a VisibilityFeature. + * @memberof google.protobuf.FeatureSet + * @interface IVisibilityFeature + */ + + /** + * Constructs a new VisibilityFeature. + * @memberof google.protobuf.FeatureSet + * @classdesc Represents a VisibilityFeature. + * @implements IVisibilityFeature + * @constructor + * @param {google.protobuf.FeatureSet.IVisibilityFeature=} [properties] Properties to set + */ + function VisibilityFeature(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 new VisibilityFeature instance using the specified properties. + * @function create + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature=} [properties] Properties to set + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature instance + */ + VisibilityFeature.create = function create(properties) { + return new VisibilityFeature(properties); + }; + + /** + * Encodes the specified VisibilityFeature message. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @function encode + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature} message VisibilityFeature message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + VisibilityFeature.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + return writer; + }; + + /** + * Encodes the specified VisibilityFeature message, length delimited. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @function encodeDelimited + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.IVisibilityFeature} message VisibilityFeature message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + VisibilityFeature.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer. + * @function decode + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + VisibilityFeature.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.protobuf.FeatureSet.VisibilityFeature(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + VisibilityFeature.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a VisibilityFeature message. + * @function verify + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + VisibilityFeature.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + return null; + }; + + /** + * Creates a VisibilityFeature message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FeatureSet.VisibilityFeature} VisibilityFeature + */ + VisibilityFeature.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FeatureSet.VisibilityFeature) + return object; + return new $root.google.protobuf.FeatureSet.VisibilityFeature(); + }; + + /** + * Creates a plain object from a VisibilityFeature message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {google.protobuf.FeatureSet.VisibilityFeature} message VisibilityFeature + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + VisibilityFeature.toObject = function toObject() { + return {}; + }; + + /** + * Converts this VisibilityFeature to JSON. + * @function toJSON + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @instance + * @returns {Object.} JSON object + */ + VisibilityFeature.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for VisibilityFeature + * @function getTypeUrl + * @memberof google.protobuf.FeatureSet.VisibilityFeature + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + VisibilityFeature.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FeatureSet.VisibilityFeature"; + }; - /** - * MessageEncoding enum. - * @name google.protobuf.FeatureSet.MessageEncoding - * @enum {number} - * @property {number} MESSAGE_ENCODING_UNKNOWN=0 MESSAGE_ENCODING_UNKNOWN value - * @property {number} LENGTH_PREFIXED=1 LENGTH_PREFIXED value - * @property {number} DELIMITED=2 DELIMITED value - */ - FeatureSet.MessageEncoding = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "MESSAGE_ENCODING_UNKNOWN"] = 0; - values[valuesById[1] = "LENGTH_PREFIXED"] = 1; - values[valuesById[2] = "DELIMITED"] = 2; - return values; - })(); + /** + * DefaultSymbolVisibility enum. + * @name google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility + * @enum {number} + * @property {number} DEFAULT_SYMBOL_VISIBILITY_UNKNOWN=0 DEFAULT_SYMBOL_VISIBILITY_UNKNOWN value + * @property {number} EXPORT_ALL=1 EXPORT_ALL value + * @property {number} EXPORT_TOP_LEVEL=2 EXPORT_TOP_LEVEL value + * @property {number} LOCAL_ALL=3 LOCAL_ALL value + * @property {number} STRICT=4 STRICT value + */ + VisibilityFeature.DefaultSymbolVisibility = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN"] = 0; + values[valuesById[1] = "EXPORT_ALL"] = 1; + values[valuesById[2] = "EXPORT_TOP_LEVEL"] = 2; + values[valuesById[3] = "LOCAL_ALL"] = 3; + values[valuesById[4] = "STRICT"] = 4; + return values; + })(); - /** - * JsonFormat enum. - * @name google.protobuf.FeatureSet.JsonFormat - * @enum {number} - * @property {number} JSON_FORMAT_UNKNOWN=0 JSON_FORMAT_UNKNOWN value - * @property {number} ALLOW=1 ALLOW value - * @property {number} LEGACY_BEST_EFFORT=2 LEGACY_BEST_EFFORT value - */ - FeatureSet.JsonFormat = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "JSON_FORMAT_UNKNOWN"] = 0; - values[valuesById[1] = "ALLOW"] = 1; - values[valuesById[2] = "LEGACY_BEST_EFFORT"] = 2; - return values; + return VisibilityFeature; })(); return FeatureSet; @@ -11826,6 +12826,7 @@ default: return "minimumEdition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -11843,6 +12844,7 @@ default: return "maximumEdition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -11891,6 +12893,10 @@ case 0: message.minimumEdition = 0; break; + case "EDITION_LEGACY": + case 900: + message.minimumEdition = 900; + break; case "EDITION_PROTO2": case 998: message.minimumEdition = 998; @@ -11943,6 +12949,10 @@ case 0: message.maximumEdition = 0; break; + case "EDITION_LEGACY": + case 900: + message.maximumEdition = 900; + break; case "EDITION_PROTO2": case 998: message.maximumEdition = 998; @@ -12051,7 +13061,8 @@ * @memberof google.protobuf.FeatureSetDefaults * @interface IFeatureSetEditionDefault * @property {google.protobuf.Edition|null} [edition] FeatureSetEditionDefault edition - * @property {google.protobuf.IFeatureSet|null} [features] FeatureSetEditionDefault features + * @property {google.protobuf.IFeatureSet|null} [overridableFeatures] FeatureSetEditionDefault overridableFeatures + * @property {google.protobuf.IFeatureSet|null} [fixedFeatures] FeatureSetEditionDefault fixedFeatures */ /** @@ -12078,12 +13089,20 @@ FeatureSetEditionDefault.prototype.edition = 0; /** - * FeatureSetEditionDefault features. - * @member {google.protobuf.IFeatureSet|null|undefined} features + * 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 * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault * @instance */ - FeatureSetEditionDefault.prototype.features = null; + FeatureSetEditionDefault.prototype.fixedFeatures = null; /** * Creates a new FeatureSetEditionDefault instance using the specified properties. @@ -12109,10 +13128,12 @@ FeatureSetEditionDefault.encode = function encode(message, writer) { if (!writer) writer = $Writer.create(); - if (message.features != null && Object.hasOwnProperty.call(message, "features")) - $root.google.protobuf.FeatureSet.encode(message.features, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); if (message.edition != null && Object.hasOwnProperty.call(message, "edition")) writer.uint32(/* id 3, wireType 0 =*/24).int32(message.edition); + if (message.overridableFeatures != null && Object.hasOwnProperty.call(message, "overridableFeatures")) + $root.google.protobuf.FeatureSet.encode(message.overridableFeatures, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); + if (message.fixedFeatures != null && Object.hasOwnProperty.call(message, "fixedFeatures")) + $root.google.protobuf.FeatureSet.encode(message.fixedFeatures, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); return writer; }; @@ -12153,8 +13174,12 @@ message.edition = reader.int32(); break; } - case 2: { - message.features = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + case 4: { + message.overridableFeatures = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); + break; + } + case 5: { + message.fixedFeatures = $root.google.protobuf.FeatureSet.decode(reader, reader.uint32()); break; } default: @@ -12197,6 +13222,7 @@ default: return "edition: enum value expected"; case 0: + case 900: case 998: case 999: case 1000: @@ -12209,10 +13235,15 @@ case 2147483647: break; } - if (message.features != null && message.hasOwnProperty("features")) { - var error = $root.google.protobuf.FeatureSet.verify(message.features); + if (message.overridableFeatures != null && message.hasOwnProperty("overridableFeatures")) { + var error = $root.google.protobuf.FeatureSet.verify(message.overridableFeatures); if (error) - return "features." + error; + return "overridableFeatures." + error; + } + if (message.fixedFeatures != null && message.hasOwnProperty("fixedFeatures")) { + var error = $root.google.protobuf.FeatureSet.verify(message.fixedFeatures); + if (error) + return "fixedFeatures." + error; } return null; }; @@ -12240,6 +13271,10 @@ case 0: message.edition = 0; break; + case "EDITION_LEGACY": + case 900: + message.edition = 900; + break; case "EDITION_PROTO2": case 998: message.edition = 998; @@ -12281,10 +13316,15 @@ message.edition = 2147483647; break; } - 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); + 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); } return message; }; @@ -12303,13 +13343,16 @@ 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; }; @@ -13524,6 +14567,22 @@ return GeneratedCodeInfo; })(); + /** + * SymbolVisibility enum. + * @name google.protobuf.SymbolVisibility + * @enum {number} + * @property {number} VISIBILITY_UNSET=0 VISIBILITY_UNSET value + * @property {number} VISIBILITY_LOCAL=1 VISIBILITY_LOCAL value + * @property {number} VISIBILITY_EXPORT=2 VISIBILITY_EXPORT value + */ + protobuf.SymbolVisibility = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "VISIBILITY_UNSET"] = 0; + values[valuesById[1] = "VISIBILITY_LOCAL"] = 1; + values[valuesById[2] = "VISIBILITY_EXPORT"] = 2; + return values; + })(); + return protobuf; })(); @@ -26401,6 +27460,7 @@ * @interface ICommonLanguageSettings * @property {string|null} [referenceDocsUri] CommonLanguageSettings referenceDocsUri * @property {Array.|null} [destinations] CommonLanguageSettings destinations + * @property {google.api.ISelectiveGapicGeneration|null} [selectiveGapicGeneration] CommonLanguageSettings selectiveGapicGeneration */ /** @@ -26435,6 +27495,14 @@ */ 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 new CommonLanguageSettings instance using the specified properties. * @function create @@ -26467,6 +27535,8 @@ writer.int32(message.destinations[i]); writer.ldelim(); } + if (message.selectiveGapicGeneration != null && Object.hasOwnProperty.call(message, "selectiveGapicGeneration")) + $root.google.api.SelectiveGapicGeneration.encode(message.selectiveGapicGeneration, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); return writer; }; @@ -26518,6 +27588,10 @@ message.destinations.push(reader.int32()); break; } + case 3: { + message.selectiveGapicGeneration = $root.google.api.SelectiveGapicGeneration.decode(reader, reader.uint32()); + break; + } default: reader.skipType(tag & 7); break; @@ -26569,6 +27643,11 @@ break; } } + if (message.selectiveGapicGeneration != null && message.hasOwnProperty("selectiveGapicGeneration")) { + var error = $root.google.api.SelectiveGapicGeneration.verify(message.selectiveGapicGeneration); + if (error) + return "selectiveGapicGeneration." + error; + } return null; }; @@ -26611,6 +27690,11 @@ 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; }; @@ -26629,8 +27713,10 @@ 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) { @@ -26638,6 +27724,8 @@ 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; }; @@ -28460,6 +29548,7 @@ * @memberof google.api * @interface IPythonSettings * @property {google.api.ICommonLanguageSettings|null} [common] PythonSettings common + * @property {google.api.PythonSettings.IExperimentalFeatures|null} [experimentalFeatures] PythonSettings experimentalFeatures */ /** @@ -28485,6 +29574,14 @@ */ 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 new PythonSettings instance using the specified properties. * @function create @@ -28511,6 +29608,8 @@ writer = $Writer.create(); if (message.common != null && Object.hasOwnProperty.call(message, "common")) $root.google.api.CommonLanguageSettings.encode(message.common, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.experimentalFeatures != null && Object.hasOwnProperty.call(message, "experimentalFeatures")) + $root.google.api.PythonSettings.ExperimentalFeatures.encode(message.experimentalFeatures, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); return writer; }; @@ -28551,6 +29650,10 @@ message.common = $root.google.api.CommonLanguageSettings.decode(reader, reader.uint32()); break; } + case 2: { + message.experimentalFeatures = $root.google.api.PythonSettings.ExperimentalFeatures.decode(reader, reader.uint32()); + break; + } default: reader.skipType(tag & 7); break; @@ -28591,6 +29694,11 @@ if (error) return "common." + error; } + if (message.experimentalFeatures != null && message.hasOwnProperty("experimentalFeatures")) { + var error = $root.google.api.PythonSettings.ExperimentalFeatures.verify(message.experimentalFeatures); + if (error) + return "experimentalFeatures." + error; + } return null; }; @@ -28611,6 +29719,11 @@ 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; }; @@ -28627,38 +29740,294 @@ 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 - * @memberof google.api.PythonSettings - * @instance - * @returns {Object.} JSON object - */ - PythonSettings.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * 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); + }; + + /** + * 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"; + }; + + 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 + * @property {boolean|null} [unversionedPackageDisabled] ExperimentalFeatures unversionedPackageDisabled + */ + + /** + * 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; + + /** + * ExperimentalFeatures unversionedPackageDisabled. + * @member {boolean} unversionedPackageDisabled + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @instance + */ + ExperimentalFeatures.prototype.unversionedPackageDisabled = false; + + /** + * Creates a new ExperimentalFeatures instance using the specified properties. + * @function create + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures=} [properties] Properties to set + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures instance + */ + ExperimentalFeatures.create = function create(properties) { + return new ExperimentalFeatures(properties); + }; + + /** + * Encodes the specified ExperimentalFeatures message. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @function encode + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures} message ExperimentalFeatures message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExperimentalFeatures.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.restAsyncIoEnabled != null && Object.hasOwnProperty.call(message, "restAsyncIoEnabled")) + writer.uint32(/* id 1, wireType 0 =*/8).bool(message.restAsyncIoEnabled); + if (message.protobufPythonicTypesEnabled != null && Object.hasOwnProperty.call(message, "protobufPythonicTypesEnabled")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.protobufPythonicTypesEnabled); + if (message.unversionedPackageDisabled != null && Object.hasOwnProperty.call(message, "unversionedPackageDisabled")) + writer.uint32(/* id 3, wireType 0 =*/24).bool(message.unversionedPackageDisabled); + return writer; + }; + + /** + * Encodes the specified ExperimentalFeatures message, length delimited. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {google.api.PythonSettings.IExperimentalFeatures} message ExperimentalFeatures message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + ExperimentalFeatures.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer. + * @function decode + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExperimentalFeatures.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.PythonSettings.ExperimentalFeatures(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + message.restAsyncIoEnabled = reader.bool(); + break; + } + case 2: { + message.protobufPythonicTypesEnabled = reader.bool(); + break; + } + case 3: { + message.unversionedPackageDisabled = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + ExperimentalFeatures.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies an ExperimentalFeatures message. + * @function verify + * @memberof google.api.PythonSettings.ExperimentalFeatures + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + ExperimentalFeatures.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.restAsyncIoEnabled != null && message.hasOwnProperty("restAsyncIoEnabled")) + if (typeof message.restAsyncIoEnabled !== "boolean") + return "restAsyncIoEnabled: boolean expected"; + if (message.protobufPythonicTypesEnabled != null && message.hasOwnProperty("protobufPythonicTypesEnabled")) + if (typeof message.protobufPythonicTypesEnabled !== "boolean") + return "protobufPythonicTypesEnabled: boolean expected"; + if (message.unversionedPackageDisabled != null && message.hasOwnProperty("unversionedPackageDisabled")) + if (typeof message.unversionedPackageDisabled !== "boolean") + return "unversionedPackageDisabled: boolean expected"; + return null; + }; + + /** + * 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); + if (object.unversionedPackageDisabled != null) + message.unversionedPackageDisabled = Boolean(object.unversionedPackageDisabled); + 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; + object.unversionedPackageDisabled = false; + } + if (message.restAsyncIoEnabled != null && message.hasOwnProperty("restAsyncIoEnabled")) + object.restAsyncIoEnabled = message.restAsyncIoEnabled; + if (message.protobufPythonicTypesEnabled != null && message.hasOwnProperty("protobufPythonicTypesEnabled")) + object.protobufPythonicTypesEnabled = message.protobufPythonicTypesEnabled; + if (message.unversionedPackageDisabled != null && message.hasOwnProperty("unversionedPackageDisabled")) + object.unversionedPackageDisabled = message.unversionedPackageDisabled; + return object; + }; - /** - * 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"; - }; + /** + * 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; })(); @@ -29536,6 +30905,7 @@ * @memberof google.api * @interface IGoSettings * @property {google.api.ICommonLanguageSettings|null} [common] GoSettings common + * @property {Object.|null} [renamedServices] GoSettings renamedServices */ /** @@ -29547,6 +30917,7 @@ * @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) @@ -29561,6 +30932,14 @@ */ GoSettings.prototype.common = null; + /** + * GoSettings renamedServices. + * @member {Object.} renamedServices + * @memberof google.api.GoSettings + * @instance + */ + GoSettings.prototype.renamedServices = $util.emptyObject; + /** * Creates a new GoSettings instance using the specified properties. * @function create @@ -29587,6 +30966,9 @@ writer = $Writer.create(); if (message.common != null && Object.hasOwnProperty.call(message, "common")) $root.google.api.CommonLanguageSettings.encode(message.common, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); + if (message.renamedServices != null && Object.hasOwnProperty.call(message, "renamedServices")) + for (var keys = Object.keys(message.renamedServices), i = 0; i < keys.length; ++i) + writer.uint32(/* id 2, wireType 2 =*/18).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.renamedServices[keys[i]]).ldelim(); return writer; }; @@ -29617,7 +30999,7 @@ GoSettings.decode = function decode(reader, length, error) { if (!(reader instanceof $Reader)) reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.GoSettings(); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.GoSettings(), key, value; while (reader.pos < end) { var tag = reader.uint32(); if (tag === error) @@ -29627,6 +31009,29 @@ message.common = $root.google.api.CommonLanguageSettings.decode(reader, reader.uint32()); break; } + case 2: { + if (message.renamedServices === $util.emptyObject) + message.renamedServices = {}; + var end2 = reader.uint32() + reader.pos; + key = ""; + value = ""; + while (reader.pos < end2) { + var tag2 = reader.uint32(); + switch (tag2 >>> 3) { + case 1: + key = reader.string(); + break; + case 2: + value = reader.string(); + break; + default: + reader.skipType(tag2 & 7); + break; + } + } + message.renamedServices[key] = value; + break; + } default: reader.skipType(tag & 7); break; @@ -29667,6 +31072,14 @@ if (error) return "common." + error; } + if (message.renamedServices != null && message.hasOwnProperty("renamedServices")) { + if (!$util.isObject(message.renamedServices)) + return "renamedServices: object expected"; + var key = Object.keys(message.renamedServices); + for (var i = 0; i < key.length; ++i) + if (!$util.isString(message.renamedServices[key[i]])) + return "renamedServices: string{k:string} expected"; + } return null; }; @@ -29687,6 +31100,13 @@ 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; }; @@ -29703,10 +31123,18 @@ 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; }; @@ -30345,6 +31773,251 @@ 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 new SelectiveGapicGeneration instance using the specified properties. + * @function create + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration=} [properties] Properties to set + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration instance + */ + SelectiveGapicGeneration.create = function create(properties) { + return new SelectiveGapicGeneration(properties); + }; + + /** + * Encodes the specified SelectiveGapicGeneration message. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @function encode + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration} message SelectiveGapicGeneration message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SelectiveGapicGeneration.encode = function encode(message, writer) { + if (!writer) + writer = $Writer.create(); + if (message.methods != null && message.methods.length) + for (var i = 0; i < message.methods.length; ++i) + writer.uint32(/* id 1, wireType 2 =*/10).string(message.methods[i]); + if (message.generateOmittedAsInternal != null && Object.hasOwnProperty.call(message, "generateOmittedAsInternal")) + writer.uint32(/* id 2, wireType 0 =*/16).bool(message.generateOmittedAsInternal); + return writer; + }; + + /** + * Encodes the specified SelectiveGapicGeneration message, length delimited. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @function encodeDelimited + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {google.api.ISelectiveGapicGeneration} message SelectiveGapicGeneration message or plain object to encode + * @param {$protobuf.Writer} [writer] Writer to encode to + * @returns {$protobuf.Writer} Writer + */ + SelectiveGapicGeneration.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim(); + }; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer. + * @function decode + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Message length if known beforehand + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SelectiveGapicGeneration.decode = function decode(reader, length, error) { + if (!(reader instanceof $Reader)) + reader = $Reader.create(reader); + var end = length === undefined ? reader.len : reader.pos + length, message = new $root.google.api.SelectiveGapicGeneration(); + while (reader.pos < end) { + var tag = reader.uint32(); + if (tag === error) + break; + switch (tag >>> 3) { + case 1: { + if (!(message.methods && message.methods.length)) + message.methods = []; + message.methods.push(reader.string()); + break; + } + case 2: { + message.generateOmittedAsInternal = reader.bool(); + break; + } + default: + reader.skipType(tag & 7); + break; + } + } + return message; + }; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer, length delimited. + * @function decodeDelimited + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + SelectiveGapicGeneration.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) + reader = new $Reader(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies a SelectiveGapicGeneration message. + * @function verify + * @memberof google.api.SelectiveGapicGeneration + * @static + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + SelectiveGapicGeneration.verify = function verify(message) { + if (typeof message !== "object" || message === null) + return "object expected"; + if (message.methods != null && message.hasOwnProperty("methods")) { + if (!Array.isArray(message.methods)) + return "methods: array expected"; + for (var i = 0; i < message.methods.length; ++i) + if (!$util.isString(message.methods[i])) + return "methods: string[] expected"; + } + if (message.generateOmittedAsInternal != null && message.hasOwnProperty("generateOmittedAsInternal")) + if (typeof message.generateOmittedAsInternal !== "boolean") + return "generateOmittedAsInternal: boolean expected"; + return null; + }; + + /** + * 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 diff --git a/packages/google-api-servicecontrol/protos/protos.json b/packages/google-api-servicecontrol/protos/protos.json index 4aac46d5041b..e2d37d4da027 100644 --- a/packages/google-api-servicecontrol/protos/protos.json +++ b/packages/google-api-servicecontrol/protos/protos.json @@ -120,12 +120,19 @@ "type": "FileDescriptorProto", "id": 1 } - } + }, + "extensions": [ + [ + 536000000, + 536000000 + ] + ] }, "Edition": { "edition": "proto2", "values": { "EDITION_UNKNOWN": 0, + "EDITION_LEGACY": 900, "EDITION_PROTO2": 998, "EDITION_PROTO3": 999, "EDITION_2023": 1000, @@ -164,6 +171,11 @@ "type": "int32", "id": 11 }, + "optionDependency": { + "rule": "repeated", + "type": "string", + "id": 15 + }, "messageType": { "rule": "repeated", "type": "DescriptorProto", @@ -252,6 +264,10 @@ "rule": "repeated", "type": "string", "id": 10 + }, + "visibility": { + "type": "SymbolVisibility", + "id": 11 } }, "nested": { @@ -477,6 +493,10 @@ "rule": "repeated", "type": "string", "id": 5 + }, + "visibility": { + "type": "SymbolVisibility", + "id": 6 } }, "nested": { @@ -527,7 +547,14 @@ "type": "ServiceOptions", "id": 3 } - } + }, + "reserved": [ + [ + 4, + 4 + ], + "stream" + ] }, "MethodDescriptorProto": { "edition": "proto2", @@ -691,6 +718,7 @@ 42, 42 ], + "php_generic_services", [ 38, 38 @@ -826,7 +854,8 @@ "type": "bool", "id": 10, "options": { - "default": false + "default": false, + "deprecated": true } }, "debugRedact": { @@ -854,6 +883,10 @@ "type": "FeatureSet", "id": 21 }, + "featureSupport": { + "type": "FeatureSupport", + "id": 22 + }, "uninterpretedOption": { "rule": "repeated", "type": "UninterpretedOption", @@ -923,6 +956,26 @@ "id": 2 } } + }, + "FeatureSupport": { + "fields": { + "editionIntroduced": { + "type": "Edition", + "id": 1 + }, + "editionDeprecated": { + "type": "Edition", + "id": 2 + }, + "deprecationWarning": { + "type": "string", + "id": 3 + }, + "editionRemoved": { + "type": "Edition", + "id": 4 + } + } } } }, @@ -1011,6 +1064,10 @@ "default": false } }, + "featureSupport": { + "type": "FieldOptions.FeatureSupport", + "id": 4 + }, "uninterpretedOption": { "rule": "repeated", "type": "UninterpretedOption", @@ -1153,6 +1210,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_2023", "edition_defaults.value": "EXPLICIT" } @@ -1163,6 +1221,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "OPEN" } @@ -1173,6 +1232,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "PACKED" } @@ -1183,6 +1243,7 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "VERIFY" } @@ -1193,7 +1254,8 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", - "edition_defaults.edition": "EDITION_PROTO2", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_LEGACY", "edition_defaults.value": "LENGTH_PREFIXED" } }, @@ -1203,27 +1265,38 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "ALLOW" } + }, + "enforceNamingStyle": { + "type": "EnforceNamingStyle", + "id": 7, + "options": { + "retention": "RETENTION_SOURCE", + "targets": "TARGET_TYPE_METHOD", + "feature_support.edition_introduced": "EDITION_2024", + "edition_defaults.edition": "EDITION_2024", + "edition_defaults.value": "STYLE2024" + } + }, + "defaultSymbolVisibility": { + "type": "VisibilityFeature.DefaultSymbolVisibility", + "id": 8, + "options": { + "retention": "RETENTION_SOURCE", + "targets": "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2024", + "edition_defaults.edition": "EDITION_2024", + "edition_defaults.value": "EXPORT_TOP_LEVEL" + } } }, "extensions": [ [ 1000, - 1000 - ], - [ - 1001, - 1001 - ], - [ - 1002, - 1002 - ], - [ - 9990, - 9990 + 9994 ], [ 9995, @@ -1268,7 +1341,13 @@ "UTF8_VALIDATION_UNKNOWN": 0, "VERIFY": 2, "NONE": 3 - } + }, + "reserved": [ + [ + 1, + 1 + ] + ] }, "MessageEncoding": { "values": { @@ -1283,6 +1362,33 @@ "ALLOW": 1, "LEGACY_BEST_EFFORT": 2 } + }, + "EnforceNamingStyle": { + "values": { + "ENFORCE_NAMING_STYLE_UNKNOWN": 0, + "STYLE2024": 1, + "STYLE_LEGACY": 2 + } + }, + "VisibilityFeature": { + "fields": {}, + "reserved": [ + [ + 1, + 536870911 + ] + ], + "nested": { + "DefaultSymbolVisibility": { + "values": { + "DEFAULT_SYMBOL_VISIBILITY_UNKNOWN": 0, + "EXPORT_ALL": 1, + "EXPORT_TOP_LEVEL": 2, + "LOCAL_ALL": 3, + "STRICT": 4 + } + } + } } } }, @@ -1310,11 +1416,26 @@ "type": "Edition", "id": 3 }, - "features": { + "overridableFeatures": { "type": "FeatureSet", - "id": 2 + "id": 4 + }, + "fixedFeatures": { + "type": "FeatureSet", + "id": 5 } - } + }, + "reserved": [ + [ + 1, + 1 + ], + [ + 2, + 2 + ], + "features" + ] } } }, @@ -1327,6 +1448,12 @@ "id": 1 } }, + "extensions": [ + [ + 536000000, + 536000000 + ] + ], "nested": { "Location": { "fields": { @@ -1411,6 +1538,14 @@ } } } + }, + "SymbolVisibility": { + "edition": "proto2", + "values": { + "VISIBILITY_UNSET": 0, + "VISIBILITY_LOCAL": 1, + "VISIBILITY_EXPORT": 2 + } } } }, @@ -1420,8 +1555,7 @@ "java_multiple_files": true, "java_outer_classname": "LaunchStageProto", "java_package": "com.google.api", - "objc_class_prefix": "GAPI", - "cc_enable_arenas": true + "objc_class_prefix": "GAPI" }, "nested": { "servicecontrol": { @@ -2576,6 +2710,10 @@ "rule": "repeated", "type": "ClientLibraryDestination", "id": 2 + }, + "selectiveGapicGeneration": { + "type": "SelectiveGapicGeneration", + "id": 3 } } }, @@ -2716,6 +2854,28 @@ "common": { "type": "CommonLanguageSettings", "id": 1 + }, + "experimentalFeatures": { + "type": "ExperimentalFeatures", + "id": 2 + } + }, + "nested": { + "ExperimentalFeatures": { + "fields": { + "restAsyncIoEnabled": { + "type": "bool", + "id": 1 + }, + "protobufPythonicTypesEnabled": { + "type": "bool", + "id": 2 + }, + "unversionedPackageDisabled": { + "type": "bool", + "id": 3 + } + } } } }, @@ -2773,6 +2933,11 @@ "common": { "type": "CommonLanguageSettings", "id": 1 + }, + "renamedServices": { + "keyType": "string", + "type": "string", + "id": 2 } } }, @@ -2834,6 +2999,19 @@ "PACKAGE_MANAGER": 20 } }, + "SelectiveGapicGeneration": { + "fields": { + "methods": { + "rule": "repeated", + "type": "string", + "id": 1 + }, + "generateOmittedAsInternal": { + "type": "bool", + "id": 2 + } + } + }, "LaunchStage": { "values": { "LAUNCH_STAGE_UNSPECIFIED": 0, diff --git a/packages/google-api-servicecontrol/samples/generated/v1/snippet_metadata_google.api.servicecontrol.v1.json b/packages/google-api-servicecontrol/samples/generated/v1/snippet_metadata_google.api.servicecontrol.v1.json index 3349c4a831ef..20789d4ef637 100644 --- a/packages/google-api-servicecontrol/samples/generated/v1/snippet_metadata_google.api.servicecontrol.v1.json +++ b/packages/google-api-servicecontrol/samples/generated/v1/snippet_metadata_google.api.servicecontrol.v1.json @@ -1,7 +1,7 @@ { "clientLibrary": { "name": "nodejs-servicecontrol", - "version": "4.3.1", + "version": "0.1.0", "language": "TYPESCRIPT", "apis": [ { diff --git a/packages/google-api-servicecontrol/samples/generated/v2/snippet_metadata_google.api.servicecontrol.v2.json b/packages/google-api-servicecontrol/samples/generated/v2/snippet_metadata_google.api.servicecontrol.v2.json index c2a8ec0fa359..aef08a98593d 100644 --- a/packages/google-api-servicecontrol/samples/generated/v2/snippet_metadata_google.api.servicecontrol.v2.json +++ b/packages/google-api-servicecontrol/samples/generated/v2/snippet_metadata_google.api.servicecontrol.v2.json @@ -1,7 +1,7 @@ { "clientLibrary": { "name": "nodejs-servicecontrol", - "version": "4.3.1", + "version": "0.1.0", "language": "TYPESCRIPT", "apis": [ { diff --git a/packages/google-api-servicecontrol/src/v1/index.ts b/packages/google-api-servicecontrol/src/v1/index.ts index 02e6a37b6303..fda8001fde7f 100644 --- a/packages/google-api-servicecontrol/src/v1/index.ts +++ b/packages/google-api-servicecontrol/src/v1/index.ts @@ -16,5 +16,5 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {QuotaControllerClient} from './quota_controller_client'; -export {ServiceControllerClient} from './service_controller_client'; +export { QuotaControllerClient } from './quota_controller_client'; +export { ServiceControllerClient } from './service_controller_client'; diff --git a/packages/google-api-servicecontrol/src/v1/quota_controller_client.ts b/packages/google-api-servicecontrol/src/v1/quota_controller_client.ts index 2260694bfe15..9c15f0d6deab 100644 --- a/packages/google-api-servicecontrol/src/v1/quota_controller_client.ts +++ b/packages/google-api-servicecontrol/src/v1/quota_controller_client.ts @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +52,7 @@ export class QuotaControllerClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('service-control'); @@ -60,8 +65,8 @@ export class QuotaControllerClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - quotaControllerStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + quotaControllerStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of QuotaControllerClient. @@ -102,21 +107,42 @@ export class QuotaControllerClient { * const client = new QuotaControllerClient({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 QuotaControllerClient; - 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 = 'servicecontrol.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -141,7 +167,7 @@ export class QuotaControllerClient { 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; @@ -155,10 +181,7 @@ export class QuotaControllerClient { } // 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 { @@ -177,8 +200,11 @@ export class QuotaControllerClient { // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.api.servicecontrol.v1.QuotaController', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.api.servicecontrol.v1.QuotaController', + 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 @@ -209,36 +235,40 @@ export class QuotaControllerClient { // Put together the "service stub" for // google.api.servicecontrol.v1.QuotaController. this.quotaControllerStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.api.servicecontrol.v1.QuotaController') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.api.servicecontrol.v1.QuotaController', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.api.servicecontrol.v1.QuotaController, - 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 quotaControllerStubMethods = - ['allocateQuota']; + const quotaControllerStubMethods = ['allocateQuota']; for (const methodName of quotaControllerStubMethods) { const callPromise = this.quotaControllerStub.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 = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -253,8 +283,14 @@ export class QuotaControllerClient { * @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 'servicecontrol.googleapis.com'; } @@ -265,8 +301,14 @@ export class QuotaControllerClient { * @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 'servicecontrol.googleapis.com'; } @@ -299,7 +341,7 @@ export class QuotaControllerClient { static get scopes() { return [ 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/servicecontrol' + 'https://www.googleapis.com/auth/servicecontrol', ]; } @@ -309,8 +351,9 @@ export class QuotaControllerClient { * 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; @@ -321,121 +364,160 @@ export class QuotaControllerClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Attempts to allocate quota for the specified consumer. It should be called - * before the operation is executed. - * - * This method requires the `servicemanagement.services.quota` - * permission on the specified service. For more information, see - * [Cloud IAM](https://cloud.google.com/iam). - * - * **NOTE:** The client **must** fail-open on server errors `INTERNAL`, - * `UNKNOWN`, `DEADLINE_EXCEEDED`, and `UNAVAILABLE`. To ensure system - * reliability, the server may inject these errors to prohibit any hard - * dependency on the quota functionality. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.serviceName - * Name of the service as specified in the service configuration. For example, - * `"pubsub.googleapis.com"`. - * - * See {@link protos.google.api.Service|google.api.Service} for the definition of a service name. - * @param {google.api.servicecontrol.v1.QuotaOperation} request.allocateOperation - * Operation that describes the quota allocation. - * @param {string} request.serviceConfigId - * Specifies which version of service configuration should be used to process - * the request. If unspecified or no matching version can be found, the latest - * one will be used. - * @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.api.servicecontrol.v1.AllocateQuotaResponse|AllocateQuotaResponse}. - * 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/quota_controller.allocate_quota.js - * region_tag:servicecontrol_v1_generated_QuotaController_AllocateQuota_async - */ + /** + * Attempts to allocate quota for the specified consumer. It should be called + * before the operation is executed. + * + * This method requires the `servicemanagement.services.quota` + * permission on the specified service. For more information, see + * [Cloud IAM](https://cloud.google.com/iam). + * + * **NOTE:** The client **must** fail-open on server errors `INTERNAL`, + * `UNKNOWN`, `DEADLINE_EXCEEDED`, and `UNAVAILABLE`. To ensure system + * reliability, the server may inject these errors to prohibit any hard + * dependency on the quota functionality. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.serviceName + * Name of the service as specified in the service configuration. For example, + * `"pubsub.googleapis.com"`. + * + * See {@link protos.google.api.Service|google.api.Service} for the definition of a service name. + * @param {google.api.servicecontrol.v1.QuotaOperation} request.allocateOperation + * Operation that describes the quota allocation. + * @param {string} request.serviceConfigId + * Specifies which version of service configuration should be used to process + * the request. If unspecified or no matching version can be found, the latest + * one will be used. + * @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.api.servicecontrol.v1.AllocateQuotaResponse|AllocateQuotaResponse}. + * 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/quota_controller.allocate_quota.js + * region_tag:servicecontrol_v1_generated_QuotaController_AllocateQuota_async + */ allocateQuota( - request?: protos.google.api.servicecontrol.v1.IAllocateQuotaRequest, - options?: CallOptions): - Promise<[ - protos.google.api.servicecontrol.v1.IAllocateQuotaResponse, - protos.google.api.servicecontrol.v1.IAllocateQuotaRequest|undefined, {}|undefined - ]>; + request?: protos.google.api.servicecontrol.v1.IAllocateQuotaRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.servicecontrol.v1.IAllocateQuotaResponse, + protos.google.api.servicecontrol.v1.IAllocateQuotaRequest | undefined, + {} | undefined, + ] + >; allocateQuota( - request: protos.google.api.servicecontrol.v1.IAllocateQuotaRequest, - options: CallOptions, - callback: Callback< - protos.google.api.servicecontrol.v1.IAllocateQuotaResponse, - protos.google.api.servicecontrol.v1.IAllocateQuotaRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.servicecontrol.v1.IAllocateQuotaRequest, + options: CallOptions, + callback: Callback< + protos.google.api.servicecontrol.v1.IAllocateQuotaResponse, + | protos.google.api.servicecontrol.v1.IAllocateQuotaRequest + | null + | undefined, + {} | null | undefined + >, + ): void; allocateQuota( - request: protos.google.api.servicecontrol.v1.IAllocateQuotaRequest, - callback: Callback< - protos.google.api.servicecontrol.v1.IAllocateQuotaResponse, - protos.google.api.servicecontrol.v1.IAllocateQuotaRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.servicecontrol.v1.IAllocateQuotaRequest, + callback: Callback< + protos.google.api.servicecontrol.v1.IAllocateQuotaResponse, + | protos.google.api.servicecontrol.v1.IAllocateQuotaRequest + | null + | undefined, + {} | null | undefined + >, + ): void; allocateQuota( - request?: protos.google.api.servicecontrol.v1.IAllocateQuotaRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.api.servicecontrol.v1.IAllocateQuotaRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.servicecontrol.v1.IAllocateQuotaResponse, - protos.google.api.servicecontrol.v1.IAllocateQuotaRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.api.servicecontrol.v1.IAllocateQuotaResponse, - protos.google.api.servicecontrol.v1.IAllocateQuotaRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.servicecontrol.v1.IAllocateQuotaResponse, - protos.google.api.servicecontrol.v1.IAllocateQuotaRequest|undefined, {}|undefined - ]>|void { + | protos.google.api.servicecontrol.v1.IAllocateQuotaRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.servicecontrol.v1.IAllocateQuotaResponse, + | protos.google.api.servicecontrol.v1.IAllocateQuotaRequest + | null + | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.servicecontrol.v1.IAllocateQuotaResponse, + protos.google.api.servicecontrol.v1.IAllocateQuotaRequest | 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({ - 'service_name': request.serviceName ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + service_name: request.serviceName ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('allocateQuota request %j', request); - const wrappedCallback: Callback< - protos.google.api.servicecontrol.v1.IAllocateQuotaResponse, - protos.google.api.servicecontrol.v1.IAllocateQuotaRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.servicecontrol.v1.IAllocateQuotaResponse, + | protos.google.api.servicecontrol.v1.IAllocateQuotaRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('allocateQuota response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.allocateQuota(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.servicecontrol.v1.IAllocateQuotaResponse, - protos.google.api.servicecontrol.v1.IAllocateQuotaRequest|undefined, - {}|undefined - ]) => { - this._log.info('allocateQuota response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .allocateQuota(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.servicecontrol.v1.IAllocateQuotaResponse, + protos.google.api.servicecontrol.v1.IAllocateQuotaRequest | undefined, + {} | undefined, + ]) => { + this._log.info('allocateQuota response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** * Terminate the gRPC channel and close the client. * @@ -444,7 +526,7 @@ export class QuotaControllerClient { */ close(): Promise { if (this.quotaControllerStub && !this._terminated) { - return this.quotaControllerStub.then(stub => { + return this.quotaControllerStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -452,4 +534,4 @@ export class QuotaControllerClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-api-servicecontrol/src/v1/service_controller_client.ts b/packages/google-api-servicecontrol/src/v1/service_controller_client.ts index c59cc7de6be4..7b3fe05cc8e5 100644 --- a/packages/google-api-servicecontrol/src/v1/service_controller_client.ts +++ b/packages/google-api-servicecontrol/src/v1/service_controller_client.ts @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -47,7 +52,7 @@ export class ServiceControllerClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('service-control'); @@ -60,8 +65,8 @@ export class ServiceControllerClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - serviceControllerStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + serviceControllerStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ServiceControllerClient. @@ -102,21 +107,42 @@ export class ServiceControllerClient { * const client = new ServiceControllerClient({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 ServiceControllerClient; - 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 = 'servicecontrol.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -141,7 +167,7 @@ export class ServiceControllerClient { 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; @@ -155,10 +181,7 @@ export class ServiceControllerClient { } // 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 { @@ -177,8 +200,11 @@ export class ServiceControllerClient { // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.api.servicecontrol.v1.ServiceController', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.api.servicecontrol.v1.ServiceController', + 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 @@ -209,36 +235,40 @@ export class ServiceControllerClient { // Put together the "service stub" for // google.api.servicecontrol.v1.ServiceController. this.serviceControllerStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.api.servicecontrol.v1.ServiceController') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.api.servicecontrol.v1.ServiceController', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.api.servicecontrol.v1.ServiceController, - 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 serviceControllerStubMethods = - ['check', 'report']; + const serviceControllerStubMethods = ['check', 'report']; for (const methodName of serviceControllerStubMethods) { const callPromise = this.serviceControllerStub.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 = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -253,8 +283,14 @@ export class ServiceControllerClient { * @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 'servicecontrol.googleapis.com'; } @@ -265,8 +301,14 @@ export class ServiceControllerClient { * @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 'servicecontrol.googleapis.com'; } @@ -299,7 +341,7 @@ export class ServiceControllerClient { static get scopes() { return [ 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/servicecontrol' + 'https://www.googleapis.com/auth/servicecontrol', ]; } @@ -309,8 +351,9 @@ export class ServiceControllerClient { * 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; @@ -321,262 +364,321 @@ export class ServiceControllerClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Checks whether an operation on a service should be allowed to proceed - * based on the configuration of the service and related policies. It must be - * called before the operation is executed. - * - * If feasible, the client should cache the check results and reuse them for - * 60 seconds. In case of any server errors, the client should rely on the - * cached results for much longer time to avoid outage. - * WARNING: There is general 60s delay for the configuration and policy - * propagation, therefore callers MUST NOT depend on the `Check` method having - * the latest policy information. - * - * NOTE: the {@link protos.google.api.servicecontrol.v1.CheckRequest|CheckRequest} has - * the size limit (wire-format byte size) of 1MB. - * - * This method requires the `servicemanagement.services.check` permission - * on the specified service. For more information, see - * [Cloud IAM](https://cloud.google.com/iam). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.serviceName - * The service name as specified in its service configuration. For example, - * `"pubsub.googleapis.com"`. - * - * See - * [google.api.Service](https://cloud.google.com/service-management/reference/rpc/google.api#google.api.Service) - * for the definition of a service name. - * @param {google.api.servicecontrol.v1.Operation} request.operation - * The operation to be checked. - * @param {string} request.serviceConfigId - * Specifies which version of service configuration should be used to process - * the request. - * - * If unspecified or no matching version can be found, the - * latest one will be used. - * @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.api.servicecontrol.v1.CheckResponse|CheckResponse}. - * 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/service_controller.check.js - * region_tag:servicecontrol_v1_generated_ServiceController_Check_async - */ + /** + * Checks whether an operation on a service should be allowed to proceed + * based on the configuration of the service and related policies. It must be + * called before the operation is executed. + * + * If feasible, the client should cache the check results and reuse them for + * 60 seconds. In case of any server errors, the client should rely on the + * cached results for much longer time to avoid outage. + * WARNING: There is general 60s delay for the configuration and policy + * propagation, therefore callers MUST NOT depend on the `Check` method having + * the latest policy information. + * + * NOTE: the {@link protos.google.api.servicecontrol.v1.CheckRequest|CheckRequest} has + * the size limit (wire-format byte size) of 1MB. + * + * This method requires the `servicemanagement.services.check` permission + * on the specified service. For more information, see + * [Cloud IAM](https://cloud.google.com/iam). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.serviceName + * The service name as specified in its service configuration. For example, + * `"pubsub.googleapis.com"`. + * + * See + * [google.api.Service](https://cloud.google.com/service-management/reference/rpc/google.api#google.api.Service) + * for the definition of a service name. + * @param {google.api.servicecontrol.v1.Operation} request.operation + * The operation to be checked. + * @param {string} request.serviceConfigId + * Specifies which version of service configuration should be used to process + * the request. + * + * If unspecified or no matching version can be found, the + * latest one will be used. + * @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.api.servicecontrol.v1.CheckResponse|CheckResponse}. + * 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/service_controller.check.js + * region_tag:servicecontrol_v1_generated_ServiceController_Check_async + */ check( - request?: protos.google.api.servicecontrol.v1.ICheckRequest, - options?: CallOptions): - Promise<[ - protos.google.api.servicecontrol.v1.ICheckResponse, - protos.google.api.servicecontrol.v1.ICheckRequest|undefined, {}|undefined - ]>; + request?: protos.google.api.servicecontrol.v1.ICheckRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.servicecontrol.v1.ICheckResponse, + protos.google.api.servicecontrol.v1.ICheckRequest | undefined, + {} | undefined, + ] + >; check( - request: protos.google.api.servicecontrol.v1.ICheckRequest, - options: CallOptions, - callback: Callback< - protos.google.api.servicecontrol.v1.ICheckResponse, - protos.google.api.servicecontrol.v1.ICheckRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.servicecontrol.v1.ICheckRequest, + options: CallOptions, + callback: Callback< + protos.google.api.servicecontrol.v1.ICheckResponse, + protos.google.api.servicecontrol.v1.ICheckRequest | null | undefined, + {} | null | undefined + >, + ): void; check( - request: protos.google.api.servicecontrol.v1.ICheckRequest, - callback: Callback< - protos.google.api.servicecontrol.v1.ICheckResponse, - protos.google.api.servicecontrol.v1.ICheckRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.servicecontrol.v1.ICheckRequest, + callback: Callback< + protos.google.api.servicecontrol.v1.ICheckResponse, + protos.google.api.servicecontrol.v1.ICheckRequest | null | undefined, + {} | null | undefined + >, + ): void; check( - request?: protos.google.api.servicecontrol.v1.ICheckRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.api.servicecontrol.v1.ICheckResponse, - protos.google.api.servicecontrol.v1.ICheckRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.api.servicecontrol.v1.ICheckRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.servicecontrol.v1.ICheckResponse, - protos.google.api.servicecontrol.v1.ICheckRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.servicecontrol.v1.ICheckResponse, - protos.google.api.servicecontrol.v1.ICheckRequest|undefined, {}|undefined - ]>|void { + protos.google.api.servicecontrol.v1.ICheckRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.servicecontrol.v1.ICheckResponse, + protos.google.api.servicecontrol.v1.ICheckRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.servicecontrol.v1.ICheckResponse, + protos.google.api.servicecontrol.v1.ICheckRequest | 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({ - 'service_name': request.serviceName ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + service_name: request.serviceName ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('check request %j', request); - const wrappedCallback: Callback< - protos.google.api.servicecontrol.v1.ICheckResponse, - protos.google.api.servicecontrol.v1.ICheckRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.servicecontrol.v1.ICheckResponse, + protos.google.api.servicecontrol.v1.ICheckRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('check response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.check(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.servicecontrol.v1.ICheckResponse, - protos.google.api.servicecontrol.v1.ICheckRequest|undefined, - {}|undefined - ]) => { - this._log.info('check response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .check(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.servicecontrol.v1.ICheckResponse, + protos.google.api.servicecontrol.v1.ICheckRequest | undefined, + {} | undefined, + ]) => { + this._log.info('check response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * Reports operation results to Google Service Control, such as logs and - * metrics. It should be called after an operation is completed. - * - * If feasible, the client should aggregate reporting data for up to 5 - * seconds to reduce API traffic. Limiting aggregation to 5 seconds is to - * reduce data loss during client crashes. Clients should carefully choose - * the aggregation time window to avoid data loss risk more than 0.01% - * for business and compliance reasons. - * - * NOTE: the {@link protos.google.api.servicecontrol.v1.ReportRequest|ReportRequest} has - * the size limit (wire-format byte size) of 1MB. - * - * This method requires the `servicemanagement.services.report` permission - * on the specified service. For more information, see - * [Google Cloud IAM](https://cloud.google.com/iam). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.serviceName - * The service name as specified in its service configuration. For example, - * `"pubsub.googleapis.com"`. - * - * See - * [google.api.Service](https://cloud.google.com/service-management/reference/rpc/google.api#google.api.Service) - * for the definition of a service name. - * @param {number[]} request.operations - * Operations to be reported. - * - * Typically the service should report one operation per request. - * Putting multiple operations into a single request is allowed, but should - * be used only when multiple operations are natually available at the time - * of the report. - * - * There is no limit on the number of operations in the same ReportRequest, - * however the ReportRequest size should be no larger than 1MB. See - * {@link protos.google.api.servicecontrol.v1.ReportResponse.report_errors|ReportResponse.report_errors} - * for partial failure behavior. - * @param {string} request.serviceConfigId - * Specifies which version of service config should be used to process the - * request. - * - * If unspecified or no matching version can be found, the - * latest one will be used. - * @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.api.servicecontrol.v1.ReportResponse|ReportResponse}. - * 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/service_controller.report.js - * region_tag:servicecontrol_v1_generated_ServiceController_Report_async - */ + /** + * Reports operation results to Google Service Control, such as logs and + * metrics. It should be called after an operation is completed. + * + * If feasible, the client should aggregate reporting data for up to 5 + * seconds to reduce API traffic. Limiting aggregation to 5 seconds is to + * reduce data loss during client crashes. Clients should carefully choose + * the aggregation time window to avoid data loss risk more than 0.01% + * for business and compliance reasons. + * + * NOTE: the {@link protos.google.api.servicecontrol.v1.ReportRequest|ReportRequest} has + * the size limit (wire-format byte size) of 1MB. + * + * This method requires the `servicemanagement.services.report` permission + * on the specified service. For more information, see + * [Google Cloud IAM](https://cloud.google.com/iam). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.serviceName + * The service name as specified in its service configuration. For example, + * `"pubsub.googleapis.com"`. + * + * See + * [google.api.Service](https://cloud.google.com/service-management/reference/rpc/google.api#google.api.Service) + * for the definition of a service name. + * @param {number[]} request.operations + * Operations to be reported. + * + * Typically the service should report one operation per request. + * Putting multiple operations into a single request is allowed, but should + * be used only when multiple operations are natually available at the time + * of the report. + * + * There is no limit on the number of operations in the same ReportRequest, + * however the ReportRequest size should be no larger than 1MB. See + * {@link protos.google.api.servicecontrol.v1.ReportResponse.report_errors|ReportResponse.report_errors} + * for partial failure behavior. + * @param {string} request.serviceConfigId + * Specifies which version of service config should be used to process the + * request. + * + * If unspecified or no matching version can be found, the + * latest one will be used. + * @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.api.servicecontrol.v1.ReportResponse|ReportResponse}. + * 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/service_controller.report.js + * region_tag:servicecontrol_v1_generated_ServiceController_Report_async + */ report( - request?: protos.google.api.servicecontrol.v1.IReportRequest, - options?: CallOptions): - Promise<[ - protos.google.api.servicecontrol.v1.IReportResponse, - protos.google.api.servicecontrol.v1.IReportRequest|undefined, {}|undefined - ]>; + request?: protos.google.api.servicecontrol.v1.IReportRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.servicecontrol.v1.IReportResponse, + protos.google.api.servicecontrol.v1.IReportRequest | undefined, + {} | undefined, + ] + >; report( - request: protos.google.api.servicecontrol.v1.IReportRequest, - options: CallOptions, - callback: Callback< - protos.google.api.servicecontrol.v1.IReportResponse, - protos.google.api.servicecontrol.v1.IReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.servicecontrol.v1.IReportRequest, + options: CallOptions, + callback: Callback< + protos.google.api.servicecontrol.v1.IReportResponse, + protos.google.api.servicecontrol.v1.IReportRequest | null | undefined, + {} | null | undefined + >, + ): void; report( - request: protos.google.api.servicecontrol.v1.IReportRequest, - callback: Callback< - protos.google.api.servicecontrol.v1.IReportResponse, - protos.google.api.servicecontrol.v1.IReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.servicecontrol.v1.IReportRequest, + callback: Callback< + protos.google.api.servicecontrol.v1.IReportResponse, + protos.google.api.servicecontrol.v1.IReportRequest | null | undefined, + {} | null | undefined + >, + ): void; report( - request?: protos.google.api.servicecontrol.v1.IReportRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.api.servicecontrol.v1.IReportResponse, - protos.google.api.servicecontrol.v1.IReportRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.api.servicecontrol.v1.IReportRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.servicecontrol.v1.IReportResponse, - protos.google.api.servicecontrol.v1.IReportRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.servicecontrol.v1.IReportResponse, - protos.google.api.servicecontrol.v1.IReportRequest|undefined, {}|undefined - ]>|void { + protos.google.api.servicecontrol.v1.IReportRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.servicecontrol.v1.IReportResponse, + protos.google.api.servicecontrol.v1.IReportRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.servicecontrol.v1.IReportResponse, + protos.google.api.servicecontrol.v1.IReportRequest | 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({ - 'service_name': request.serviceName ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + service_name: request.serviceName ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('report request %j', request); - const wrappedCallback: Callback< - protos.google.api.servicecontrol.v1.IReportResponse, - protos.google.api.servicecontrol.v1.IReportRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.servicecontrol.v1.IReportResponse, + protos.google.api.servicecontrol.v1.IReportRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('report response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.report(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.servicecontrol.v1.IReportResponse, - protos.google.api.servicecontrol.v1.IReportRequest|undefined, - {}|undefined - ]) => { - this._log.info('report response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .report(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.servicecontrol.v1.IReportResponse, + protos.google.api.servicecontrol.v1.IReportRequest | undefined, + {} | undefined, + ]) => { + this._log.info('report response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** * Terminate the gRPC channel and close the client. * @@ -585,7 +687,7 @@ export class ServiceControllerClient { */ close(): Promise { if (this.serviceControllerStub && !this._terminated) { - return this.serviceControllerStub.then(stub => { + return this.serviceControllerStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -593,4 +695,4 @@ export class ServiceControllerClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-api-servicecontrol/src/v2/index.ts b/packages/google-api-servicecontrol/src/v2/index.ts index 6bc09afc5dca..802411162e1d 100644 --- a/packages/google-api-servicecontrol/src/v2/index.ts +++ b/packages/google-api-servicecontrol/src/v2/index.ts @@ -16,4 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {ServiceControllerClient} from './service_controller_client'; +export { ServiceControllerClient } from './service_controller_client'; diff --git a/packages/google-api-servicecontrol/src/v2/service_controller_client.ts b/packages/google-api-servicecontrol/src/v2/service_controller_client.ts index 21d957276c94..daf7ffc14b91 100644 --- a/packages/google-api-servicecontrol/src/v2/service_controller_client.ts +++ b/packages/google-api-servicecontrol/src/v2/service_controller_client.ts @@ -18,11 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, +} from 'google-gax'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); -import {loggingUtils as logging, decodeAnyProtosInArray} from 'google-gax'; +import { loggingUtils as logging, decodeAnyProtosInArray } from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -49,7 +54,7 @@ export class ServiceControllerClient { private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; - private _defaults: {[method: string]: gax.CallSettings}; + private _defaults: { [method: string]: gax.CallSettings }; private _universeDomain: string; private _servicePath: string; private _log = logging.log('servicecontrol'); @@ -62,8 +67,8 @@ export class ServiceControllerClient { batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; - innerApiCalls: {[name: string]: Function}; - serviceControllerStub?: Promise<{[name: string]: Function}>; + innerApiCalls: { [name: string]: Function }; + serviceControllerStub?: Promise<{ [name: string]: Function }>; /** * Construct an instance of ServiceControllerClient. @@ -104,21 +109,42 @@ export class ServiceControllerClient { * const client = new ServiceControllerClient({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 ServiceControllerClient; - 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 = 'servicecontrol.' + 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'); - opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); + 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; @@ -143,7 +169,7 @@ export class ServiceControllerClient { 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; @@ -157,10 +183,7 @@ export class ServiceControllerClient { } // 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 { @@ -179,8 +202,11 @@ export class ServiceControllerClient { // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.api.servicecontrol.v2.ServiceController', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.api.servicecontrol.v2.ServiceController', + 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 @@ -211,36 +237,40 @@ export class ServiceControllerClient { // Put together the "service stub" for // google.api.servicecontrol.v2.ServiceController. this.serviceControllerStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.api.servicecontrol.v2.ServiceController') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.api.servicecontrol.v2.ServiceController', + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.api.servicecontrol.v2.ServiceController, - 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 serviceControllerStubMethods = - ['check', 'report']; + const serviceControllerStubMethods = ['check', 'report']; for (const methodName of serviceControllerStubMethods) { const callPromise = this.serviceControllerStub.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 = - undefined; + const descriptor = undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor, - this._opts.fallback + this._opts.fallback, ); this.innerApiCalls[methodName] = apiCall; @@ -255,8 +285,14 @@ export class ServiceControllerClient { * @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 'servicecontrol.googleapis.com'; } @@ -267,8 +303,14 @@ export class ServiceControllerClient { * @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 'servicecontrol.googleapis.com'; } @@ -301,7 +343,7 @@ export class ServiceControllerClient { static get scopes() { return [ 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/servicecontrol' + 'https://www.googleapis.com/auth/servicecontrol', ]; } @@ -311,8 +353,9 @@ export class ServiceControllerClient { * 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; @@ -323,257 +366,316 @@ export class ServiceControllerClient { // ------------------- // -- Service calls -- // ------------------- -/** - * This method provides admission control for services that are integrated - * with [Service - * Infrastructure](https://cloud.google.com/service-infrastructure). It checks - * whether an operation should be allowed based on the service configuration - * and relevant policies. It must be called before the operation is executed. - * For more information, see - * [Admission - * Control](https://cloud.google.com/service-infrastructure/docs/admission-control). - * - * NOTE: The admission control has an expected policy propagation delay of - * 60s. The caller **must** not depend on the most recent policy changes. - * - * NOTE: The admission control has a hard limit of 1 referenced resources - * per call. If an operation refers to more than 1 resources, the caller - * must call the Check method multiple times. - * - * This method requires the `servicemanagement.services.check` permission - * on the specified service. For more information, see - * [Service Control API Access - * Control](https://cloud.google.com/service-infrastructure/docs/service-control/access-control). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.serviceName - * The service name as specified in its service configuration. For example, - * `"pubsub.googleapis.com"`. - * - * See - * [google.api.Service](https://cloud.google.com/service-management/reference/rpc/google.api#google.api.Service) - * for the definition of a service name. - * @param {string} request.serviceConfigId - * Specifies the version of the service configuration that should be used to - * process the request. Must not be empty. Set this field to 'latest' to - * specify using the latest configuration. - * @param {google.rpc.context.AttributeContext} request.attributes - * Describes attributes about the operation being executed by the service. - * @param {number[]} request.resources - * Describes the resources and the policies applied to each resource. - * @param {string} request.flags - * Optional. Contains a comma-separated list of flags. - * @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.api.servicecontrol.v2.CheckResponse|CheckResponse}. - * 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/v2/service_controller.check.js - * region_tag:servicecontrol_v2_generated_ServiceController_Check_async - */ + /** + * This method provides admission control for services that are integrated + * with [Service + * Infrastructure](https://cloud.google.com/service-infrastructure). It checks + * whether an operation should be allowed based on the service configuration + * and relevant policies. It must be called before the operation is executed. + * For more information, see + * [Admission + * Control](https://cloud.google.com/service-infrastructure/docs/admission-control). + * + * NOTE: The admission control has an expected policy propagation delay of + * 60s. The caller **must** not depend on the most recent policy changes. + * + * NOTE: The admission control has a hard limit of 1 referenced resources + * per call. If an operation refers to more than 1 resources, the caller + * must call the Check method multiple times. + * + * This method requires the `servicemanagement.services.check` permission + * on the specified service. For more information, see + * [Service Control API Access + * Control](https://cloud.google.com/service-infrastructure/docs/service-control/access-control). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.serviceName + * The service name as specified in its service configuration. For example, + * `"pubsub.googleapis.com"`. + * + * See + * [google.api.Service](https://cloud.google.com/service-management/reference/rpc/google.api#google.api.Service) + * for the definition of a service name. + * @param {string} request.serviceConfigId + * Specifies the version of the service configuration that should be used to + * process the request. Must not be empty. Set this field to 'latest' to + * specify using the latest configuration. + * @param {google.rpc.context.AttributeContext} request.attributes + * Describes attributes about the operation being executed by the service. + * @param {number[]} request.resources + * Describes the resources and the policies applied to each resource. + * @param {string} request.flags + * Optional. Contains a comma-separated list of flags. + * @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.api.servicecontrol.v2.CheckResponse|CheckResponse}. + * 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/v2/service_controller.check.js + * region_tag:servicecontrol_v2_generated_ServiceController_Check_async + */ check( - request?: protos.google.api.servicecontrol.v2.ICheckRequest, - options?: CallOptions): - Promise<[ - protos.google.api.servicecontrol.v2.ICheckResponse, - protos.google.api.servicecontrol.v2.ICheckRequest|undefined, {}|undefined - ]>; + request?: protos.google.api.servicecontrol.v2.ICheckRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.servicecontrol.v2.ICheckResponse, + protos.google.api.servicecontrol.v2.ICheckRequest | undefined, + {} | undefined, + ] + >; check( - request: protos.google.api.servicecontrol.v2.ICheckRequest, - options: CallOptions, - callback: Callback< - protos.google.api.servicecontrol.v2.ICheckResponse, - protos.google.api.servicecontrol.v2.ICheckRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.servicecontrol.v2.ICheckRequest, + options: CallOptions, + callback: Callback< + protos.google.api.servicecontrol.v2.ICheckResponse, + protos.google.api.servicecontrol.v2.ICheckRequest | null | undefined, + {} | null | undefined + >, + ): void; check( - request: protos.google.api.servicecontrol.v2.ICheckRequest, - callback: Callback< - protos.google.api.servicecontrol.v2.ICheckResponse, - protos.google.api.servicecontrol.v2.ICheckRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.servicecontrol.v2.ICheckRequest, + callback: Callback< + protos.google.api.servicecontrol.v2.ICheckResponse, + protos.google.api.servicecontrol.v2.ICheckRequest | null | undefined, + {} | null | undefined + >, + ): void; check( - request?: protos.google.api.servicecontrol.v2.ICheckRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.api.servicecontrol.v2.ICheckResponse, - protos.google.api.servicecontrol.v2.ICheckRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.api.servicecontrol.v2.ICheckRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.servicecontrol.v2.ICheckResponse, - protos.google.api.servicecontrol.v2.ICheckRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.servicecontrol.v2.ICheckResponse, - protos.google.api.servicecontrol.v2.ICheckRequest|undefined, {}|undefined - ]>|void { + protos.google.api.servicecontrol.v2.ICheckRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.servicecontrol.v2.ICheckResponse, + protos.google.api.servicecontrol.v2.ICheckRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.servicecontrol.v2.ICheckResponse, + protos.google.api.servicecontrol.v2.ICheckRequest | 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({ - 'service_name': request.serviceName ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + service_name: request.serviceName ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('check request %j', request); - const wrappedCallback: Callback< - protos.google.api.servicecontrol.v2.ICheckResponse, - protos.google.api.servicecontrol.v2.ICheckRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.servicecontrol.v2.ICheckResponse, + protos.google.api.servicecontrol.v2.ICheckRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('check response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.check(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.servicecontrol.v2.ICheckResponse, - protos.google.api.servicecontrol.v2.ICheckRequest|undefined, - {}|undefined - ]) => { - this._log.info('check response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .check(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.servicecontrol.v2.ICheckResponse, + protos.google.api.servicecontrol.v2.ICheckRequest | undefined, + {} | undefined, + ]) => { + this._log.info('check response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } -/** - * This method provides telemetry reporting for services that are integrated - * with [Service - * Infrastructure](https://cloud.google.com/service-infrastructure). It - * reports a list of operations that have occurred on a service. It must be - * called after the operations have been executed. For more information, see - * [Telemetry - * Reporting](https://cloud.google.com/service-infrastructure/docs/telemetry-reporting). - * - * NOTE: The telemetry reporting has a hard limit of 100 operations and 1MB - * per Report call. - * - * This method requires the `servicemanagement.services.report` permission - * on the specified service. For more information, see - * [Service Control API Access - * Control](https://cloud.google.com/service-infrastructure/docs/service-control/access-control). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.serviceName - * The service name as specified in its service configuration. For example, - * `"pubsub.googleapis.com"`. - * - * See - * [google.api.Service](https://cloud.google.com/service-management/reference/rpc/google.api#google.api.Service) - * for the definition of a service name. - * @param {string} request.serviceConfigId - * Specifies the version of the service configuration that should be used to - * process the request. Must not be empty. Set this field to 'latest' to - * specify using the latest configuration. - * @param {number[]} request.operations - * Describes the list of operations to be reported. Each operation is - * represented as an AttributeContext, and contains all attributes around an - * API access. - * @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.api.servicecontrol.v2.ReportResponse|ReportResponse}. - * 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/v2/service_controller.report.js - * region_tag:servicecontrol_v2_generated_ServiceController_Report_async - */ + /** + * This method provides telemetry reporting for services that are integrated + * with [Service + * Infrastructure](https://cloud.google.com/service-infrastructure). It + * reports a list of operations that have occurred on a service. It must be + * called after the operations have been executed. For more information, see + * [Telemetry + * Reporting](https://cloud.google.com/service-infrastructure/docs/telemetry-reporting). + * + * NOTE: The telemetry reporting has a hard limit of 100 operations and 1MB + * per Report call. + * + * This method requires the `servicemanagement.services.report` permission + * on the specified service. For more information, see + * [Service Control API Access + * Control](https://cloud.google.com/service-infrastructure/docs/service-control/access-control). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.serviceName + * The service name as specified in its service configuration. For example, + * `"pubsub.googleapis.com"`. + * + * See + * [google.api.Service](https://cloud.google.com/service-management/reference/rpc/google.api#google.api.Service) + * for the definition of a service name. + * @param {string} request.serviceConfigId + * Specifies the version of the service configuration that should be used to + * process the request. Must not be empty. Set this field to 'latest' to + * specify using the latest configuration. + * @param {number[]} request.operations + * Describes the list of operations to be reported. Each operation is + * represented as an AttributeContext, and contains all attributes around an + * API access. + * @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.api.servicecontrol.v2.ReportResponse|ReportResponse}. + * 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/v2/service_controller.report.js + * region_tag:servicecontrol_v2_generated_ServiceController_Report_async + */ report( - request?: protos.google.api.servicecontrol.v2.IReportRequest, - options?: CallOptions): - Promise<[ - protos.google.api.servicecontrol.v2.IReportResponse, - protos.google.api.servicecontrol.v2.IReportRequest|undefined, {}|undefined - ]>; + request?: protos.google.api.servicecontrol.v2.IReportRequest, + options?: CallOptions, + ): Promise< + [ + protos.google.api.servicecontrol.v2.IReportResponse, + protos.google.api.servicecontrol.v2.IReportRequest | undefined, + {} | undefined, + ] + >; report( - request: protos.google.api.servicecontrol.v2.IReportRequest, - options: CallOptions, - callback: Callback< - protos.google.api.servicecontrol.v2.IReportResponse, - protos.google.api.servicecontrol.v2.IReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.servicecontrol.v2.IReportRequest, + options: CallOptions, + callback: Callback< + protos.google.api.servicecontrol.v2.IReportResponse, + protos.google.api.servicecontrol.v2.IReportRequest | null | undefined, + {} | null | undefined + >, + ): void; report( - request: protos.google.api.servicecontrol.v2.IReportRequest, - callback: Callback< - protos.google.api.servicecontrol.v2.IReportResponse, - protos.google.api.servicecontrol.v2.IReportRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.api.servicecontrol.v2.IReportRequest, + callback: Callback< + protos.google.api.servicecontrol.v2.IReportResponse, + protos.google.api.servicecontrol.v2.IReportRequest | null | undefined, + {} | null | undefined + >, + ): void; report( - request?: protos.google.api.servicecontrol.v2.IReportRequest, - optionsOrCallback?: CallOptions|Callback< + request?: protos.google.api.servicecontrol.v2.IReportRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.api.servicecontrol.v2.IReportResponse, - protos.google.api.servicecontrol.v2.IReportRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< - protos.google.api.servicecontrol.v2.IReportResponse, - protos.google.api.servicecontrol.v2.IReportRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.api.servicecontrol.v2.IReportResponse, - protos.google.api.servicecontrol.v2.IReportRequest|undefined, {}|undefined - ]>|void { + protos.google.api.servicecontrol.v2.IReportRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.api.servicecontrol.v2.IReportResponse, + protos.google.api.servicecontrol.v2.IReportRequest | null | undefined, + {} | null | undefined + >, + ): Promise< + [ + protos.google.api.servicecontrol.v2.IReportResponse, + protos.google.api.servicecontrol.v2.IReportRequest | 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({ - 'service_name': request.serviceName ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + service_name: request.serviceName ?? '', + }); + this.initialize().catch((err) => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('report request %j', request); - const wrappedCallback: Callback< - protos.google.api.servicecontrol.v2.IReportResponse, - protos.google.api.servicecontrol.v2.IReportRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.api.servicecontrol.v2.IReportResponse, + protos.google.api.servicecontrol.v2.IReportRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('report response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.report(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.api.servicecontrol.v2.IReportResponse, - protos.google.api.servicecontrol.v2.IReportRequest|undefined, - {}|undefined - ]) => { - this._log.info('report response %j', response); - return [response, options, rawResponse]; - }).catch((error: any) => { - if (error && 'statusDetails' in error && error.statusDetails instanceof Array) { - const protos = this._gaxModule.protobuf.Root.fromJSON(jsonProtos) as unknown as gax.protobuf.Type; - error.statusDetails = decodeAnyProtosInArray(error.statusDetails, protos); + return this.innerApiCalls + .report(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.api.servicecontrol.v2.IReportResponse, + protos.google.api.servicecontrol.v2.IReportRequest | undefined, + {} | undefined, + ]) => { + this._log.info('report response %j', response); + return [response, options, rawResponse]; + }, + ) + .catch((error: any) => { + if ( + error && + 'statusDetails' in error && + error.statusDetails instanceof Array + ) { + const protos = this._gaxModule.protobuf.Root.fromJSON( + jsonProtos, + ) as unknown as gax.protobuf.Type; + error.statusDetails = decodeAnyProtosInArray( + error.statusDetails, + protos, + ); } throw error; }); } - /** * Terminate the gRPC channel and close the client. * @@ -582,7 +684,7 @@ export class ServiceControllerClient { */ close(): Promise { if (this.serviceControllerStub && !this._terminated) { - return this.serviceControllerStub.then(stub => { + return this.serviceControllerStub.then((stub) => { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); @@ -590,4 +692,4 @@ export class ServiceControllerClient { } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/packages/google-api-servicecontrol/system-test/fixtures/sample/src/index.ts b/packages/google-api-servicecontrol/system-test/fixtures/sample/src/index.ts index a8c21925a56a..5c794a884588 100644 --- a/packages/google-api-servicecontrol/system-test/fixtures/sample/src/index.ts +++ b/packages/google-api-servicecontrol/system-test/fixtures/sample/src/index.ts @@ -16,7 +16,10 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {QuotaControllerClient, ServiceControllerClient} from '@google-cloud/service-control'; +import { + QuotaControllerClient, + ServiceControllerClient, +} from '@google-cloud/service-control'; // check that the client class type name can be used function doStuffWithQuotaControllerClient(client: QuotaControllerClient) { diff --git a/packages/google-api-servicecontrol/system-test/install.ts b/packages/google-api-servicecontrol/system-test/install.ts index 394f3362d203..ccf167042d2e 100644 --- a/packages/google-api-servicecontrol/system-test/install.ts +++ b/packages/google-api-servicecontrol/system-test/install.ts @@ -16,34 +16,36 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('📦 pack-n-play test', () => { - - it('TypeScript code', async function() { + it('TypeScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'TypeScript user can use the type definitions', - ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() - } + ts: readFileSync( + './system-test/fixtures/sample/src/index.ts', + ).toString(), + }, }; await packNTest(options); }); - it('JavaScript code', async function() { + it('JavaScript code', async function () { this.timeout(300000); const options = { packageDir: process.cwd(), sample: { description: 'JavaScript user can use the library', - ts: readFileSync('./system-test/fixtures/sample/src/index.js').toString() - } + cjs: readFileSync( + './system-test/fixtures/sample/src/index.js', + ).toString(), + }, }; await packNTest(options); }); - }); diff --git a/packages/google-api-servicecontrol/test/gapic_quota_controller_v1.ts b/packages/google-api-servicecontrol/test/gapic_quota_controller_v1.ts index 665f7169fb42..f11058cb31aa 100644 --- a/packages/google-api-servicecontrol/test/gapic_quota_controller_v1.ts +++ b/packages/google-api-servicecontrol/test/gapic_quota_controller_v1.ts @@ -19,304 +19,373 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as quotacontrollerModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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); } describe('v1.QuotaControllerClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new quotacontrollerModule.v1.QuotaControllerClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'servicecontrol.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new quotacontrollerModule.v1.QuotaControllerClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new quotacontrollerModule.v1.QuotaControllerClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'servicecontrol.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 = quotacontrollerModule.v1.QuotaControllerClient.servicePath; - assert.strictEqual(servicePath, 'servicecontrol.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + it('has universeDomain', () => { + const client = new quotacontrollerModule.v1.QuotaControllerClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = quotacontrollerModule.v1.QuotaControllerClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'servicecontrol.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new quotacontrollerModule.v1.QuotaControllerClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'servicecontrol.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 = + quotacontrollerModule.v1.QuotaControllerClient.servicePath; + assert.strictEqual(servicePath, 'servicecontrol.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new quotacontrollerModule.v1.QuotaControllerClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'servicecontrol.example.com'); - }); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + quotacontrollerModule.v1.QuotaControllerClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'servicecontrol.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new quotacontrollerModule.v1.QuotaControllerClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'servicecontrol.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 quotacontrollerModule.v1.QuotaControllerClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'servicecontrol.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new quotacontrollerModule.v1.QuotaControllerClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'servicecontrol.example.com'); + }); - 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 quotacontrollerModule.v1.QuotaControllerClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'servicecontrol.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 quotacontrollerModule.v1.QuotaControllerClient({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 quotacontrollerModule.v1.QuotaControllerClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'servicecontrol.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = quotacontrollerModule.v1.QuotaControllerClient.port; - assert(port); - assert(typeof port === 'number'); + 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 quotacontrollerModule.v1.QuotaControllerClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'servicecontrol.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new quotacontrollerModule.v1.QuotaControllerClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new quotacontrollerModule.v1.QuotaControllerClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new quotacontrollerModule.v1.QuotaControllerClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = quotacontrollerModule.v1.QuotaControllerClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new quotacontrollerModule.v1.QuotaControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.quotaControllerStub, undefined); - await client.initialize(); - assert(client.quotaControllerStub); - }); + it('should create a client with no option', () => { + const client = new quotacontrollerModule.v1.QuotaControllerClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new quotacontrollerModule.v1.QuotaControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.quotaControllerStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new quotacontrollerModule.v1.QuotaControllerClient({ + fallback: true, + }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new quotacontrollerModule.v1.QuotaControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.quotaControllerStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new quotacontrollerModule.v1.QuotaControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.quotaControllerStub, undefined); + await client.initialize(); + assert(client.quotaControllerStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new quotacontrollerModule.v1.QuotaControllerClient({ - 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 close method for the initialized client', (done) => { + const client = new quotacontrollerModule.v1.QuotaControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.quotaControllerStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new quotacontrollerModule.v1.QuotaControllerClient({ - 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('has close method for the non-initialized client', (done) => { + const client = new quotacontrollerModule.v1.QuotaControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.quotaControllerStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('allocateQuota', () => { - it('invokes allocateQuota without error', async () => { - const client = new quotacontrollerModule.v1.QuotaControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.servicecontrol.v1.AllocateQuotaRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.servicecontrol.v1.AllocateQuotaRequest', ['serviceName']); - request.serviceName = defaultValue1; - const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.servicecontrol.v1.AllocateQuotaResponse() - ); - client.innerApiCalls.allocateQuota = stubSimpleCall(expectedResponse); - const [response] = await client.allocateQuota(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.allocateQuota as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.allocateQuota 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 quotacontrollerModule.v1.QuotaControllerClient({ + 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 allocateQuota without error using callback', async () => { - const client = new quotacontrollerModule.v1.QuotaControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.servicecontrol.v1.AllocateQuotaRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.servicecontrol.v1.AllocateQuotaRequest', ['serviceName']); - request.serviceName = defaultValue1; - const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.servicecontrol.v1.AllocateQuotaResponse() - ); - client.innerApiCalls.allocateQuota = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.allocateQuota( - request, - (err?: Error|null, result?: protos.google.api.servicecontrol.v1.IAllocateQuotaResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.allocateQuota as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.allocateQuota 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 quotacontrollerModule.v1.QuotaControllerClient({ + 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 allocateQuota with error', async () => { - const client = new quotacontrollerModule.v1.QuotaControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.servicecontrol.v1.AllocateQuotaRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.servicecontrol.v1.AllocateQuotaRequest', ['serviceName']); - request.serviceName = defaultValue1; - const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.allocateQuota = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.allocateQuota(request), expectedError); - const actualRequest = (client.innerApiCalls.allocateQuota as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.allocateQuota as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('allocateQuota', () => { + it('invokes allocateQuota without error', async () => { + const client = new quotacontrollerModule.v1.QuotaControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.servicecontrol.v1.AllocateQuotaRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.servicecontrol.v1.AllocateQuotaRequest', + ['serviceName'], + ); + request.serviceName = defaultValue1; + const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.servicecontrol.v1.AllocateQuotaResponse(), + ); + client.innerApiCalls.allocateQuota = stubSimpleCall(expectedResponse); + const [response] = await client.allocateQuota(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.allocateQuota as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.allocateQuota as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes allocateQuota with closed client', async () => { - const client = new quotacontrollerModule.v1.QuotaControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.servicecontrol.v1.AllocateQuotaRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.servicecontrol.v1.AllocateQuotaRequest', ['serviceName']); - request.serviceName = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.allocateQuota(request), expectedError); - }); + it('invokes allocateQuota without error using callback', async () => { + const client = new quotacontrollerModule.v1.QuotaControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.servicecontrol.v1.AllocateQuotaRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.servicecontrol.v1.AllocateQuotaRequest', + ['serviceName'], + ); + request.serviceName = defaultValue1; + const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.servicecontrol.v1.AllocateQuotaResponse(), + ); + client.innerApiCalls.allocateQuota = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.allocateQuota( + request, + ( + err?: Error | null, + result?: protos.google.api.servicecontrol.v1.IAllocateQuotaResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.allocateQuota as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.allocateQuota as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes allocateQuota with error', async () => { + const client = new quotacontrollerModule.v1.QuotaControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.servicecontrol.v1.AllocateQuotaRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.servicecontrol.v1.AllocateQuotaRequest', + ['serviceName'], + ); + request.serviceName = defaultValue1; + const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.allocateQuota = stubSimpleCall( + undefined, + expectedError, + ); + await assert.rejects(client.allocateQuota(request), expectedError); + const actualRequest = ( + client.innerApiCalls.allocateQuota as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.allocateQuota as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes allocateQuota with closed client', async () => { + const client = new quotacontrollerModule.v1.QuotaControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.servicecontrol.v1.AllocateQuotaRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.servicecontrol.v1.AllocateQuotaRequest', + ['serviceName'], + ); + request.serviceName = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.allocateQuota(request), expectedError); }); + }); }); diff --git a/packages/google-api-servicecontrol/test/gapic_service_controller_v1.ts b/packages/google-api-servicecontrol/test/gapic_service_controller_v1.ts index 9f5c777f8f57..ca0cf937e824 100644 --- a/packages/google-api-servicecontrol/test/gapic_service_controller_v1.ts +++ b/packages/google-api-servicecontrol/test/gapic_service_controller_v1.ts @@ -19,412 +19,496 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as servicecontrollerModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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); } describe('v1.ServiceControllerClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new servicecontrollerModule.v1.ServiceControllerClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'servicecontrol.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new servicecontrollerModule.v1.ServiceControllerClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new servicecontrollerModule.v1.ServiceControllerClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'servicecontrol.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 = servicecontrollerModule.v1.ServiceControllerClient.servicePath; - assert.strictEqual(servicePath, 'servicecontrol.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + it('has universeDomain', () => { + const client = new servicecontrollerModule.v1.ServiceControllerClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = servicecontrollerModule.v1.ServiceControllerClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'servicecontrol.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new servicecontrollerModule.v1.ServiceControllerClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'servicecontrol.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 = + servicecontrollerModule.v1.ServiceControllerClient.servicePath; + assert.strictEqual(servicePath, 'servicecontrol.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new servicecontrollerModule.v1.ServiceControllerClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'servicecontrol.example.com'); - }); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + servicecontrollerModule.v1.ServiceControllerClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'servicecontrol.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new servicecontrollerModule.v1.ServiceControllerClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'servicecontrol.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 servicecontrollerModule.v1.ServiceControllerClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'servicecontrol.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new servicecontrollerModule.v1.ServiceControllerClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'servicecontrol.example.com'); + }); - 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 servicecontrollerModule.v1.ServiceControllerClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'servicecontrol.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 servicecontrollerModule.v1.ServiceControllerClient({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 servicecontrollerModule.v1.ServiceControllerClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'servicecontrol.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = servicecontrollerModule.v1.ServiceControllerClient.port; - assert(port); - assert(typeof port === 'number'); + 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 servicecontrollerModule.v1.ServiceControllerClient( + { universeDomain: 'configured.example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'servicecontrol.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new servicecontrollerModule.v1.ServiceControllerClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new servicecontrollerModule.v1.ServiceControllerClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new servicecontrollerModule.v1.ServiceControllerClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = servicecontrollerModule.v1.ServiceControllerClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new servicecontrollerModule.v1.ServiceControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.serviceControllerStub, undefined); - await client.initialize(); - assert(client.serviceControllerStub); - }); + it('should create a client with no option', () => { + const client = new servicecontrollerModule.v1.ServiceControllerClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new servicecontrollerModule.v1.ServiceControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.serviceControllerStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new servicecontrollerModule.v1.ServiceControllerClient({ + fallback: true, + }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new servicecontrollerModule.v1.ServiceControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.serviceControllerStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new servicecontrollerModule.v1.ServiceControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.serviceControllerStub, undefined); + await client.initialize(); + assert(client.serviceControllerStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new servicecontrollerModule.v1.ServiceControllerClient({ - 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 close method for the initialized client', (done) => { + const client = new servicecontrollerModule.v1.ServiceControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.serviceControllerStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new servicecontrollerModule.v1.ServiceControllerClient({ - 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('has close method for the non-initialized client', (done) => { + const client = new servicecontrollerModule.v1.ServiceControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.serviceControllerStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('check', () => { - it('invokes check without error', async () => { - const client = new servicecontrollerModule.v1.ServiceControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.servicecontrol.v1.CheckRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.servicecontrol.v1.CheckRequest', ['serviceName']); - request.serviceName = defaultValue1; - const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.servicecontrol.v1.CheckResponse() - ); - client.innerApiCalls.check = stubSimpleCall(expectedResponse); - const [response] = await client.check(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.check as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.check 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 servicecontrollerModule.v1.ServiceControllerClient({ + 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 check without error using callback', async () => { - const client = new servicecontrollerModule.v1.ServiceControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.servicecontrol.v1.CheckRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.servicecontrol.v1.CheckRequest', ['serviceName']); - request.serviceName = defaultValue1; - const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.servicecontrol.v1.CheckResponse() - ); - client.innerApiCalls.check = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.check( - request, - (err?: Error|null, result?: protos.google.api.servicecontrol.v1.ICheckResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.check as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.check 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 servicecontrollerModule.v1.ServiceControllerClient({ + 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 check with error', async () => { - const client = new servicecontrollerModule.v1.ServiceControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.servicecontrol.v1.CheckRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.servicecontrol.v1.CheckRequest', ['serviceName']); - request.serviceName = defaultValue1; - const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.check = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.check(request), expectedError); - const actualRequest = (client.innerApiCalls.check as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.check as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('check', () => { + it('invokes check without error', async () => { + const client = new servicecontrollerModule.v1.ServiceControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.servicecontrol.v1.CheckRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.servicecontrol.v1.CheckRequest', + ['serviceName'], + ); + request.serviceName = defaultValue1; + const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.servicecontrol.v1.CheckResponse(), + ); + client.innerApiCalls.check = stubSimpleCall(expectedResponse); + const [response] = await client.check(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.check as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.check as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes check with closed client', async () => { - const client = new servicecontrollerModule.v1.ServiceControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.servicecontrol.v1.CheckRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.servicecontrol.v1.CheckRequest', ['serviceName']); - request.serviceName = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.check(request), expectedError); - }); + it('invokes check without error using callback', async () => { + const client = new servicecontrollerModule.v1.ServiceControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.servicecontrol.v1.CheckRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.servicecontrol.v1.CheckRequest', + ['serviceName'], + ); + request.serviceName = defaultValue1; + const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.servicecontrol.v1.CheckResponse(), + ); + client.innerApiCalls.check = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.check( + request, + ( + err?: Error | null, + result?: protos.google.api.servicecontrol.v1.ICheckResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.check as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.check as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('report', () => { - it('invokes report without error', async () => { - const client = new servicecontrollerModule.v1.ServiceControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.servicecontrol.v1.ReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.servicecontrol.v1.ReportRequest', ['serviceName']); - request.serviceName = defaultValue1; - const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.servicecontrol.v1.ReportResponse() - ); - client.innerApiCalls.report = stubSimpleCall(expectedResponse); - const [response] = await client.report(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.report as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.report as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes check with error', async () => { + const client = new servicecontrollerModule.v1.ServiceControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.servicecontrol.v1.CheckRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.servicecontrol.v1.CheckRequest', + ['serviceName'], + ); + request.serviceName = defaultValue1; + const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.check = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.check(request), expectedError); + const actualRequest = (client.innerApiCalls.check as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.check as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes report without error using callback', async () => { - const client = new servicecontrollerModule.v1.ServiceControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.servicecontrol.v1.ReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.servicecontrol.v1.ReportRequest', ['serviceName']); - request.serviceName = defaultValue1; - const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.servicecontrol.v1.ReportResponse() - ); - client.innerApiCalls.report = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.report( - request, - (err?: Error|null, result?: protos.google.api.servicecontrol.v1.IReportResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.report as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.report as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes check with closed client', async () => { + const client = new servicecontrollerModule.v1.ServiceControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.servicecontrol.v1.CheckRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.servicecontrol.v1.CheckRequest', + ['serviceName'], + ); + request.serviceName = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.check(request), expectedError); + }); + }); - it('invokes report with error', async () => { - const client = new servicecontrollerModule.v1.ServiceControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.servicecontrol.v1.ReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.servicecontrol.v1.ReportRequest', ['serviceName']); - request.serviceName = defaultValue1; - const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.report = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.report(request), expectedError); - const actualRequest = (client.innerApiCalls.report as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.report as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('report', () => { + it('invokes report without error', async () => { + const client = new servicecontrollerModule.v1.ServiceControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.servicecontrol.v1.ReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.servicecontrol.v1.ReportRequest', + ['serviceName'], + ); + request.serviceName = defaultValue1; + const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.servicecontrol.v1.ReportResponse(), + ); + client.innerApiCalls.report = stubSimpleCall(expectedResponse); + const [response] = await client.report(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.report as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.report as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes report with closed client', async () => { - const client = new servicecontrollerModule.v1.ServiceControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.servicecontrol.v1.ReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.servicecontrol.v1.ReportRequest', ['serviceName']); - request.serviceName = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.report(request), expectedError); - }); + it('invokes report without error using callback', async () => { + const client = new servicecontrollerModule.v1.ServiceControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.servicecontrol.v1.ReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.servicecontrol.v1.ReportRequest', + ['serviceName'], + ); + request.serviceName = defaultValue1; + const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.servicecontrol.v1.ReportResponse(), + ); + client.innerApiCalls.report = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.report( + request, + ( + err?: Error | null, + result?: protos.google.api.servicecontrol.v1.IReportResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.report as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.report as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes report with error', async () => { + const client = new servicecontrollerModule.v1.ServiceControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.servicecontrol.v1.ReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.servicecontrol.v1.ReportRequest', + ['serviceName'], + ); + request.serviceName = defaultValue1; + const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.report = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.report(request), expectedError); + const actualRequest = (client.innerApiCalls.report as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.report as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes report with closed client', async () => { + const client = new servicecontrollerModule.v1.ServiceControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.servicecontrol.v1.ReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.servicecontrol.v1.ReportRequest', + ['serviceName'], + ); + request.serviceName = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.report(request), expectedError); }); + }); }); diff --git a/packages/google-api-servicecontrol/test/gapic_service_controller_v2.ts b/packages/google-api-servicecontrol/test/gapic_service_controller_v2.ts index 2af506a1b081..5d8ef0471188 100644 --- a/packages/google-api-servicecontrol/test/gapic_service_controller_v2.ts +++ b/packages/google-api-servicecontrol/test/gapic_service_controller_v2.ts @@ -19,412 +19,496 @@ import * as protos from '../protos/protos'; import * as assert from 'assert'; import * as sinon from 'sinon'; -import {SinonStub} from 'sinon'; -import {describe, it} from 'mocha'; +import { SinonStub } from 'sinon'; +import { describe, it } from 'mocha'; import * as servicecontrollerModule from '../src'; -import {protobuf} from 'google-gax'; +import { protobuf } 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/protos.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/protos.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); } describe('v2.ServiceControllerClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new servicecontrollerModule.v2.ServiceControllerClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'servicecontrol.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new servicecontrollerModule.v2.ServiceControllerClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new servicecontrollerModule.v2.ServiceControllerClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'servicecontrol.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 = servicecontrollerModule.v2.ServiceControllerClient.servicePath; - assert.strictEqual(servicePath, 'servicecontrol.googleapis.com'); - assert(stub.called); - stub.restore(); - }); + it('has universeDomain', () => { + const client = new servicecontrollerModule.v2.ServiceControllerClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = servicecontrollerModule.v2.ServiceControllerClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'servicecontrol.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new servicecontrollerModule.v2.ServiceControllerClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'servicecontrol.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 = + servicecontrollerModule.v2.ServiceControllerClient.servicePath; + assert.strictEqual(servicePath, 'servicecontrol.googleapis.com'); + assert(stub.called); + stub.restore(); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new servicecontrollerModule.v2.ServiceControllerClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'servicecontrol.example.com'); - }); + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + servicecontrollerModule.v2.ServiceControllerClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'servicecontrol.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new servicecontrollerModule.v2.ServiceControllerClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'servicecontrol.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 servicecontrollerModule.v2.ServiceControllerClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'servicecontrol.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new servicecontrollerModule.v2.ServiceControllerClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'servicecontrol.example.com'); + }); - 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 servicecontrollerModule.v2.ServiceControllerClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'servicecontrol.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 servicecontrollerModule.v2.ServiceControllerClient({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 servicecontrollerModule.v2.ServiceControllerClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'servicecontrol.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - it('has port', () => { - const port = servicecontrollerModule.v2.ServiceControllerClient.port; - assert(port); - assert(typeof port === 'number'); + 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 servicecontrollerModule.v2.ServiceControllerClient( + { universeDomain: 'configured.example.com' }, + ); + const servicePath = client.apiEndpoint; + assert.strictEqual( + servicePath, + 'servicecontrol.configured.example.com', + ); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } }); - - it('should create a client with no option', () => { - const client = new servicecontrollerModule.v2.ServiceControllerClient(); - assert(client); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new servicecontrollerModule.v2.ServiceControllerClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('should create a client with gRPC fallback', () => { - const client = new servicecontrollerModule.v2.ServiceControllerClient({ - fallback: true, - }); - assert(client); - }); + it('has port', () => { + const port = servicecontrollerModule.v2.ServiceControllerClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new servicecontrollerModule.v2.ServiceControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.serviceControllerStub, undefined); - await client.initialize(); - assert(client.serviceControllerStub); - }); + it('should create a client with no option', () => { + const client = new servicecontrollerModule.v2.ServiceControllerClient(); + assert(client); + }); - it('has close method for the initialized client', done => { - const client = new servicecontrollerModule.v2.ServiceControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.serviceControllerStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('should create a client with gRPC fallback', () => { + const client = new servicecontrollerModule.v2.ServiceControllerClient({ + fallback: true, + }); + assert(client); + }); - it('has close method for the non-initialized client', done => { - const client = new servicecontrollerModule.v2.ServiceControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.serviceControllerStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new servicecontrollerModule.v2.ServiceControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.serviceControllerStub, undefined); + await client.initialize(); + assert(client.serviceControllerStub); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new servicecontrollerModule.v2.ServiceControllerClient({ - 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 close method for the initialized client', (done) => { + const client = new servicecontrollerModule.v2.ServiceControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.initialize().catch((err) => { + throw err; + }); + assert(client.serviceControllerStub); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new servicecontrollerModule.v2.ServiceControllerClient({ - 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('has close method for the non-initialized client', (done) => { + const client = new servicecontrollerModule.v2.ServiceControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.serviceControllerStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch((err) => { + throw err; }); }); - describe('check', () => { - it('invokes check without error', async () => { - const client = new servicecontrollerModule.v2.ServiceControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.servicecontrol.v2.CheckRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.servicecontrol.v2.CheckRequest', ['serviceName']); - request.serviceName = defaultValue1; - const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.servicecontrol.v2.CheckResponse() - ); - client.innerApiCalls.check = stubSimpleCall(expectedResponse); - const [response] = await client.check(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.check as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.check 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 servicecontrollerModule.v2.ServiceControllerClient({ + 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 check without error using callback', async () => { - const client = new servicecontrollerModule.v2.ServiceControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.servicecontrol.v2.CheckRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.servicecontrol.v2.CheckRequest', ['serviceName']); - request.serviceName = defaultValue1; - const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.servicecontrol.v2.CheckResponse() - ); - client.innerApiCalls.check = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.check( - request, - (err?: Error|null, result?: protos.google.api.servicecontrol.v2.ICheckResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.check as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.check 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 servicecontrollerModule.v2.ServiceControllerClient({ + 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 check with error', async () => { - const client = new servicecontrollerModule.v2.ServiceControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.servicecontrol.v2.CheckRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.servicecontrol.v2.CheckRequest', ['serviceName']); - request.serviceName = defaultValue1; - const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.check = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.check(request), expectedError); - const actualRequest = (client.innerApiCalls.check as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.check as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('check', () => { + it('invokes check without error', async () => { + const client = new servicecontrollerModule.v2.ServiceControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.servicecontrol.v2.CheckRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.servicecontrol.v2.CheckRequest', + ['serviceName'], + ); + request.serviceName = defaultValue1; + const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.servicecontrol.v2.CheckResponse(), + ); + client.innerApiCalls.check = stubSimpleCall(expectedResponse); + const [response] = await client.check(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.check as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.check as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes check with closed client', async () => { - const client = new servicecontrollerModule.v2.ServiceControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.servicecontrol.v2.CheckRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.servicecontrol.v2.CheckRequest', ['serviceName']); - request.serviceName = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.check(request), expectedError); - }); + it('invokes check without error using callback', async () => { + const client = new servicecontrollerModule.v2.ServiceControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.servicecontrol.v2.CheckRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.servicecontrol.v2.CheckRequest', + ['serviceName'], + ); + request.serviceName = defaultValue1; + const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.servicecontrol.v2.CheckResponse(), + ); + client.innerApiCalls.check = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.check( + request, + ( + err?: Error | null, + result?: protos.google.api.servicecontrol.v2.ICheckResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.check as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.check as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('report', () => { - it('invokes report without error', async () => { - const client = new servicecontrollerModule.v2.ServiceControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.servicecontrol.v2.ReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.servicecontrol.v2.ReportRequest', ['serviceName']); - request.serviceName = defaultValue1; - const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.servicecontrol.v2.ReportResponse() - ); - client.innerApiCalls.report = stubSimpleCall(expectedResponse); - const [response] = await client.report(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.report as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.report as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes check with error', async () => { + const client = new servicecontrollerModule.v2.ServiceControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.servicecontrol.v2.CheckRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.servicecontrol.v2.CheckRequest', + ['serviceName'], + ); + request.serviceName = defaultValue1; + const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.check = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.check(request), expectedError); + const actualRequest = (client.innerApiCalls.check as SinonStub).getCall(0) + .args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.check as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes report without error using callback', async () => { - const client = new servicecontrollerModule.v2.ServiceControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.servicecontrol.v2.ReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.servicecontrol.v2.ReportRequest', ['serviceName']); - request.serviceName = defaultValue1; - const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.api.servicecontrol.v2.ReportResponse() - ); - client.innerApiCalls.report = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.report( - request, - (err?: Error|null, result?: protos.google.api.servicecontrol.v2.IReportResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.report as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.report as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes check with closed client', async () => { + const client = new servicecontrollerModule.v2.ServiceControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.servicecontrol.v2.CheckRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.servicecontrol.v2.CheckRequest', + ['serviceName'], + ); + request.serviceName = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.check(request), expectedError); + }); + }); - it('invokes report with error', async () => { - const client = new servicecontrollerModule.v2.ServiceControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.servicecontrol.v2.ReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.servicecontrol.v2.ReportRequest', ['serviceName']); - request.serviceName = defaultValue1; - const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.report = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.report(request), expectedError); - const actualRequest = (client.innerApiCalls.report as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.report as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('report', () => { + it('invokes report without error', async () => { + const client = new servicecontrollerModule.v2.ServiceControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.servicecontrol.v2.ReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.servicecontrol.v2.ReportRequest', + ['serviceName'], + ); + request.serviceName = defaultValue1; + const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.servicecontrol.v2.ReportResponse(), + ); + client.innerApiCalls.report = stubSimpleCall(expectedResponse); + const [response] = await client.report(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.report as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.report as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes report with closed client', async () => { - const client = new servicecontrollerModule.v2.ServiceControllerClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.api.servicecontrol.v2.ReportRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.api.servicecontrol.v2.ReportRequest', ['serviceName']); - request.serviceName = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.report(request), expectedError); - }); + it('invokes report without error using callback', async () => { + const client = new servicecontrollerModule.v2.ServiceControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.servicecontrol.v2.ReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.servicecontrol.v2.ReportRequest', + ['serviceName'], + ); + request.serviceName = defaultValue1; + const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.api.servicecontrol.v2.ReportResponse(), + ); + client.innerApiCalls.report = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.report( + request, + ( + err?: Error | null, + result?: protos.google.api.servicecontrol.v2.IReportResponse | null, + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }, + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.report as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.report as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes report with error', async () => { + const client = new servicecontrollerModule.v2.ServiceControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.servicecontrol.v2.ReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.servicecontrol.v2.ReportRequest', + ['serviceName'], + ); + request.serviceName = defaultValue1; + const expectedHeaderRequestParams = `service_name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.report = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.report(request), expectedError); + const actualRequest = (client.innerApiCalls.report as SinonStub).getCall( + 0, + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.report as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes report with closed client', async () => { + const client = new servicecontrollerModule.v2.ServiceControllerClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.api.servicecontrol.v2.ReportRequest(), + ); + const defaultValue1 = getTypeDefaultValue( + '.google.api.servicecontrol.v2.ReportRequest', + ['serviceName'], + ); + request.serviceName = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch((err) => { + throw err; + }); + await assert.rejects(client.report(request), expectedError); }); + }); }); diff --git a/packages/google-api-servicecontrol/webpack.config.js b/packages/google-api-servicecontrol/webpack.config.js index bc7e42870005..a206a37ea7a6 100644 --- a/packages/google-api-servicecontrol/webpack.config.js +++ b/packages/google-api-servicecontrol/webpack.config.js @@ -1,4 +1,4 @@ -// Copyright 2026 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/packages/google-api-servicemanagement/.eslintignore b/packages/google-api-servicemanagement/.eslintignore new file mode 100644 index 000000000000..cfc348ec4d11 --- /dev/null +++ b/packages/google-api-servicemanagement/.eslintignore @@ -0,0 +1,7 @@ +**/node_modules +**/.coverage +build/ +docs/ +protos/ +system-test/ +samples/generated/ diff --git a/packages/google-api-servicemanagement/.eslintrc.json b/packages/google-api-servicemanagement/.eslintrc.json new file mode 100644 index 000000000000..3e8d97ccb390 --- /dev/null +++ b/packages/google-api-servicemanagement/.eslintrc.json @@ -0,0 +1,4 @@ +{ + "extends": "./node_modules/gts", + "root": true +} diff --git a/packages/google-api-servicemanagement/README.md b/packages/google-api-servicemanagement/README.md index 87274991e7e8..15a23e095865 100644 --- a/packages/google-api-servicemanagement/README.md +++ b/packages/google-api-servicemanagement/README.md @@ -105,7 +105,7 @@ More Information: [Google Cloud Platform Launch Stages][launch_stages] ## Contributing -Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-api-servicemanagement/CONTRIBUTING.md). +Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/google-cloud-node/blob/main/CONTRIBUTING.md). Please note that this `README.md` and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`) @@ -115,7 +115,7 @@ are generated from a central template. Apache Version 2.0 -See [LICENSE](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-api-servicemanagement/LICENSE) +See [LICENSE](https://github.com/googleapis/google-cloud-node/blob/main/LICENSE) [shell_img]: https://gstatic.com/cloudssh/images/open-btn.png [projects]: https://console.cloud.google.com/project diff --git a/packages/google-api-servicemanagement/protos/protos.d.ts b/packages/google-api-servicemanagement/protos/protos.d.ts index fde978c7586f..3e5641a1b54a 100644 --- a/packages/google-api-servicemanagement/protos/protos.d.ts +++ b/packages/google-api-servicemanagement/protos/protos.d.ts @@ -4216,6 +4216,9 @@ export namespace google { /** CommonLanguageSettings destinations */ destinations?: (google.api.ClientLibraryDestination[]|null); + + /** CommonLanguageSettings selectiveGapicGeneration */ + selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); } /** Represents a CommonLanguageSettings. */ @@ -4233,6 +4236,9 @@ export namespace google { /** CommonLanguageSettings destinations. */ public destinations: google.api.ClientLibraryDestination[]; + /** CommonLanguageSettings selectiveGapicGeneration. */ + public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); + /** * Creates a new CommonLanguageSettings instance using the specified properties. * @param [properties] Properties to set @@ -4933,6 +4939,9 @@ export namespace google { /** PythonSettings common */ common?: (google.api.ICommonLanguageSettings|null); + + /** PythonSettings experimentalFeatures */ + experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); } /** Represents a PythonSettings. */ @@ -4947,6 +4956,9 @@ export namespace google { /** PythonSettings common. */ public common?: (google.api.ICommonLanguageSettings|null); + /** PythonSettings experimentalFeatures. */ + public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); + /** * Creates a new PythonSettings instance using the specified properties. * @param [properties] Properties to set @@ -5025,6 +5037,118 @@ 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); + + /** ExperimentalFeatures unversionedPackageDisabled */ + unversionedPackageDisabled?: (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; + + /** ExperimentalFeatures unversionedPackageDisabled. */ + public unversionedPackageDisabled: boolean; + + /** + * Creates a new ExperimentalFeatures instance using the specified properties. + * @param [properties] Properties to set + * @returns ExperimentalFeatures instance + */ + public static create(properties?: google.api.PythonSettings.IExperimentalFeatures): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Encodes the specified ExperimentalFeatures message. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @param message ExperimentalFeatures message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.PythonSettings.IExperimentalFeatures, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified ExperimentalFeatures message, length delimited. Does not implicitly {@link google.api.PythonSettings.ExperimentalFeatures.verify|verify} messages. + * @param message ExperimentalFeatures message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.PythonSettings.IExperimentalFeatures, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Decodes an ExperimentalFeatures message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns ExperimentalFeatures + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.PythonSettings.ExperimentalFeatures; + + /** + * Verifies an ExperimentalFeatures message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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 { @@ -5351,6 +5475,9 @@ export namespace google { /** GoSettings common */ common?: (google.api.ICommonLanguageSettings|null); + + /** GoSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); } /** Represents a GoSettings. */ @@ -5365,6 +5492,9 @@ export namespace google { /** GoSettings common. */ public common?: (google.api.ICommonLanguageSettings|null); + /** GoSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + /** * Creates a new GoSettings instance using the specified properties. * @param [properties] Properties to set @@ -5689,6 +5819,109 @@ export namespace google { PACKAGE_MANAGER = 20 } + /** 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 new SelectiveGapicGeneration instance using the specified properties. + * @param [properties] Properties to set + * @returns SelectiveGapicGeneration instance + */ + public static create(properties?: google.api.ISelectiveGapicGeneration): google.api.SelectiveGapicGeneration; + + /** + * Encodes the specified SelectiveGapicGeneration message. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @param message SelectiveGapicGeneration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.api.ISelectiveGapicGeneration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified SelectiveGapicGeneration message, length delimited. Does not implicitly {@link google.api.SelectiveGapicGeneration.verify|verify} messages. + * @param message SelectiveGapicGeneration message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.api.ISelectiveGapicGeneration, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.SelectiveGapicGeneration; + + /** + * Decodes a SelectiveGapicGeneration message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns SelectiveGapicGeneration + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.SelectiveGapicGeneration; + + /** + * Verifies a SelectiveGapicGeneration message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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. */ enum LaunchStage { LAUNCH_STAGE_UNSPECIFIED = 0, @@ -8700,6 +8933,9 @@ export namespace google { /** MetricDescriptorMetadata ingestDelay */ ingestDelay?: (google.protobuf.IDuration|null); + + /** MetricDescriptorMetadata timeSeriesResourceHierarchyLevel */ + timeSeriesResourceHierarchyLevel?: (google.api.MetricDescriptor.MetricDescriptorMetadata.TimeSeriesResourceHierarchyLevel[]|null); } /** Represents a MetricDescriptorMetadata. */ @@ -8720,6 +8956,9 @@ export namespace google { /** MetricDescriptorMetadata ingestDelay. */ public ingestDelay?: (google.protobuf.IDuration|null); + /** MetricDescriptorMetadata timeSeriesResourceHierarchyLevel. */ + public timeSeriesResourceHierarchyLevel: google.api.MetricDescriptor.MetricDescriptorMetadata.TimeSeriesResourceHierarchyLevel[]; + /** * Creates a new MetricDescriptorMetadata instance using the specified properties. * @param [properties] Properties to set @@ -8797,6 +9036,17 @@ export namespace google { */ public static getTypeUrl(typeUrlPrefix?: string): string; } + + namespace MetricDescriptorMetadata { + + /** TimeSeriesResourceHierarchyLevel enum. */ + enum TimeSeriesResourceHierarchyLevel { + TIME_SERIES_RESOURCE_HIERARCHY_LEVEL_UNSPECIFIED = 0, + PROJECT = 1, + ORGANIZATION = 2, + FOLDER = 3 + } + } } /** Properties of a Metric. */ @@ -10529,6 +10779,7 @@ export namespace google { /** Edition enum. */ enum Edition { EDITION_UNKNOWN = 0, + EDITION_LEGACY = 900, EDITION_PROTO2 = 998, EDITION_PROTO3 = 999, EDITION_2023 = 1000, @@ -10559,6 +10810,9 @@ export namespace google { /** FileDescriptorProto weakDependency */ weakDependency?: (number[]|null); + /** FileDescriptorProto optionDependency */ + optionDependency?: (string[]|null); + /** FileDescriptorProto messageType */ messageType?: (google.protobuf.IDescriptorProto[]|null); @@ -10608,6 +10862,9 @@ export namespace google { /** FileDescriptorProto weakDependency. */ public weakDependency: number[]; + /** FileDescriptorProto optionDependency. */ + public optionDependency: string[]; + /** FileDescriptorProto messageType. */ public messageType: google.protobuf.IDescriptorProto[]; @@ -10742,6 +10999,9 @@ export namespace google { /** DescriptorProto reservedName */ reservedName?: (string[]|null); + + /** DescriptorProto visibility */ + visibility?: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility|null); } /** Represents a DescriptorProto. */ @@ -10783,6 +11043,9 @@ export namespace google { /** DescriptorProto reservedName. */ public reservedName: string[]; + /** DescriptorProto visibility. */ + public visibility: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility); + /** * Creates a new DescriptorProto instance using the specified properties. * @param [properties] Properties to set @@ -11630,6 +11893,9 @@ export namespace google { /** EnumDescriptorProto reservedName */ reservedName?: (string[]|null); + + /** EnumDescriptorProto visibility */ + visibility?: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility|null); } /** Represents an EnumDescriptorProto. */ @@ -11656,6 +11922,9 @@ export namespace google { /** EnumDescriptorProto reservedName. */ public reservedName: string[]; + /** EnumDescriptorProto visibility. */ + public visibility: (google.protobuf.SymbolVisibility|keyof typeof google.protobuf.SymbolVisibility); + /** * Creates a new EnumDescriptorProto instance using the specified properties. * @param [properties] Properties to set @@ -12584,6 +12853,9 @@ 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); @@ -12639,6 +12911,9 @@ 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[]; @@ -12859,6 +13134,121 @@ export namespace google { */ public static getTypeUrl(typeUrlPrefix?: string): string; } + + /** Properties of a FeatureSupport. */ + interface IFeatureSupport { + + /** FeatureSupport editionIntroduced */ + editionIntroduced?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + + /** FeatureSupport editionDeprecated */ + editionDeprecated?: (google.protobuf.Edition|keyof typeof google.protobuf.Edition|null); + + /** FeatureSupport deprecationWarning */ + deprecationWarning?: (string|null); + + /** FeatureSupport editionRemoved */ + editionRemoved?: (google.protobuf.Edition|keyof typeof 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|keyof typeof google.protobuf.Edition); + + /** FeatureSupport editionDeprecated. */ + public editionDeprecated: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** FeatureSupport deprecationWarning. */ + public deprecationWarning: string; + + /** FeatureSupport editionRemoved. */ + public editionRemoved: (google.protobuf.Edition|keyof typeof google.protobuf.Edition); + + /** + * Creates a new FeatureSupport instance using the specified properties. + * @param [properties] Properties to set + * @returns FeatureSupport instance + */ + public static create(properties?: google.protobuf.FieldOptions.IFeatureSupport): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Encodes the specified FeatureSupport message. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @param message FeatureSupport message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.FieldOptions.IFeatureSupport, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified FeatureSupport message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.FeatureSupport.verify|verify} messages. + * @param message FeatureSupport message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.FieldOptions.IFeatureSupport, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Decodes a FeatureSupport message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns FeatureSupport + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldOptions.FeatureSupport; + + /** + * Verifies a FeatureSupport message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * 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. */ @@ -13097,6 +13487,9 @@ export namespace google { /** EnumValueOptions debugRedact */ debugRedact?: (boolean|null); + /** EnumValueOptions featureSupport */ + featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); + /** EnumValueOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } @@ -13119,6 +13512,9 @@ export namespace google { /** EnumValueOptions debugRedact. */ public debugRedact: boolean; + /** EnumValueOptions featureSupport. */ + public featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); + /** EnumValueOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -13714,6 +14110,12 @@ export namespace google { /** FeatureSet jsonFormat */ jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|keyof typeof google.protobuf.FeatureSet.JsonFormat|null); + + /** FeatureSet enforceNamingStyle */ + enforceNamingStyle?: (google.protobuf.FeatureSet.EnforceNamingStyle|keyof typeof google.protobuf.FeatureSet.EnforceNamingStyle|null); + + /** FeatureSet defaultSymbolVisibility */ + defaultSymbolVisibility?: (google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|keyof typeof google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|null); } /** Represents a FeatureSet. */ @@ -13743,6 +14145,12 @@ export namespace google { /** FeatureSet jsonFormat. */ public jsonFormat: (google.protobuf.FeatureSet.JsonFormat|keyof typeof google.protobuf.FeatureSet.JsonFormat); + /** FeatureSet enforceNamingStyle. */ + public enforceNamingStyle: (google.protobuf.FeatureSet.EnforceNamingStyle|keyof typeof google.protobuf.FeatureSet.EnforceNamingStyle); + + /** FeatureSet defaultSymbolVisibility. */ + public defaultSymbolVisibility: (google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility|keyof typeof google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility); + /** * Creates a new FeatureSet instance using the specified properties. * @param [properties] Properties to set @@ -13865,6 +14273,116 @@ export namespace google { ALLOW = 1, LEGACY_BEST_EFFORT = 2 } + + /** EnforceNamingStyle enum. */ + enum EnforceNamingStyle { + ENFORCE_NAMING_STYLE_UNKNOWN = 0, + STYLE2024 = 1, + STYLE_LEGACY = 2 + } + + /** Properties of a VisibilityFeature. */ + interface IVisibilityFeature { + } + + /** Represents a VisibilityFeature. */ + class VisibilityFeature implements IVisibilityFeature { + + /** + * Constructs a new VisibilityFeature. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FeatureSet.IVisibilityFeature); + + /** + * Creates a new VisibilityFeature instance using the specified properties. + * @param [properties] Properties to set + * @returns VisibilityFeature instance + */ + public static create(properties?: google.protobuf.FeatureSet.IVisibilityFeature): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Encodes the specified VisibilityFeature message. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @param message VisibilityFeature message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encode(message: google.protobuf.FeatureSet.IVisibilityFeature, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Encodes the specified VisibilityFeature message, length delimited. Does not implicitly {@link google.protobuf.FeatureSet.VisibilityFeature.verify|verify} messages. + * @param message VisibilityFeature message or plain object to encode + * @param [writer] Writer to encode to + * @returns Writer + */ + public static encodeDelimited(message: google.protobuf.FeatureSet.IVisibilityFeature, writer?: $protobuf.Writer): $protobuf.Writer; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer. + * @param reader Reader or buffer to decode from + * @param [length] Message length if known beforehand + * @returns VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Decodes a VisibilityFeature message from the specified reader or buffer, length delimited. + * @param reader Reader or buffer to decode from + * @returns VisibilityFeature + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {$protobuf.util.ProtocolError} If required fields are missing + */ + public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Verifies a VisibilityFeature message. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a VisibilityFeature message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns VisibilityFeature + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet.VisibilityFeature; + + /** + * Creates a plain object from a VisibilityFeature message. Also converts values to other types if specified. + * @param message VisibilityFeature + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet.VisibilityFeature, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this VisibilityFeature to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for VisibilityFeature + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The defau{"code":"deadline_exceeded","msg":"operation timed out"}